gestione gare pubbliche
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.
 
 
 
 
 

966 righe
34 KiB

<?php
use \Studioamica\OidcClient\Utils\Config as OIDC_Config;
class Ente {
public $codice;
public $moduli;
public $excludeConnector;
private $info;
private $root;
private $dbName;
private $config;
public $printUfficio;
public $erpConnector;
public static $frontOfficeRequest;
private static PDOStatement $insertPreservationStatement;
private static PDOStatement $checkPreservationStatement;
/**
* Query initialization
*
* @var bool
*/
private static bool $queryInitialized = false;
public function __construct() {
global $root, $config, $pdo;
$this->root = $root;
$this->excludeConnector = false;
$this->printUfficio = true;
$this->config = &$config;
}
/**
* Inizializza le varibili statiche
*
* @return void
*/
private static function setup() : void
{
// Inizlializzo le query
global $pdo;
if (!self::$queryInitialized) {
self::$insertPreservationStatement = $pdo->prepare("INSERT INTO b_conservazione (`modulo`, `codice_elemento`, `codice_ente`, `tipologia`, `titolo`, `timestamp_esecuzione`, `utente_modifica`, `timestamp_creazione`) VALUES (:modulo, :codice_elemento, :codice_ente, :tipologia, :titolo, :timestamp_esecuzione, :utente_modifica, :timestamp_creazione)");
self::$checkPreservationStatement = $pdo->prepare("SELECT codice FROM b_conservazione WHERE codice_elemento = :codice_elemento AND modulo = :modulo");
self::$queryInitialized = true;
}
}
/**
* Ottieni tutti i moduli attivi per l'ente selezionato
*
* @param Int $ente Codice Ente
* @return Array|null Array moduli attivi
*/
public static function getModuli(Int $ente) : ?Array
{
global $pdo;
return $pdo->go("SELECT id_modulo FROM r_moduli_ente WHERE cod_ente = :cod_ente", [":cod_ente" => $ente])->fetchAll(PDO::FETCH_COLUMN, 0);
}
public function hasModulo($radice) {
if (!empty($this->moduli[$radice])) {
return true;
}
return false;
}
public function checkSPID() {
return $this->getInfo()["spid"] == "S" && ($this->info["indice_spid"] === "0" || $this->info["indice_spid"] > 0);
}
public function checkOIDC() {
return $this->getInfo()["oidc"] == "S";
}
public static function getContributiSUA($codice,$importo = null) {
$ente = self::getInfoFromID($codice)[0] ?? null;
$return = [];
if (!empty($ente["contributo_sua"])) {
global $pdo;
$sql = "SELECT * FROM r_contributi_sua WHERE codice_ente = :codice";
$bind = [":codice"=>$codice];
if (isset($importo)) {
$bind[":importo"] = $importo;
$sql .= " AND minimo <= :importo AND (massimo > :importo OR massimo = 0) ";
}
$quote = $pdo->go($sql,$bind);
if (!empty($quote->rowCount())) {
$return = ["tipo"=>$ente["contributo_sua"],"all"=>(empty($ente["tipo_contributo_sua"])),"quote"=>[]];
while($quota = $quote->fetch(PDO::FETCH_ASSOC)) {
$return["quote"][] = $quota;
}
}
}
return $return;
}
private function setSpecificDB($root = false) {
$user = $this->config["db_user"];
$pass = $this->config["db_pass"];
if ($root) {
$user = $this->config["db_root_user"];
$pass = $this->config["db_root_pass"];
}
return new myPDO($this->config["db_host"],$user,$pass,$this->dbName, $this->config['socket']);
}
public function getDbName() {
return $this->dbName;
}
public static function validateDomainForTenant(String $domain) {
$re = '/^[a-z0-9\-\.]+\.[a-z0-9\-]+\.[\a-z0-9]{2,6}$/';
return preg_match($re,$domain);
}
private function initDB() {
if (!empty($this->config["prefix_db"])) {
if ($this->config["developEnv"]) {
$rootPdo = new myPDO($this->config["db_host"],$this->config["db_root_user"],$this->config["db_root_pass"],$this->config["db_name"], $this->config['socket']);
$rootPdo->switch = false;
$pdoEnte = $this->setSpecificDB();
$mainTables = $rootPdo->go("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
$enteTables = $pdoEnte->go("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
$posArray = array_search("a_migrazioni",$enteTables);
if ($posArray !== false) {
unset($enteTables[$posArray]);
$enteTables = array_values($enteTables);
}
$fileManagerIndex = array_search("b_filemanager", $enteTables);
if($fileManagerIndex !== false) {
$enteTables[$fileManagerIndex] = "b_fileManager";
}
file_put_contents($this->config["first_level"]."/enti/enteTables.json",json_encode($enteTables,JSON_PRETTY_PRINT));
$intersect = array_intersect($mainTables,$enteTables);
if (empty($intersect)) {
return true;
}
} else {
return true;
}
}
return false;
}
/**
* Carica uno od una lista di enti compatibili con i filtri richiesti
*
* @return array
*/
public static function fetchEnti(array $fields = ["*"], array $filters = [], bool $multiple = true): array
{
$fields = array_filter($fields, function($field) {
if($field === "*") return true;
if(!myPDO::validFieldName($field)) {
throw new Exception("Invalid field name {$field}");
}
return true;
}, ARRAY_FILTER_USE_BOTH);
global $pdo;
if(empty($filters["attivo"]))
$filters["attivo"] = "S";
$fields_str = implode(",", $fields);
$bind = [];
$filter_str = [];
// Per ogni filtro, lo aggiungiamo nei bind e nella query
foreach ($filters as $field => $value) {
if(!myPDO::validFieldName($field)) {
throw new Exception("Invalid field name {$field}");
}
$operand = "=";
if (is_array($value)) {
$operand = $value[0];
$value = $value[1];
}
$bind[":{$field}"] = $value;
$filter_str[] = "`{$field}` $operand :{$field}";
}
// Ricostruiamo la query where
if (!empty($filter_str)) {
$filter_str = "WHERE " . implode(" AND ", $filter_str);
} else {
$filter_str = "";
}
$limit_str = "";
if (!$multiple) {
$limit_str = "LIMIT 1";
}
$sql = "SELECT {$fields_str} FROM b_enti {$filter_str} ORDER BY `codice`, `timestamp` ASC {$limit_str}";
$result = $pdo->go($sql, $bind);
$enti = $multiple ? $result->fetchAll(PDO::FETCH_ASSOC) : $result->fetch(PDO::FETCH_ASSOC);
if (!is_array($enti)) {
return [];
}
return $enti;
}
public function init($search) {
global $pdo;
global $config;
global $root;
if (!empty($search)) {
$where_clause = "AND attivo = 'S'";
if(defined("__CMDS_JOB_EXEC") && __CMDS_JOB_EXEC) { $where_clause = ""; }
$sql = "SELECT * FROM b_enti WHERE dominio = :search {$where_clause}";
$ris = $pdo->go($sql,array(":search"=>$search));
if ($ris->rowCount() === 1) {
$this->info = $ris->fetch(PDO::FETCH_ASSOC);
$this->codice = $this->info["codice"];
if (!empty($config["moduli"])) {
$ris = $pdo->prepare("SELECT * FROM r_moduli_ente WHERE id_modulo = :id_modulo AND cod_ente = :codice_ente ");
$ris->bindValue(":codice_ente",$this->codice);
$this->moduli = [];
foreach($config["moduli"] AS $radice => $modulo) {
$insert = false;
if ($modulo["ente"]) {
if ($modulo["all_ente"]) {
$insert= true;
} else {
$ris->bindValue(":id_modulo",$radice);
$ris->execute();
if ($ris->rowCount() > 0) {
$insert = true;
}
}
if ($insert) { $this->moduli[$radice] = $modulo; }
}
if ($modulo["tipo"] == "integrazione") {
Integrazione::loadIntegration($modulo, $this);
}
}
}
$this->dbName = $this->config["prefix_db"] . "_ente" . $this->codice;
$this->printUfficio = (settingsManager::getValue("beneficiarioUfficioAreaPubblica",$this->codice) == "S");
$erpConnectorPath = $this->getExtensionPath() . DIRECTORY_SEPARATOR . "connectorErp.class.php";
if (file_exists($erpConnectorPath) && !$this->excludeConnector) {
include_once $erpConnectorPath;
if (class_exists("ConnectorERP")) {
$this->erpConnector = new ConnectorERP();
}
}
if ($this->initDB()) {
return true;
}
}
}
return false;
}
/**
* Get
*
* @param mixed $chiave
* @param mixed $valore
* @return Array
*/
public static function tipologieEnte($chiave = "attivo", $valore = "S") : ?Array {
global $config;
if(file_exists("{$config["jsonFolder"]}/enti-tipologie.json")) {
$tipologie = jsonToArray("{$config["jsonFolder"]}/enti-tipologie.json");
if (!empty($chiave) && !empty($valore)) {
$tipologie = array_filter($tipologie, function($value) use ($chiave, $valore) {
return $value[$chiave] == $valore;
});
}
return $tipologie;
}
return null;
}
public static function tipoAttivita($chiave="attivo",$valore="S") {
$return = [];
$return[] = ["codice"=>1,"tag"=>"GENERAL_PUBLIC_SERVICES","value"=>"Servizi generali delle amministrazioni pubbliche","attivo"=>"S","eliminato"=>"N"];
$return[] = ["codice"=>2,"tag"=>"SOCIAL_PROTECTION","value"=>"Protezione Sociale","attivo"=>"S","eliminato"=>"N"];
$return[] = ["codice"=>3,"tag"=>"EDUCATION","value"=>"Istruzione","attivo"=>"S","eliminato"=>"N"];
$return[] = ["codice"=>4,"tag"=>"HEALTH","value"=>"Salute","attivo"=>"S","eliminato"=>"N"];
$return[] = ["codice"=>5,"tag"=>"ENVIRONMENT","value"=>"Ambiente","attivo"=>"S","eliminato"=>"N"];
$return[] = ["codice"=>6,"tag"=>"PUBLIC_ORDER_AND_SAFETY","value"=>"Ordine pubblico e sicurezza","attivo"=>"S","eliminato"=>"N"];
$return[] = ["codice"=>7,"tag"=>"HOUSING_AND_COMMUNITY_AMENITIES","value"=>"Abitazioni e assetto territoriale","attivo"=>"S","eliminato"=>"N"];
$return[] = ["codice"=>8,"tag"=>"DEFENCE","value"=>"Difesa","attivo"=>"S","eliminato"=>"N"];
$return[] = ["codice"=>9,"tag"=>"ECONOMIC_AND_FINANCIAL_AFFAIRS","value"=>"Affari economici e finanziari","attivo"=>"S","eliminato"=>"N"];
$return[] = ["codice"=>10,"tag"=>"RECREATION_CULTURE_AND_RELIGION","value"=>"Servizi ricreativi, cultura e religione","attivo"=>"S","eliminato"=>"N"];
if (!empty($chiave) && !empty($valore)) {
$tmp = [];
foreach($return AS $element) {
if ($element[$chiave] == $valore) { $tmp[] = $element; }
}
$return = $tmp;
}
return $return;
}
public static function entiAggregatiFromID($codice,bool $includePrivati = true) {
global $pdo;
$sql = "";
if (!$includePrivati) {
$sql .= " AND soggettoPrivato = 'N'";
}
$enti = $pdo->go("SELECT * FROM b_enti WHERE sua = :codice {$sql}",[":codice"=>$codice]);
if ($enti->rowCount() > 0) {
$return = [];
while($ente = $enti->fetch(PDO::FETCH_ASSOC)) {
$return[$ente["codice"]] = $ente;
}
return $return;
}
return [];
}
public function entiAggregati(bool $includePrivati = true) {
return self::entiAggregatiFromID($this->codice,$includePrivati);
}
public function entiBeneficiari(bool $includePrivati = true) {
$return = $this->entiAggregati($includePrivati);
if (!$this->printUfficio && self::$frontOfficeRequest) {
$tmp = [];
foreach($return AS $ente) {
if ($ente["ufficio"] == "S") {
$ente["denominazione"] = $this->info["denominazione"];
}
$tmp[$ente["codice"]] = $ente;
}
$return = $tmp;
}
$return[$this->codice] = $this->getInfo();
return $return;
}
public function check() {
global $pdo;
$where_clause = "AND attivo = 'S'";
if(defined("__CMDS_JOB_EXEC") && __CMDS_JOB_EXEC) { $where_clause = ""; }
$sql = "SELECT * FROM b_enti WHERE codice = :codice {$where_clause}";
$ris = $pdo->go($sql,array(":codice"=>$this->codice));
if ($ris->rowCount() === 1) {
$this->info = $ris->fetch(PDO::FETCH_ASSOC);
$this->codice = $this->info["codice"];
$_SESSION["ente"] = $this;
} else {
session_destroy();
echo '<meta http-equiv="refresh" content="0;URL=/index.php">';
die();
}
}
public function certificazioneManualeUtenti() {
return settingsManager::getValue("certificazioneUtenze",$this->codice) == "S";
}
public function getInfo() {
return $this->info;
}
public static function getSize(int $ente):?int {
global $config;
$f = $config["mediaFolder"] . DIRECTORY_SEPARATOR . $ente;
return folderSize($f);
}
/**
* Verifica se l'elemento del modulo è conservabile
*
* @param mixed $modulo
* @param mixed $codice
* @param mixed $stato
* @return Boolean
*/
public function checkConservazione(string $modulo, int $codice, int $stato, int $codice_ente) : bool
{
self::setup();
global $pdo, $config;
self::$checkPreservationStatement->bindValue(":codice_elemento", $codice);
self::$insertPreservationStatement->bindValue(":codice_elemento", $codice);
self::$insertPreservationStatement->bindValue(":codice_ente", $_SESSION["utente"]->codice_ente ?? ($_SESSION["ente"]->codice ?? $codice_ente));
switch($modulo) {
case 'gare':
$stati = gara::getStati();
self::$checkPreservationStatement->bindValue(":modulo", $modulo);
self::$insertPreservationStatement->bindValue(":modulo", $modulo);
self::$insertPreservationStatement->bindValue(":titolo", "FASCICOLO GARA #{$codice} - " . date('d/m/Y H:i'));
break;
case 'stipula':
$stati = stipula::getStati();
self::$checkPreservationStatement->bindValue(":modulo", "contratti");
self::$insertPreservationStatement->bindValue(":modulo", "contratti");
self::$insertPreservationStatement->bindValue(":titolo", "FASCICOLO CONTRATTO #{$codice} - " . date('d/m/Y H:i'));
break;
default:
throw new InvalidArgumentException("Il modulo {$modulo} non è valido.");
}
if(isset($stati[$stato]["conclusivo"]) && $stati[$stato]["conclusivo"]) {
$days = 45;
$conserva = false;
$tipologia = "download";
if($this->hasModulo('conservazione')) {
$conserva = true;
$settings = json_decode($this->info["conservazione"], TRUE);
if(! empty($settings["tipologia"]) && ($settings["tipologia"] == "all" || $codice_ente == $this->info["codice"])) {
self::$insertPreservationStatement->bindValue(":codice_ente", $this->info["codice"]);
if(! empty($settings["standsteel"])) { $days = $settings["standsteel"]; }
if(! empty($settings["credenziali"]) && ! empty($settings["credenziali"]["username"])) {
$tipologia = "conservazione";
}
}
}
if(! $conserva && $codice_ente !== $this->info["codice"]) {
$ente = self::getInfoFromID($codice_ente);
if(is_array($ente) && count($ente) == 1 && ! empty($ente[0])) { $ente = $ente[0]; }
$moduli = self::getModuli($codice_ente);
if(in_array("conservazione", $moduli)) {
$conserva = true;
$settings = json_decode($ente["conservazione"], TRUE);
if(! empty($settings["standsteel"])) { $days = $settings["standsteel"]; }
if(! empty($settings["credenziali"]) && ! empty($settings["credenziali"]["username"])) { $tipologia = "conservazione"; }
self::$insertPreservationStatement->bindValue(":codice_ente", $ente["codice"]);
}
}
if($conserva) {
self::$checkPreservationStatement->execute();
if(self::$checkPreservationStatement->rowCount() < 1) {
self::$insertPreservationStatement->bindValue(":tipologia", $tipologia);
self::$insertPreservationStatement->bindValue(":utente_modifica", isset($_SESSION["utente"]->codice) ? $_SESSION["utente"]->codice : 0);
self::$insertPreservationStatement->bindValue(":timestamp_creazione", date('Y-m-d H:i:s', strtotime("now")));
self::$insertPreservationStatement->bindValue(":timestamp_esecuzione", date('Y-m-d 00:00:00', $days > 1 ? strtotime("+{$days} days") : ($days == 1 ? strtotime("+1 day") : strtotime('now'))));
if(self::$insertPreservationStatement->execute()) {
$id = (int) $pdo->lastInsertId();
if(! empty($id)) {
if (php_sapi_name() == "cli") {
return true;
}
$dispatch = date('Y-m-d H:i:s', strtotime('+3 hour'));
$result = shell_exec("php {$config["cmds_folder"]}/artisan job:dispatch Preservation/GetFilesJob -P {$this->codice} -P {$id} -Q preservation -C database -D {$dispatch} 2>&1");
$result = preg_replace('~[[:cntrl:]]~', '', $result);
if($result == "Job has been scheduled.") {
return true;
}
}
}
return false;
}
return true;
}
}
return false;
}
/**
* Verifica se l'ente ha un provider di configurazione
*
* @param mixed $codice_ente
* @return Bool
*/
public static function hasProviderConservazione(?Int $codice_ente = null) : Bool {
if(empty($codice_ente) && ! empty($_SESSION["ente"])) { $codice_ente = $_SESSION["ente"]->codice; }
$ente = self::getInfoFromID($codice_ente)[0];
if(! empty($ente["conservazione"]) && is_json($ente["conservazione"])) {
$connettore = json_decode($ente["conservazione"]);
return ! empty($connettore) && ! empty($connettore->credenziali);
}
return false;
}
public static function getUtentiFromModulo(string $idModulo,int $codice_ente,string $ruolo = "",int $idElement = 0) {
global $pdo;
$return = false;
$modulo = Modulo::getModuli()[$idModulo];
if (!empty($modulo)) {
if ($modulo["ente"]) {
$procedi = true;
if (!$modulo["all_ente"]) {
$procedi = false;
$check = $pdo->go("SELECT codice FROM r_moduli_ente WHERE id_modulo = :modulo AND cod_ente = :ente",[":modulo"=>$idModulo,":ente"=>$codice_ente]);
if ($check->rowCount() === 1) { $procedi = true; }
}
if ($procedi) {
$bind = [];
$bind[":codice_ente"] = $codice_ente;
$bind[":modulo"]= $idModulo;
$sql = "SELECT b_utenti.codice, r_collaborazioni.gruppo
FROM b_utenti
JOIN r_collaborazioni ON b_utenti.codice = r_collaborazioni.codice_utente ";
if (!$modulo["all_utente"]) { $sql .= " JOIN r_permessi_collaborazioni ON r_collaborazioni.codice = r_permessi_collaborazioni.cod_relazione "; }
$sql .= " WHERE b_utenti.attivo = 'S' AND r_collaborazioni.attivo = 'S' ";
if (!empty($_SESSION["ente"])) {
$bind[":codice_ente"] = $_SESSION["ente"]->codice;
$sql .= " AND r_collaborazioni.monitoraggio = 'N' AND (r_collaborazioni.codice_ente = :codice_ente OR r_collaborazioni.codice_ente IN (SELECT codice FROM b_enti WHERE sua = :codice_ente)) ";
}
if (!empty($ruolo)) {
$sql .= " AND r_collaborazioni.gruppo = :ruolo ";
$bind[":ruolo"] = $ruolo;
}
if (!$modulo["all_utente"]) {
$bind[":modulo"]= $idModulo;
$sql .= " AND r_permessi_collaborazioni.id_modulo = :modulo ";
}
$risultati = $pdo->go($sql,$bind);
if ($risultati->rowCount() > 0) {
$return = [];
$ruoli = [];
while($utente = $risultati->fetch(PDO::FETCH_ASSOC)) {
$return[] = $utente["codice"];
$ruoli[$utente["codice"]] = $utente["gruppo"];
}
$return = array_unique($return);
}
}
}
if (!empty($return)) {
$settings = Utente::permissionSettings();
$settings = $settings[$idModulo] ?? $settings["default"];
if ($settings["permissionRequired"] && !empty($idElement)) {
$tmp = [];
$check = $pdo->prepare("SELECT codice FROM r_permessi WHERE sezione = :sezione AND codice_elemento = :idElement AND codice_gestore = :codice_gestore AND codice_utente = :codice_utente ");
$check->bindValue(":codice_gestore",$codice_ente);
$check->bindValue(":sezione",$idModulo);
$check->bindValue(":idElement",$idElement);
foreach($return AS $utente) {
$check->bindValue(":codice_utente",$utente);
$check->execute();
if ($check->rowCount() > 0 || $ruoli[$utente] == "ADM") { $tmp[] = $utente; }
}
$return = $tmp;
}
}
}
return $return;
}
public function getUtentiFromEnte(array $utenti,int $ente, int $sogliaGerarchia = 10) {
$ruoliUtenti = [];
$tmpUtenti = Utente::getInfoFromID($utenti);
if (isset($_SESSION["utente"]) && $_SESSION["utente"]->fromHere()) {
$ruoliUtenti = Utente::getRuoloFromID($utenti,$this->codice);
}
if ($this->codice != $ente) {
$ruoliUtentiBeneficiario = Utente::getRuoloFromID($utenti,$ente);
if (!empty($ruoliUtentiBeneficiario)) {
if (!empty($ruoliUtenti)) {
foreach($ruoliUtentiBeneficiario AS $codiceUtente => $ruolo) {
if (isset($ruoliUtenti[$codiceUtente])) {
$ruoliUtenti[$codiceUtente] = [$ruoliUtenti[$codiceUtente]];
}
$ruoliUtenti[$codiceUtente][] = $ruolo;
}
$ruoliUtenti = $ruoliUtenti + $ruoliUtentiBeneficiario;
} else {
$ruoliUtenti = $ruoliUtentiBeneficiario;
}
}
}
if (!empty($tmpUtenti)) {
$utenti = [];
foreach($tmpUtenti AS $utente) {
if (isset($ruoliUtenti[$utente["codice"]])) {
if (isset($ruoliUtenti[$utente["codice"]]["codice_ente"])) {
$ruoliUtenti[$utente["codice"]] = [$ruoliUtenti[$utente["codice"]]];
}
foreach($ruoliUtenti[$utente["codice"]] AS $ruolo) {
$utente["codice_ente"] = $ruolo["codice_ente"];
if (Utente::ruoli()[$ruolo["gruppo"]]["gerarchia"] > $sogliaGerarchia) {
$utenti[] = $utente;
}
}
}
}
return $utenti;
}
}
public function getUtentiAbilitati($modulo) {
return self::getUtentiFromModulo($modulo,$this->codice);
}
public static function getInfoFromID($ids) {
global $pdo;
$return = false;
if (!is_array($ids) && is_numeric($ids)) { $ids = [$ids]; }
if (is_array($ids)) {
$return = [];
$enti = $pdo->prepare("SELECT * FROM b_enti WHERE codice = :id");
foreach($ids AS $id) {
$enti->bindValue(":id",$id);
$enti->execute();
if ($enti->rowCount() > 0) {
$ente = $enti->fetch(PDO::FETCH_ASSOC);
if ($ente["ufficio"] == "S" && isset($_SESSION["ente"]) && !$_SESSION["ente"]->printUfficio && self::$frontOfficeRequest) {
$_codice = $ente["codice"];
$ente = $_SESSION["ente"]->getInfo();
$ente["codice"] = $_codice;
}
$return[] = $ente;
}
}
if (empty($return)) { $return = false; }
}
return $return;
}
public static function getAdvancedConfigForTenant(Int $id,Bool $associative = true) : Array {
$ente = Ente::getInfoFromID($id);
if (!empty($ente)) {
$ente = reset($ente);
global $config;
global $pdo;
$json = $pdo->go("SELECT json FROM s_tenant_configs WHERE codice_ente = :ente ",[":ente"=>$id]);
if ($json->rowCount() === 1) {
$json = $json->fetch(PDO::FETCH_COLUMN);
if (!empty($json)) {
$json = simple_decrypt($json,$config["simple_encrypt"]["advanced_tenant"]);
if (!empty($json)) {
return json_decode($json,$associative);
}
}
}
}
return [];
}
public function getAdvancedConfig() : Array {
return self::getAdvancedConfigForTenant($this->info["codice"]);
}
public static function saveAdvancedConfigForTenant(String $data,Int $id) : Bool {
$check = json_decode($data);
if (empty($data) || !empty($check)) {
$ente = Ente::getInfoFromID($id);
if (!empty($ente)) {
global $config;
$ente = reset($ente);
$salva = new salva();
$salva->debug = false;
$salva->nome_tabella = "s_tenant_configs";
$salva->operazione = "REPLACE";
$salva->oggetto = ["codice_ente"=>$id,"json" => (empty($data)) ? "[]" : simple_encrypt($data,$config["simple_encrypt"]["advanced_tenant"])];
if ($salva->save()) {
return true;
}
}
} else {
throw new Exception("Errore validazione JSON", 400);
}
return false;
}
public static function getLimitiFromID($ids) {
$infos = self::getInfoFromID($ids);
$return = [];
if (!empty($infos)) {
foreach($infos AS $ente) {
$limiti = false;
if (!empty($ente["limiti_moduli"])) {
$limiti = json_decode($ente["limiti_moduli"],true);
}
$return[$ente["codice"]] = $limiti;
}
}
return $return;
}
public function getImportiMassimiProcedure() {
return self::getImportiMassimiProcedureFromID($this->codice);
}
public static function getImportiMassimiProcedureFromID($ids) {
global $pdo;
$limiti = [];
$quickReturn = false;
if (!is_array($ids)) {
$quickReturn = true;
$ids = [$ids];
}
foreach($ids AS $id) {
$bind[":codice"] = $id;
$sql = "SELECT * FROM b_limitazioni WHERE codice_ente = :codice";
$risultato = $pdo->go($sql,$bind);
if($risultato->rowCount()>0){
$limite = $risultato->fetchAll(PDO::FETCH_ASSOC);
if ($quickReturn) {
return $limite;
} else {
$limiti[$id] = $limite;
}
}
}
return $limiti;
}
public static function getSACodesPath(bool $fullPath = false) : String {
global $config;
$path = $config["mediaFolder"] . DIRECTORY_SEPARATOR . "ausa";
if (!is_dir($path)) {
mkdir($path,0770,true);
}
if ($fullPath) {
$path .= DIRECTORY_SEPARATOR . "stazioni-appaltanti_csv.csv";
}
return $path;
}
public static function updateSACodes() {
$path = self::getSACodesPath();
$data = file_get_contents("https://dati.anticorruzione.it/opendata/download/dataset/stazioni-appaltanti/filesystem/stazioni-appaltanti_csv.zip");
if (!empty($data)) {
file_put_contents($path.".zip",$data);
$zip = new ZipArchive;
if ($zip->open($path.".zip") === true) {
$zip->extractTo($path,"stazioni-appaltanti_csv.csv");
$zip->close();
}
}
}
public static function getAusaInfo(String $codice_fiscale) : ?Array {
$codici = fromCSVtoArray(self::getSACodesPath(true));
if (!empty($codici)) {
$codici = array_column($codici,null,"codice_fiscale");
return $codici[$codice_fiscale] ?? null;
}
}
public static function getEccezioniCrossFromID($ids) {
$infos = self::getInfoFromID($ids);
$return = [];
if (!empty($infos)) {
foreach($infos AS $ente) {
$eccezioni = false;
if (!empty($ente["eccezioni_cross"])) {
$eccezioni = json_decode($ente["eccezioni_cross"],true);
}
$return[$ente["codice"]] = (empty($eccezioni)) ? [] : $eccezioni;
}
}
return $return;
}
public static function printAlertLimite() {
$staticFunction = true;
include(__DIR__."/helpers/alertSuperamentoLimite.php");
}
public function checkPEC() {
$return = true;
if ($this->getInfo()["ambienteTest"] == "N") {
if (empty($_SESSION["pecErrore"])) {
if (!file_exists($this->getExtensionPath().DIRECTORY_SEPARATOR."communicator.bridge.class.php")) {
if (!empty(Communicator::availablePEC($this->codice))) {
global $pdo;
$sql = "SELECT codice FROM b_coda WHERE codice_ente = :codice_ente AND `timestamp_creazione` < '" . date('Y-m-d h:i:s', strtotime('-1 day')) . "'";
if ($pdo->go($sql,[":codice_ente"=>$this->codice])->rowCount() > 0) {
$return = false;
}
} else {
$return = false;
}
}
} else {
$return = false;
}
}
if (!$return) {
$_SESSION["pecErrore"] = true;
}
return $return;
}
public function checkLimite($modulo,$print=false) {
$limiti = self::getLimitiFromID($this->codice);
$proceed = true;
if (isset($limiti[$this->codice][$modulo])) {
$checkPath = $this->root."/backend/{$modulo}/_countLimit.php";
if (file_exists($checkPath)) {
global $pdo;
$limiteMassimo = $limiti[$this->codice][$modulo];
include($checkPath);
}
}
if (!$proceed) {
if ($limiti[$this->codice]["_tipologia"] == "alert") {
$proceed = true;
}
if ($print) {
self::printAlertLimite();
}
}
if ($proceed && isset($_SESSION["utente"]) && $_SESSION["utente"]->readOnly) {
$proceed = false;
}
return $proceed;
}
public function sendAlertLimite($modulo) {
$mail = new Communicator();
$mail->corpo = $this->getInfo()["denominazione"] . " " . __("raggiunto il limite per il modulo:","IT") . " {$modulo}";
$mail->oggetto = __("Superamento limite") . " - " . $modulo;
$mail->destinatari = $this->config["email_assistenza"];
$mail->codice_pec = -3;
$mail->send();
}
public function getEccezioniCross() {
return self::getEccezioniCrossFromID($this->codice)[$this->codice] ?? [];
}
public function updateHub($ambito, $id, $obj) {
global $pdo;
if (method_exists($obj,"getHubData")) {
$hubData = $obj->getHubData();
if (!empty($hubData) && (isset($hubData["b_hub_centrale"]))) {
$hubData = [$hubData];
}
if (!empty($hubData)) {
foreach($hubData AS $data) {
if (!empty($data["b_hub_centrale"])) {
$relations = [];
$relations[] = "b_hub_cig";
$relations[] = "b_hub_cup";
$relations[] = "r_hub_cpv";
$relations[] = "r_hub_soa";
$bind = [
":gestore" => $this->info["codice"],
":ambito" => $ambito,
":id" => $id
];
$check = $pdo->go("SELECT codice FROM b_hub_centrale WHERE codice_gestore = :gestore AND ambito = :ambito AND codice_interno = :id",$bind);
$operazione = "INSERT";
if (!empty($check->rowCount())) {
$operazione = "UPDATE";
$id = $check->fetch(PDO::FETCH_COLUMN);
$data["b_hub_centrale"]["codice"] = $id;
}
$salva = new salva();
$salva->debug = false;
$salva->nome_tabella = "b_hub_centrale";
$salva->operazione = $operazione;
$salva->oggetto = $data["b_hub_centrale"];
$id = $salva->save();
if (!empty($id)) {
foreach($relations AS $table) {
$pdo->go("DELETE FROM {$table} WHERE codice_elemento = :id",[":id"=>$id]);
if (!empty($data[$table])) {
foreach($data[$table] AS $sub) {
$sub["codice_elemento"] = $id;
$salva->nome_tabella = $table;
$salva->operazione = "INSERT";
$salva->oggetto = $sub;
$salva->save();
}
}
}
}
} else {
$this->deleteFromHub($ambito, $id);
}
}
}
}
}
public function deleteFromHub($ambito, $id) {
global $pdo;
$bind = [
":gestore" => $this->info["codice"],
":ambito" => $ambito,
":id" => $id
];
$pdo->go("DELETE FROM b_hub_centrale WHERE codice_gestore = :gestore AND ambito = :ambito AND codice_interno = :id",$bind);
scriviLog("b_hub_centrale","DELETE",$pdo->getSQL());
}
public function manageUpdates($ambito, $id, $obj = null) {
if (isset($obj) && is_object($obj)) {
$this->updateHub($ambito, $id, $obj);
}
if (isset($this->erpConnector) && method_exists($this->erpConnector,"sendUpdateRequest")) {
return $this->erpConnector->sendUpdateRequest($ambito,$id,$obj);
}
$integration_function_name = "sendUpdateRequestOn" . Integrazione::unslugify($ambito);
foreach($this as $_ => $value) {
if ($value instanceof Integrazione &&
method_exists($value, $integration_function_name) &&
$value->isValidConfiguration()){
$value->{$integration_function_name}($id);
}
}
}
public function defaultAutenticationLevel() {
return $this->getInfo()["defaultAuthenticationLevel"] ?? 1;
}
public function getExtensionPath() : String {
return self::getTenantExtensionPath($this->codice);
}
public static function getTenantExtensionPath(int $codiceTenant) : String {
global $realRoot, $config;
return $realRoot.DIRECTORY_SEPARATOR."enti".DIRECTORY_SEPARATOR."estensioni".DIRECTORY_SEPARATOR.$config["id-installazione"].DIRECTORY_SEPARATOR.$codiceTenant;
}
}