Benvenuto nel portale ' . APP_NAME . '
Ecco di tuoi dati di accesso
Link di accesso: ' . BASE_HTTP . '
Username: ' . $username . '
Password: ' . $password . '
Codice Da inserire: ' . $codiceGenerato . '

   
'; date_default_timezone_set('Etc/UTC'); $mail = new PHPMailer; $mail->IsSMTP(); $mail->CharSet = "UTF-8"; $mail->SMTPDebug = $GLOBALS['EMAIL_CONFIG']['DEBUG']; $mail->Debugoutput = 'html'; $mail->Host = $GLOBALS['EMAIL_CONFIG']['HOST']; $mail->Port = $GLOBALS['EMAIL_CONFIG']['PORT']; $mail->SMTPSecure = $GLOBALS['EMAIL_CONFIG']['SMTP_SECURE']; $mail->SMTPAuth = $GLOBALS['EMAIL_CONFIG']['SMTP_AUTH']; $mail->Username = $GLOBALS['EMAIL_CONFIG']['USERNAME']; $mail->Password = $GLOBALS['EMAIL_CONFIG']['PASSWORD']; $mail->setFrom($GLOBALS['EMAIL_CONFIG']['FROM'], $GLOBALS['EMAIL_CONFIG']['FROM_DESC']); $mail->addAddress($email, $email); $mail->Subject = $GLOBALS['EMAIL_CONFIG']['SUBJECT']; $mail->msgHTML($testo); $mail->AltBody = $testo; if (!$mail->send()) { $value = "Mailer Error: " . $mail->ErrorInfo; Utils::print_array($value); $value = 0; } else { $value = 1; } return $value; } /** * Funzione per l'invio delle email dopo la richiesta di reset password dell'utente * @param type $email * @param type $username * @param type $password * @return int */ public static function invioMailResetPswUtente($email, $username, $password) { if (!INVIO_EMAIL) return 1; $testo = '' . APP_NAME . '
La password è stata modificata
di seguito i dati di accesso
Link di accesso: ' . BASE_HTTP . '
Username: ' . $username . '
Password: ' . $password . '

   
'; date_default_timezone_set('Etc/UTC'); $mail = new PHPMailer; $mail->IsSMTP(); $mail->CharSet = "UTF-8"; $mail->SMTPDebug = $GLOBALS['EMAIL_CONFIG']['DEBUG']; $mail->Debugoutput = 'html'; $mail->Host = $GLOBALS['EMAIL_CONFIG']['HOST']; $mail->Port = $GLOBALS['EMAIL_CONFIG']['PORT']; $mail->SMTPSecure = $GLOBALS['EMAIL_CONFIG']['SMTP_SECURE']; $mail->SMTPAuth = $GLOBALS['EMAIL_CONFIG']['SMTP_AUTH']; $mail->Username = $GLOBALS['EMAIL_CONFIG']['USERNAME']; $mail->Password = $GLOBALS['EMAIL_CONFIG']['PASSWORD']; $mail->setFrom($GLOBALS['EMAIL_CONFIG']['FROM'], $GLOBALS['EMAIL_CONFIG']['FROM_DESC']); $mail->addAddress($email, $email); $mail->Subject = $GLOBALS['EMAIL_CONFIG']['SUBJECT']; $mail->msgHTML($testo); $mail->AltBody = $testo; if (!$mail->send()) { $value = "Mailer Error: " . $mail->ErrorInfo; Utils::print_array($value); $value = 0; } else { $value = 1; } return $value; } /** * Funzione invio email per la registrazione di un nuovo operatore * @global type $GLOBALS * @param type $email * @param type $username * @param type $password * @return int */ public static function invioMailRegOperatore($email, $username, $password) { global $GLOBALS; if (!INVIO_EMAIL) { $value['esito'] = 1; return $value; } $testo = 'Benvenuto nel portale ' . APP_NAME . '
Ecco di tuoi dati di accesso
Link di accesso: ' . BASE_HTTP . 'admin/
Username: ' . $username . '
Password: ' . $password . '

   
'; date_default_timezone_set('Etc/UTC'); $mail = new PHPMailer; $mail->IsSMTP(); $mail->CharSet = "UTF-8"; $mail->SMTPDebug = $GLOBALS['EMAIL_CONFIG']['DEBUG']; $mail->Debugoutput = 'html'; $mail->Host = $GLOBALS['EMAIL_CONFIG']['HOST']; $mail->Port = $GLOBALS['EMAIL_CONFIG']['PORT']; $mail->SMTPSecure = $GLOBALS['EMAIL_CONFIG']['SMTP_SECURE']; $mail->SMTPAuth = $GLOBALS['EMAIL_CONFIG']['SMTP_AUTH']; $mail->Username = $GLOBALS['EMAIL_CONFIG']['USERNAME']; $mail->Password = $GLOBALS['EMAIL_CONFIG']['PASSWORD']; $mail->setFrom($GLOBALS['EMAIL_CONFIG']['FROM'], $GLOBALS['EMAIL_CONFIG']['FROM_DESC']); $mail->addAddress($email, $email); $mail->Subject = $GLOBALS['EMAIL_CONFIG']['SUBJECT']; $mail->msgHTML($testo); $mail->AltBody = $testo; if (!$mail->send()) { $value['descrizioneErrore'] = "Mailer Error: " . $mail->ErrorInfo; $value['esito'] = 0; } else { $value['esito'] = 1; } return $value; } /** * Funzione dell'invio della mei l dopo la richiesta di recupero password * @param type $email * @param type $username * @param type $password * @return int */ public static function invioMailResetPswOperatore($email, $username, $password) { if (!INVIO_EMAIL) return 1; $testo = '' . APP_NAME . '
La password è stata modificata
di seguito i dati di accesso
Link di accesso: ' . BASE_HTTP . 'admin/
Username: ' . $username . '
Password: ' . $password . '

   
'; date_default_timezone_set('Etc/UTC'); $mail = new PHPMailer; $mail->IsSMTP(); $mail->CharSet = "UTF-8"; $mail->SMTPDebug = $GLOBALS['EMAIL_CONFIG']['DEBUG']; $mail->Debugoutput = 'html'; $mail->Host = $GLOBALS['EMAIL_CONFIG']['HOST']; $mail->Port = $GLOBALS['EMAIL_CONFIG']['PORT']; $mail->SMTPSecure = $GLOBALS['EMAIL_CONFIG']['SMTP_SECURE']; $mail->SMTPAuth = $GLOBALS['EMAIL_CONFIG']['SMTP_AUTH']; $mail->Username = $GLOBALS['EMAIL_CONFIG']['USERNAME']; $mail->Password = $GLOBALS['EMAIL_CONFIG']['PASSWORD']; $mail->setFrom($GLOBALS['EMAIL_CONFIG']['FROM'], $GLOBALS['EMAIL_CONFIG']['FROM_DESC']); $mail->addAddress($email, $email); $mail->Subject = $GLOBALS['EMAIL_CONFIG']['SUBJECT']; $mail->msgHTML($testo); $mail->AltBody = $testo; if (!$mail->send()) { $value = "Mailer Error: " . $mail->ErrorInfo; Utils::print_array($value); $value = 0; } else { $value = 1; } return $value; } public static function isNull($input) { if (!empty($input)) { return $input; } else { return NULL; } } public static function isNullData($input) { if (!empty($input)) { return $input; } else { return "STR"; } } public static function generateCodice($length = 8) { $password = ''; $possibleChars = '0123456789'; $i = 0; while ($i < $length) { $char = substr($possibleChars, mt_rand(0, strlen($possibleChars) - 1), 1); if (!strstr($password, $char)) { $password .= $char; $i++; } } return $password; } public static function generatePassword($length = 8) { $password = ''; $possibleChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@'; $i = 0; while ($i < $length) { $char = substr($possibleChars, mt_rand(0, strlen($possibleChars) - 1), 1); if (!strstr($password, $char)) { $password .= $char; $i++; } } return $password; } public static function calcolaGiorni($scadenza, $data) { $startTimeStamp = strtotime($data); $endTimeStamp = strtotime($scadenza); $timeDiff = abs($endTimeStamp - $startTimeStamp); $numberDays = $timeDiff / 86400; // 86400 seconds in one day // and you might want to convert to integer $numberDays = intval($numberDays); return $numberDays; } public static function convertiProfilo($ruolo) { $d = ""; switch ($ruolo) { case 1: $d = "SUPER ADMIN"; break; case 2: $d = "ADMIN"; break; case 3: $d = "OPERATORE"; break; } return $d; } public static function time12to24($time = null) { $result = ''; if ($time != null) { $ora_ampm = explode(' ', $time); $ora = explode(':', $ora_ampm[0]); if ($ora_ampm[1] == 'PM') { $ora[0] = $ora[0] + 12; } $result = $ora[0] . ':' . $ora[1]; } return $result; } public static function is_date($date) { $date = str_replace(array('\'', '-', '.', ','), '/', $date); $date = explode('/', $date); if (count($date) == 1 // No tokens and is_numeric($date[0]) and $date[0] < 20991231 and ( checkdate(substr($date[0], 4, 2) , substr($date[0], 6, 2) , substr($date[0], 0, 4))) ) { return true; } if (count($date) == 3 and is_numeric($date[0]) and is_numeric($date[1]) and is_numeric($date[2]) and ( checkdate($date[0], $date[1], $date[2]) //mmddyyyy or checkdate($date[1], $date[0], $date[2]) //ddmmyyyy or checkdate($date[1], $date[2], $date[0])) //yyyymmdd ) { return true; } return false; } public static function convertiData($originalDate) { $newDate = date("d/m/Y", strtotime($originalDate)); return $newDate; } public static function convertiDataConOra($originalDate) { $newDate = date("d/m/Y H:i:s", strtotime($originalDate)); return $newDate; } public static function convertiDataUSA($originalDate) { list ($giorno, $mese, $anno) = split('[/.-]', $originalDate); return $anno . "/" . $mese . "/" . $giorno; } public static function getMyIp() { $ip = getenv('HTTP_CLIENT_IP') ?: getenv('HTTP_X_FORWARDED_FOR') ?: getenv('HTTP_X_FORWARDED') ?: getenv('HTTP_FORWARDED_FOR') ?: getenv('HTTP_FORWARDED') ?: getenv('REMOTE_ADDR'); return $ip; } public static function addLog($db, $id_utente, $username, $ruolo, $evento) { //myIp $mio_ip = getMyIp(); $evento = addslashes($evento); return mysqli_query($db, "INSERT INTO log_sistema (ID_UTENTE,NOME_OPERATORE,RUOLO,INDIRIZZO_IP,EVENTO) VALUES($id_utente,'$username',$ruolo,'$mio_ip','$evento')"); } public static function isIspettore() { return $_SESSION['id_gruppo'] == GRUPPO_ISPETTORE_SANITARIO; } public static function getFilterProvinciaAuthLogged() { $provincia = ''; if ($_SESSION['id_gruppo'] == GRUPPO_ISPETTORE_SANITARIO || $_SESSION['id_gruppo'] == GRUPPO_CAPO_PROVINCIALE) { $provincia = strtolower($_SESSION['provincia_ap']); } return $provincia; } public static function getProvFromString($prov = '') { $response = ''; if ($prov != '') { $var = explode("(", $prov); $te = $var[1]; $te = explode(")", $te); $response = $te[0]; } return $response; } public static function checkLogin() { if (!isset($_SESSION['ID'])) { header("Location: " . BASE_HTTP . "login_spid.php"); } } /** * Controllo se ho impostata la sessione per poter accedere ai servizi * @return boolean */ public static function canAccess() { $access = false; if (isset($_SESSION['ID']) && intval($_SESSION['ID']) > 0) { $access = true; } return $access; } public static function getUTF8($element = '') { $response = $element; if (!is_array($element)) { $response = utf8_encode($element); } return $response; } /** * Inizializza le proprieta' di un oggetto con i valori di un array associativo * * @param mixed $obj L'oggetto da inizializzare, deve essere passato by-ref * @param array $row L'array associativo da cui recuperare i valori * @param mixed $callbackOnExists (Facoltativo) Metodo dell'oggetto da richiamare quando si deve assegnare il valore alla proprieta' */ public static function FillObjectFromRow(&$obj, $row, $stripSlashes = false, $callbackOnExists = false) { $props = get_class_vars(get_class($obj)); //echo "
".print_r($props, true)."
"; foreach ($props as $prop => $value) { if ($row != null && array_key_exists($prop, $row)) { if (!$callbackOnExists) $obj->$prop = ($stripSlashes ? stripslashes($row[$prop]) : $row[$prop]); else $obj->$callbackOnExists($prop, utf8_encode($row[$prop])); } } } public static function prepareKeyArray(&$src) { if (is_array($src)) { foreach ($src as $k => $v) { $kn = str_replace('-', '', $k); $newsrc[$kn] = Utils::prepareKeyArray($v); } } else { $newsrc = $src; } //Utils::print_array($newsrc); return $newsrc; } // Funzione per Le notifiche // Settaggi // visibile_utente=0 L'utente non vede la notifica (AZIENDA) // visibile_utente=1 // visibile per utente // lettura_utente=0 l'utente non ha ancora visualizzato // lettura_utente=1 l'utente ha visualizzato la notifica function setNotifica($descrizione = null, $id_ditta = 0, $id_operatore = 0, $visibile = 1, $lettura_utente = 0, $id_destinatario = 0, $id_laboratorio = 0) { global $con, $LoggedAccount; $date = date("Y-m-d"); $queryNotifica = $con->prepare("INSERT INTO notifica(descrizione, id_operatore, id_utente,data_creazione,visibile_utente,lettura_utente,id_destinatario, id_laboratorio)VALUES (:descrizione,:id_operatore,:id_utente,:data_creazione,:visibile_utente,:lettura_utente,:id_destinatario, :id_laboratorio)"); $queryNotifica->bindParam(":descrizione", $descrizione); $queryNotifica->bindParam(":id_operatore", $LoggedAccount->id); $queryNotifica->bindParam(":id_utente", $id_ditta); $queryNotifica->bindParam(":data_creazione", $date); $queryNotifica->bindParam(":visibile_utente", $visibile); $queryNotifica->bindParam(":lettura_utente", $lettura_utente); $queryNotifica->bindParam(":id_destinatario", $id_destinatario); $queryNotifica->bindParam(":id_laboratorio", $id_laboratorio); try { $return = $queryNotifica->execute(); $return['esito'] = 1; } catch (Exception $exc) { $return['esito'] = -999; $return['descrizioneErrore'] = $exc->getMessage(); } return $return; } public static function GetAge($dataNascita) { if ($dataNascita == "" || $dataNascita == '00/00/0000' || $dataNascita == '0000-00-00') return 0; // Ricavo giorno, mese e anno list($giorno, $mese, $anno) = explode("/", Utils::FormatDate($dataNascita, DATE_FORMAT_ITA)); // Calcolo anni $eta = date('Y') - $anno; // Tolgo 1 se ad esempio sono X anni e 11 mesi if (date('m') < $mese) $eta--; // Stessa cosa per i giorni elseif (date('m') == $mese && date('d') < $giorno) $eta--; return $eta; } public static function GetValidName($oldName) { $newName = ""; $name = $oldName; for ($i = 0; $i < strlen($name); $i++) { $char = substr($name, $i, 1); if (!preg_match("/^[a-zA-Z0-9]$/", $char)) $char = "_"; $newName .= $char; } return $newName; } /** * * @param type $oldName * @param type $newExt * @param type $arrayExt estensioni da controllare di secondo livello nel filename es: array('.pdf','.doc','.zip') * @return type */ public static function GetValidFilename($oldName, $newExt = "", $arrayExt = array('.pdf')) { $newName = ""; $name = $oldName; $ext = self::GetFilenameExtension($name); if ($ext != "") { $name = substr($name, 0, strlen($name) - strlen($ext)); $ext2 = self::GetFilenameExtension($name); if (in_array($ext2, $arrayExt)) { $name = substr($name, 0, strlen($name) - strlen($ext2)); $ext = $ext2 . $ext; } } for ($i = 0; $i < strlen($name); $i++) { $char = substr($name, $i, 1); if (!preg_match("/^[a-zA-Z0-9-]$/", $char)) $char = "_"; $newName .= $char; } $newName = str_replace(" ", "_", $newName); $newName .= ($newExt != "" ? $newExt : $ext); return $newName; } public static function GetFilenameExtension($filename) { $i = strrpos($filename, "."); if ($i === false) return ""; return substr($filename, $i); } public static function InsertArrayIndex($array, $new_element, $index) { /* * * get the start of the array ** */ $start = array_slice($array, 0, $index); /* * * get the end of the array ** */ $end = array_slice($array, $index); /* * * add the new element to the array ** */ $start[] = $new_element; /* * * glue them back together and return ** */ return array_merge($start, $end); } public static function EncodeJavascript($text, $escapeChar = '"') { if ($escapeChar == '"') return str_replace($escapeChar, '\\"', $text); elseif ($escapeChar == '"') return str_replace($escapeChar, "\\'", $text); return $text; } /** $interval can be: yyyy - Number of full years q - Number of full quarters m - Number of full months y - Difference between day numbers (eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".) d - Number of full days w - Number of full weekdays ww - Number of full weeks h - Number of full hours n - Number of full minutes s - Number of full seconds (default) */ public static function DateDiff($interval, $datefrom, $dateto, $using_timestamps = false, $return_absolute_diff = true) { if (!$using_timestamps) { $datefrom = strtotime(str_replace("/", "-", $datefrom), 0); $dateto = strtotime(str_replace("/", "-", $dateto), 0); } $difference = $dateto - $datefrom; // Difference in seconds switch ($interval) { case 'yyyy': // Number of full years $years_difference = floor($difference / 31536000); if (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom), date("j", $datefrom), date("Y", $datefrom) + $years_difference) > $dateto) { $years_difference--; } if (mktime(date("H", $dateto), date("i", $dateto), date("s", $dateto), date("n", $dateto), date("j", $dateto), date("Y", $dateto) - ($years_difference + 1)) > $datefrom) { $years_difference++; } $datediff = $years_difference; break; case "q": // Number of full quarters $quarters_difference = floor($difference / 8035200); while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom) + ($quarters_difference * 3), date("j", $dateto), date("Y", $datefrom)) < $dateto) { $months_difference++; } $quarters_difference--; $datediff = $quarters_difference; break; case "m": // Number of full months $months_difference = floor($difference / 2678400); while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom) + ($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) { $months_difference++; } $months_difference--; $datediff = $months_difference; break; case 'y': // Difference between day numbers $datediff = date("z", $dateto) - date("z", $datefrom); break; case "d": // Number of full days $datediff = floor($difference / 86400); break; case "w": // Number of full weekdays $days_difference = floor($difference / 86400); $weeks_difference = floor($days_difference / 7); // Complete weeks $first_day = date("w", $datefrom); $days_remainder = floor($days_difference % 7); $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder? if ($odd_days > 7) { // Sunday $days_remainder--; } if ($odd_days > 6) { // Saturday $days_remainder--; } $datediff = ($weeks_difference * 5) + $days_remainder; break; case "ww": // Number of full weeks $datediff = floor($difference / 604800); break; case "h": // Number of full hours $datediff = floor($difference / 3600); break; case "n": // Number of full minutes $datediff = floor($difference / 60); break; default: // Number of full seconds (default) $datediff = $difference; break; } return $return_absolute_diff ? abs($datediff) : $datediff; } function GetTimestamp($data, $add_days = 0, $debug = false) { if (strpos($data, " ") === false) { $a_data = $data; $a_time = "00:00"; } else { $a_data = substr($data, 0, strpos($data, " ")); $a_time = substr($data, strpos($data, " ") + 1, 8); } $a_data = explode("/", str_replace("-", "/", $a_data)); $a_time = explode(":", str_replace(".", ":", $a_time)); if (strlen($a_data[0]) == 4) { // Arriva in formato ISO $timestamp = mktime($a_time[0], $a_time[1], $a_time[2], $a_data[1], $add_days + $a_data[2], $a_data[0]); } else { // Arriva in formato ITA $timestamp = mktime($a_time[0], $a_time[1], $a_time[2], $a_data[1], $add_days + $a_data[0], $a_data[2]); } return $timestamp; } /** * Data una stringa, ne restituisce la data corrispondente nel formato richiesto. * * @param string $data La stringa contenente la data in formato italiano * @param mixed $format Deve essere DATE_FORMAT_ITA oppure DATE_FORMAT_ISO * @return string */ public static function FormatDate($data = null, $format = DATE_FORMAT_ITA) { if ($data == '') return ""; if ($data == null) $data = date("d/m/Y"); $len = strlen($data); if ($len != 10 && $len != 16 && $len != 19) return $data; if ($len == 10) { list($d1, $d2, $d3) = explode("/", str_replace("-", "/", $data)); if (strlen($d1) == 4) { $year = $d1; $month = $d2; $day = $d3; } else { $day = $d1; $month = $d2; $year = $d3; } //echo "F: ".$format; exit; switch ($format) { case DATE_FORMAT_ITA: return sprintf("%s/%s/%s", $day, $month, $year); case DATE_FORMAT_ISO: return sprintf("%s-%s-%s", $year, $month, $day); case DATE_FORMAT_ITA_WITHOUT_SEP: return sprintf("%s%s%s", $day, $month, $year); default: $timestamp = mktime(0, 0, 0, $month, $day, $year); return strftime($format, $timestamp); } } else { $array = explode(" ", $data); $date = $array[0]; $ora = $array[1]; list($d1, $d2, $d3) = explode("/", str_replace("-", "/", $date)); list($hour, $minute) = explode(":", str_replace(".", ":", $ora)); if (strlen($d1) == 4) { $year = $d1; $month = $d2; $day = $d3; } else { $day = $d1; $month = $d2; $year = $d3; } switch ($format) { case DATE_FORMAT_ITA: return sprintf("%s/%s/%s %s:%s:00", $day, $month, $year, $hour, $minute); case DATE_FORMAT_ISO: return sprintf("%s-%s-%s %s:%s:00", $year, $month, $day, $hour, $minute); case DATE_FORMAT_ITA_WITHOUT_SEP: return sprintf("%s%s%s", $day, $month, $year, $hour, $minute); default: $timestamp = mktime(0, 0, 0, $month, $day, $year); return strftime($format, $timestamp); } } } /** * Redireziona il browser all'indirizzo specificato * * @param string $url Indirizzo verso cui redirezionare */ public static function RedirectTo($url) { ob_clean(); header("Location: " . $url); exit(); } /** * Restituisce un array associativo da un oggetto recuperandone le proprieta' * * @param mixed $obj Oggetto da cui ricavare l'array * @return array Array associativo con le proprieta' e relativi valori * */ public static function ObjectToArray($obj) { $array = array(); $props = get_class_vars(get_class($obj)); foreach ($props as $prop => $value) { $array[$prop] = $obj->$prop; } return $array; } public static function CreateRecursiveTree(&$tree, $a) { foreach ($a as $k => $v) { if (!array_key_exists($k, $tree)) { $tree[$k] = $v; } else { if (is_array($v)) { Utils::CreateRecursiveTree($tree[$k], $v); } } } } public static function array_values_recursive($array) { $temp = array(); foreach ($array as $key => $value) { if (is_numeric($key)) { $temp[] = is_array($value) ? Utils::array_values_recursive($value) : $value; } else { $temp[$key] = is_array($value) ? Utils::array_values_recursive($value) : $value; } } return $temp; } public static function GetInizioSettimana($Data) { $myDate = strtotime($Data); $giornoSettimana = date("w", $myDate); $differenzaGiorni = $giornoSettimana - 1; $giornoCheFu = date("Y-m-d", strtotime($Data . "-" . $differenzaGiorni . " days")); return $giornoCheFu; } public static function GetFineSettimana($Data) { //$myDate = strtotime($Data); $giornoSettimana = date("w", $Data); $giornoCheSara = date("Y-m-d", strtotime($Data . "+" . $giornoSettimana . " days")); return $giornoCheSara; } public static function AddTime($Start, $Adding, $unit, $diff = "+") { $Start = strtotime($Start); switch ($unit) { case "hours": $etime = strtotime("$diff $Adding hours", $Start); return date('H:i:s', $etime); case "minutes": $etime = strtotime("$diff $Adding minutes", $Start); return date('H:i:s', $etime); case "seconds": $etime = strtotime("$diff $Adding seconds", $Start); return date('H:i:s', $etime); } } public static function GetGiornoSettimana($data, $all = false) { if ($data == "") return ""; $giorni = array('Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato'); $data = Utils::FormatDate($data, DATE_FORMAT_ISO); if ($all) return $giorni[date('w', strtotime($data))]; else return substr($giorni[date('w', strtotime($data))], 0, 3); } public static function pdo_debugStrParams($stmt) { ob_start(); $stmt->debugDumpParams(); $r = ob_get_contents(); ob_end_clean(); return $r; } public static function get_filter_string64_get($valore) { $options = array('options' => array('default' => NULL)); $valid = filter_input(INPUT_GET, $valore, FILTER_SANITIZE_STRING, $options); return base64_decode($valid); // Default will return } public static function get_filter_string64($valore) { $options = array('options' => array('default' => NULL)); $valid = filter_input(INPUT_POST, $valore, FILTER_SANITIZE_STRING, $options); return base64_decode($valid); // Default will return } public static function get_filter_int($valore) { $options = array('options' => array('default' => NULL)); $valid = filter_input(INPUT_POST, $valore, FILTER_VALIDATE_INT, $options); if ($valid == "") { $valid = NULL; } return $valid; // Default will return } /** * Filtra gli input stringa $_POST * @param type $valore; se $post è true $valore deve essere il nome della chiave POST altrimenti deve essere la variabile * @param type $post; true = gestisce il INPUT_POST; false gestice il valore della variabile $valore * @return type */ public static function get_filter_string($valore, $array = false) { $options = array('options' => array('default' => NULL)); if (!$array) { $valid = filter_input(INPUT_POST, $valore, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES); } else { $valid = filter_input(INPUT_POST, $valore, FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY); } if ($valid == "") { $valid = NULL; } return $valid; // Default will return } // public static function get_filter_array_string($valore) { // $options = array($valore => array( // 'filter'=>FILTER_VALIDATE_REGEXP | FILTER_SANITIZE_STRING, // 'flags'=>FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_BACKTICK, // 'options'=>array('regexp'=>"/t(.*)/"), // )); // $valid = filter_input_array(INPUT_POST, $options); // if ($valid == "") { // $valid = NULL; // } // return $valid; // Default will return // } /** * Passando le variabili della classe viene costruita la sintassi della stringa sql (INSERT O UPDATE) * @param type $table * @param type $vars * @param type $varKeyAutoincrement nome colonna chiave autoincrement * @return string */ public static function prepareQuery($table, $vars, $varKeyAutoincrement = 'ID') { $sottrai = (array_key_exists($varKeyAutoincrement, $vars) ? 1 : 0); if ($vars[$varKeyAutoincrement] > 0) { $sql = "UPDATE " . $table . " SET "; $i = 0; foreach ($vars as $k => $v) { if ($k == $varKeyAutoincrement) continue; $i++; $sql .= $k . "=:" . $k; if ($i < count($vars) - $sottrai) $sql .= ", "; } $sql .= " WHERE " . $varKeyAutoincrement . " = :" . $varKeyAutoincrement; } else { $sql = "INSERT INTO " . $table; $i = 0; foreach ($vars as $k => $v) { if ($k == $varKeyAutoincrement) continue; $i++; if ($i == 1) $sql .= " ("; $sql .= $k; if ($i < count($vars) - $sottrai) $sql .= ", "; } $sql .= ") VALUES ("; $ii = 0; foreach ($vars as $k => $v) { if ($k == $varKeyAutoincrement) continue; $ii++; $sql .= ":" . $k . " "; if ($ii < count($vars) - $sottrai) $sql .= ", "; } $sql .= ") "; $sql .= ($get_return ? " RETURNING " . $varKeyAutoincrement : ''); } return $sql; } public static function getDateField($key, $value) { $pos = strpos($key, "data_"); if (($pos !== false) && ($value == "")) { $value = NULL; } return $value; } public static function getFromReq($param, $defval = null) { return (isset($_REQUEST[$param]) ? trim($_REQUEST[$param]) : $defval); } public static function checkStringField($string, $defRet = null) { $ret = $defRet; if ($string != null && trim($string) != '') { $ret = $string; } return $ret; } public static function recJsonResponse($count, $row, $page, $record) { $result = array(); $result[] = array( 'totrec' => $count, 'recs' => $record, 'page' => $page, 'row' => $row ); return json_encode($result); } public static function saveJsonResponse($response) { $result = array(); $result[] = array( 'status' => $count, 'recs' => $record, 'page' => $page, 'row' => $row ); return json_encode($result); } public static function print_array($array = array()) { echo "
" . print_r($array, true) . "
"; } public static function print_xml($xml = '') { echo "
" . htmlentities($xml) . "
"; } public static function normalizeGps($gps) { if (strpos($gps, 'N') !== false) { $gps = str_ireplace("' ", "", trim($gps)); $gps = str_ireplace(". ", "", trim($gps)); $gps = str_ireplace(".", "", trim($gps)); $gps = str_ireplace("\"", "", trim($gps)); $gps = str_ireplace("° ", ".", trim($gps)); $gps = str_ireplace("E", "", trim($gps)); $coord = explode("N", $gps); } else { $coord = explode(", ", $gps); } $lat[0] = trim($coord[0]); $lat[1] = trim($coord[1]); return $lat; } /* * Funzione per il controllo dei dati ricevuti */ public static function requestDati($array = "") { $lunghezza = count($array); $ritorno = array(); foreach ($array as $key => $element) { $nuovoValorNumeric = ""; $nuovoValorString = ""; if (is_numeric($element) && substr($element, 0, 1) != '0') { $nuovoValorNumeric = trim(Utils::get_filter_int_No_Input($element)); $ritorno[$key] = $nuovoValorNumeric; } else { if ($key != "action" && $key != "module" && $key != "password") { $nuovoValorString = trim((Utils::get_filter_string_No_Input($element))); $ritorno[$key] = $nuovoValorString; } // if ($key == "username" || $key == "USERNAME" || $key=="NOME_UTENTE") { // $nuovoValorString = trim(strtolower(Utils::get_filter_string_No_Input($element))); // $ritorno[$key] = $nuovoValorString; // } } } return $ritorno; } /* * funzione di invio sms */ function sendsmsOtp($otp, $numerosms) { $userSms = $GLOBALS["SMS_CONFIG"]['USERSMS']; $pwdSms = $GLOBALS["SMS_CONFIG"]['PWDSMS']; $urlSms = $GLOBALS["SMS_CONFIG"]['URLSMS']; $senderSms = $GLOBALS["SMS_CONFIG"]['SENDERSMS']; //MAX 10CHAR $testoSms = "Sipars - OTP :" . $otp; $postfields = array( smsUSER => $userSms, smsPASSWORD => $pwdSms, smsTEXT => $testoSms, smsSENDER => $senderSms, smsGATEWAY => "M", // smsNUMBER => '+39' . $numerosms); smsNUMBER => '+1111111111'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $urlSms); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only! $result = curl_exec($ch); $xml = htmlentities($result); $substr = '+Ok'; if (strpos($xml, $substr) !== false) { return 1; } else { return 0; } } /* * Creazione Otp */ public static function createOtp() { $otp = substr(number_format(time() * rand(), 0, '', ''), 0, 6); return $otp; } /* * Restituisce i valori da una funzione non da input */ public static function get_filter_int_No_Input($valore) { $options = array('options' => array('default' => NULL)); $valid = filter_var($valore, FILTER_VALIDATE_INT, $options); if ($valid == "") { $valid = NULL; } return $valid; // Default will return } public static function get_filter_string_No_Input($valore) { $options = array('options' => array('default' => NULL)); $valid = filter_var($valore, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES); if ($valid == "") { $valid = NULL; } return $valid; // Default will return } public static function verifyErroriGoogle($valore) { $messaggio = ""; switch ($valore) { case "EMAIL_EXISTS": $messaggio = EMAIL_EXISTS; break; case "OPERATION_NOT_ALLOWED": $messaggio = OPERATION_NOT_ALLOWED; break; case "TOO_MANY_ATTEMPTS_TRY_LATER": $messaggio = TOO_MANY_ATTEMPTS_TRY_LATER; break; case "EMAIL_NOT_FOUND": $messaggio = EMAIL_NOT_FOUND; break; case "INVALID_PASSWORD": $messaggio = INVALID_PASSWORD; break; case "USER_DISABLED": $messaggio = USER_DISABLED; break; case "INVALID_ID_TOKEN": $messaggio = INVALID_ID_TOKEN; break; case "USER_NOT_FOUND": $messaggio = USER_NOT_FOUND; break; case "WEAK_PASSWORD": $messaggio = WEAK_PASSWORD; break; } return $messaggio; // Default will return } /* * * Registrazione Utente * */ public static function signUpFirebase($email = "", $password = "") { $return = array(); $endpoint = LINK_FIREBASE . "accounts:signUp?key=" . API_FIREBASE_KEY; $postvars = json_encode(array( email => $email, password => $password, returnSecureToken => false )); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); $result = curl_exec($ch); $arrayresponse = json_decode($result, true); $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_errno = curl_errno($ch); if ($http_status == 200) { $return['esito'] = 1; $return['dati'] = $arrayresponse; } else { if (is_array($arrayresponse['error'])) { $return['esito'] = -999; $return['erroreDescrizione'] = Utils::verifyErroriGoogle($arrayresponse['error']['message']); } else { $return['esito'] = -999; $return['erroreDescrizione'] = "Servizio Momentaneamente Non Disponibile"; } } curl_close($ch); return ($return); } /* * * Invio Mail di Verifica Utente * */ public static function sendVerificationMailFirebase($idToken = "") { $return = array(); $endpoint = LINK_FIREBASE . "accounts:sendOobCode?key=" . API_FIREBASE_KEY; $postvars = json_encode(array( idToken => $idToken, requestType => "VERIFY_EMAIL", // returnSecureToken => true )); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); $result = curl_exec($ch); $arrayresponse = json_decode($result, true); $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_errno = curl_errno($ch); // print_r($result); if ($http_status == 200) { $return['esito'] = 1; $return['dati'] = $arrayresponse; } else { if (is_array($arrayresponse['error'])) { $return['esito'] = -999; $return['erroreDescrizione'] = Utils::verifyErroriGoogle($arrayresponse['error']['message']); } else { $return['esito'] = -999; $return['erroreDescrizione'] = "Servizio Momentaneamente Non Disponibile"; } } curl_close($ch); return ($return); } /* * * Login Firebase * "e-mail" ------------------>L'email con cui l'utente sta effettuando l'accesso. * "password" --------------------> La password per l'account. * "returnSecureToken" ------------------> booleano Se restituire o meno un ID e aggiornare il token. Dovrebbe essere sempre vero. */ public static function loginFirebase($email = "", $password = "") { $return = array(); $endpoint = LINK_FIREBASE . "accounts:signInWithPassword?key=" . API_FIREBASE_KEY; $postvars = json_encode(array( email => $email, password => $password, returnSecureToken => true )); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); $result = curl_exec($ch); $arrayresponse = json_decode($result, true); $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_errno = curl_errno($ch); if ($http_status == 200) { $return['esito'] = 1; $return['dati'] = $arrayresponse; } else { if (is_array($arrayresponse['error'])) { $return['esito'] = -999; $return['erroreDescrizione'] = Utils::verifyErroriGoogle($arrayresponse['error']['message']); } else { $return['esito'] = -999; $return['erroreDescrizione'] = "Servizio Momentaneamente Non Disponibile"; } } curl_close($ch); return ($return); } /* * * Load Utente Firebase * IDToken corda Il token ID Firebase dell'account. * get user data */ public static function loadUtenteFirebase($IDToken = "") { $return = array(); $endpoint = LINK_FIREBASE . "accounts:lookup?key=" . API_FIREBASE_KEY; $postvars = json_encode(array( idToken => $IDToken, )); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); $result = curl_exec($ch); $arrayresponse = json_decode($result, true); $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_errno = curl_errno($ch); if ($http_status == 200) { $return['esito'] = 1; $return['dati'] = $arrayresponse; } else { Utils::print_array($arrayresponse); if (is_array($arrayresponse['error'])) { $return['esito'] = -999; $return['erroreDescrizione'] = Utils::verifyErroriGoogle($arrayresponse['error']['message']); } else { $return['esito'] = -999; $return['erroreDescrizione'] = "Servizio Momentaneamente Non Disponibile"; } } curl_close($ch); return ($return); } public static function deleteUtenteFirebase($IDToken = "") { $return = array(); $endpoint = LINK_FIREBASE . "accounts:delete?key=" . API_FIREBASE_KEY; $postvars = json_encode(array( idToken => $IDToken, )); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); $result = curl_exec($ch); $arrayresponse = json_decode($result, true); $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_errno = curl_errno($ch); if ($http_status == 200) { $return['esito'] = 1; $return['dati'] = $arrayresponse; } else { if (is_array($arrayresponse['error'])) { $return['esito'] = -999; $return['erroreDescrizione'] = Utils::verifyErroriGoogle($arrayresponse['error']['message']); } else { $return['esito'] = -999; $return['erroreDescrizione'] = "Servizio Momentaneamente Non Disponibile"; } } curl_close($ch); return ($return); } public static function getUserDataFirebase($idToken = "") { $return = array(); $endpoint = LINK_FIREBASE . "accounts:lookup?key=" . API_FIREBASE_KEY; $postvars = json_encode(array( idToken => $idToken )); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); $result = curl_exec($ch); $arrayresponse = json_decode($result, true); $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_errno = curl_errno($ch); if ($http_status == 200) { $return['esito'] = 1; $return['dati'] = $arrayresponse; } else { if (is_array($arrayresponse['error'])) { $return['esito'] = -999; $return['erroreDescrizione'] = Utils::verifyErroriGoogle($arrayresponse['error']['message']); } else { $return['esito'] = -999; $return['erroreDescrizione'] = "Servizio Momentaneamente Non Disponibile"; } } curl_close($ch); return ($return); } public static function sendPwdResetFirebase($email = "") { $return = array(); $endpoint = LINK_FIREBASE . "accounts:sendOobCode?key=" . API_FIREBASE_KEY; $postvars = json_encode(array( requestType => "PASSWORD_RESET", email => $email, )); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); $result = curl_exec($ch); $arrayresponse = json_decode($result, true); $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_errno = curl_errno($ch); if ($http_status == 200) { $return['esito'] = 1; $return['dati'] = $arrayresponse; } else { // Utils::print_array($arrayresponse); if (is_array($arrayresponse['error'])) { $return['esito'] = -999; $return['erroreDescrizione'] = Utils::verifyErroriGoogle($arrayresponse['error']['message']); } else { $return['esito'] = -999; $return['erroreDescrizione'] = "Servizio Momentaneamente Non Disponibile"; } } curl_close($ch); return ($return); } /* * Controllo se L'utente ha preso visione dell'accettazione dei dati */ public static function checkViewConsent() { global $LoggedAccount; if ($_SERVER['REQUEST_URI'] != PERCORSO_CONSENSO) { if ($LoggedAccount->CONSENSO == 0) { header("Location:" . BASE_HTTP . 'modules/aziende/consenso.php'); } } } public static function dateOracleTimeStamp($data = "") { $converteddate = DateTime::createFromFormat("d-M-y h.i.s.u A", $data); $DateTime = $converteddate->format('d-m-Y H:i:s.u'); return $DateTime; } /** * Restituisce il contenuto di un tag * @param type $string * @param type $tag_open * @param type $tag_close * @return type */ public static function tag_contents($string, $tag_open, $tag_close) { foreach (explode($tag_open, $string) as $key => $value) { if (strpos($value, $tag_close) !== FALSE) { $result[] = substr($value, 0, strpos($value, $tag_close)); } } return $result; } /** * Verifico se il certificato del file firmato p7m è valido e se il codice fiscale del firmatario corrisponde al codice fiscale dell'utente loggato * @global type $LoggedAccount utente loggato * @param type $leggoCertificato certificato estratto * @return string */ public static function verifyCertificato($leggoCertificato) { global $LoggedAccount; $return = array(); $return['esito'] = -999; $return['descrizioneErrore'] = "Al momento non è possibile completare l'operazione"; $errori = array(); $cerco = self::tag_contents($leggoCertificato, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----"); foreach ($cerco as $scorrolefirme) { $datiCertificatoSearch = openssl_x509_parse("-----BEGIN CERTIFICATE-----\n" . trim($scorrolefirme) . "\n-----END CERTIFICATE-----"); if ($LoggedAccount->CODICE_FISCALE == self::extractCf($datiCertificatoSearch['subject']['serialNumber'])) { $verifyValidCertificateDate = self::verifyValidCertificateDate($datiCertificatoSearch['validFrom_time_t'], $datiCertificatoSearch['validTo_time_t']); if ($verifyValidCertificateDate['esito'] == 1) { $return['esito'] = 1; $return['descrizioneErrore'] = ""; } else { $return['esito'] = -999; $return['descrizioneErrore'] = "Certificato di firma digitale scaduto"; } return $return; } else { $return['esito'] = -999; $return['descrizioneErrore'] = "Errore 1: Il codice fiscale del soggetto firmatario del certificato " . "di firma, non è il medesimo dell'utente loggato"; } } return $return; } /** * Estrai li codice fiscale dal tag del certificato p7m * @param type $codice_fiscale * @return type */ public static function extractCf($codice_fiscale) { $cfrevisitedexplode = explode("-", $codice_fiscale); if ($cfrevisitedexplode[1] == "") { $cfrevisitedexplode = explode(":", $codice_fiscale); $cfrevisited = $cfrevisitedexplode[1]; } else { $cfrevisited = $cfrevisitedexplode[1]; } return $cfrevisited; } /** * Verifica la scadenza del certificato p7m * @param type $validFrom * @param type $validTo * @return string */ public static function verifyValidCertificateDate($validFrom, $validTo) { $dataAttuale = time(); if ($dataAttuale >= $validFrom && $dataAttuale <= $validTo) { $return['esito'] = 1; $return['descrizioneErrore'] = ""; } else { $return['esito'] = -999; $return['descrizioneErrore'] = "Certificato Scaduto"; } return $return; } public static function verifyCertificatoOLD($datiCertificato = "") { global $LoggedAccount; $dataAttuale = time(); $validFrom = $datiCertificato['validFrom_time_t']; $validTo = $datiCertificato['validTo_time_t']; if ($dataAttuale >= $validFrom && $dataAttuale <= $validTo) { } else { $return['esito'] = -999; $return['descrizioneErrore'] = "Certificato di firma digitale scaduto"; } return $return; } public static function verifyCertificatoRevisore($datiCertificato = "") { global $LoggedAccount; $dataAttuale = time(); $validFrom = $datiCertificato['validFrom_time_t']; $validTo = $datiCertificato['validTo_time_t']; if ($dataAttuale >= $validFrom && $dataAttuale <= $validTo) { $return['esito'] = 1; } else { $return['esito'] = -999; $return['descrizioneErrore'] = "Certificato di firma digitale scaduto"; } return $return; } /** * Funzione per lo spelling dei numeri * @param type $num * @param type $centOOttanta * @return string */ public static function spell_my_int($num, $centOOttanta = false) { $num = (int) $num; $mono = array("", "uno", "due", "tre", "quattro", "cinque", "sei", "sette", "otto", "nove"); $duplo = array("dieci", "undici", "dodici", "{$mono[3]}dici", "quattordici", "quindici", "sedici", "dicias{$mono[7]}", "dici{$mono[8]}", "dician{$mono[9]}"); $deca = array("", $duplo[0], "venti", "{$mono[3]}nta", "quaranta", "cinquanta", "sessanta", "settanta", "ottanta", "novanta"); $cento = array("cent", "cento"); $mili = array( 0 => array("", "mille", "milione", "miliardo", "bilione", "biliardo"), 1 => array("", "mila", "milioni", "miliardi", "bilioni", "biliardi") ); $max = pow(10, count($mili[0]) * 3) - 1; if (!is_numeric($num)) { return "Non è un numero!"; } elseif ($num < 0) { return "Numero negativo!"; } elseif ($num > $max) { return "Limite superato!"; } elseif ($num == 0) { return "zero"; } $result = ""; $sezione = 0; $num = (string) $num; switch (strlen($num) % 3) { case 1: $num = "00$num"; break; case 2: $num = "0$num"; } $numlen = strlen($num); while (($sezione + 1) * 3 <= $numlen) { $cifra = substr($num, (($numlen - 1) - (($sezione + 1) * 3)) + 1, 3); $numero = (int) $cifra; $cifra[0] = (int) $cifra[0]; $cifra[1] = (int) $cifra[1]; $cifra[2] = (int) $cifra[2]; if ($numero <> 0) { $prime2cifre = (int) ($cifra[1] . $cifra[2]); if ($prime2cifre < 10) { $text[2] = $mono[$cifra[2]]; $text[1] = ""; } elseif ($prime2cifre < 20) { $text[2] = ""; $text[1] = $duplo[$prime2cifre - 10]; } else { // ventitre => ventitrè if ($sezione == 0 && $cifra[2] == 3) { $text[2] = "trè"; } else { $text[2] = $mono[$cifra[2]]; } // novantaotto => novantotto if ($cifra[2] == 1 || $cifra[2] == 8) { $text[1] = substr($deca[$cifra[1]], 0, -1); } else { $text[1] = $deca[$cifra[1]]; } } if ($cifra[0] == 0) { $text[0] = ""; } else { // centoottanta => centottanta if (!$centOOttanta && $cifra[1] == 8 || ($cifra[1] == 0 && $cifra[2] == 8)) { $IDcent = 0; } else { $IDcent = 1; } if ($cifra[0] <> 1) { $text[0] = $mono[$cifra[0]] . $cento[$IDcent]; } else { $text[0] = $cento[$IDcent]; } } // unomille => mille // miliardo => unmiliardo if ($numero == 1 && $sezione <> 0) { if ($sezione >= 2) { $result = "un" . $mili[0][$sezione] . $result; } else { $result = $mili[0][$sezione] . $result; } } else { $result = $text[0] . $text[1] . $text[2] . $mili[1][$sezione] . $result; } } $sezione++; } return $result; } public static function getStrReplace($param = "") { $param = str_replace(".", ",", $param); return $param; } public static function getJwt($fields = array(), $secretkey = NULL) { $header = array( 'alg' => 'HS256', 'typ' => 'JWT' ); // Returns the JSON representation of the header $header = json_encode($header); //encodes the $header with base64. $header = self::base64url_encode($header); $payload = json_encode($fields); $payload = self::base64url_encode($payload); $signature = hash_hmac('SHA256', "$header.$payload", $secretkey, true); $signature = self::base64url_encode($signature); $jwtcreated = "$header.$payload.$signature"; return $jwtcreated; } public static function base64url_encode($data) { return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); } /** * Tronca il testo eliminando tutti i tag html contenuti in esso. * @param mixed $testo This il testo da troncare * @param mixed $caratteri This il numero dei catarreri da rstituire * * @return mixed Restituisce il testo troncato escluso anche dai tag html * * */ public static function troncaTesto($testo, $caratteri = 50) { $testo = strip_tags($testo); if (strlen($testo) <= $caratteri) return $testo; $nuovo = wordwrap($testo, $caratteri, "|"); $nuovotesto = explode("|", $nuovo); return $nuovotesto[0] . "..."; } /** * * @return string */ public function randomHex() { $chars = 'ABCDEF0123456789'; $color = '#'; for ($i = 0; $i < 6; $i++) { $color .= $chars[rand(0, strlen($chars) - 1)]; } return $color; } /* * Controllo la luminosita del colore */ public static function getContrast50($hexcolor) { return (hexdec($hexcolor) > 0xffffff / 2) ? '000000' : 'ffffff'; //'black':'white'; } /** * Restituisce il codice ATECO al netto dei punti e degli zeri finali * @param type $ateco * @return type */ public function normalizzaATECO($ateco = '') { $char = "0"; $res = ""; if ($ateco != "") { //echo "Originale ===> ".$ateco."
"; $ateco = str_ireplace('.', '', $ateco); //echo "Senza punti ===> ".$ateco2."
"; $ateco = rtrim($ateco, $char); //echo "Senza zeri finali ===> ".$ateco3."
"; $res = $ateco; } return $res; } public static function GetStatoSportello() { $oggi = new DateTime(); $response = 0; $manutenzione = 0; $preparazione = 0; $presentazione = 0; /* MANUTENZIONE */ $dtStart = new DateTime(DATA_MANUTENZIONE_INIZIO); $dtEnd = new DateTime(DATA_MANUTENZIONE_FINE); $start = Utils::DateDiff('s', $oggi->format('Y-m-d H:i:s'), $dtStart->format('Y-m-d H:i:s'), false, false); $end = Utils::DateDiff('s', $dtEnd->format('Y-m-d H:i:s'), $oggi->format('Y-m-d H:i:s'), false, false); if ($start < 0 && $end < 0) { $manutenzione = 1; } else { $manutenzione = 0; } /* END MANUTENZIONE */ /* PREPARAZIONE */ $dt_prep_Start = new DateTime(DATA_PREPARAZIONE_INIZIO); $dt_prep_End = new DateTime(DATA_PREPARAZIONE_FINE); $start_prep = Utils::DateDiff('s', $oggi->format('Y-m-d H:i:s'), $dt_prep_Start->format('Y-m-d H:i:s'), false, false); $end_prep = Utils::DateDiff('s', $dt_prep_End->format('Y-m-d H:i:s'), $oggi->format('Y-m-d H:i:s'), false, false); if ($start_prep < 0 && $end_prep < 0) { $preparazione = 1; } else { $preparazione = 0; } /* PRESENTAZIONE */ $dt_pres_Start = new DateTime(DATA_ATTESTATI_INIZIO); $dt_pres_End = new DateTime(DATA_ATTESTATI_FINE); $start_pres = Utils::DateDiff('s', $oggi->format('Y-m-d H:i:s'), $dt_pres_Start->format('Y-m-d H:i:s'), false, false); $end_pres = Utils::DateDiff('s', $dt_pres_End->format('Y-m-d H:i:s'), $oggi->format('Y-m-d H:i:s'), false, false); if ($start_pres < 0 && $end_pres < 0) { $presentazione = 1; } else { $presentazione = 0; } /* END PREPARAZIONE */ if (intval($manutenzione) == 1) {//SPORTELLO_MANUTENZIONE $response = SPORTELLO_MANUTENZIONE; } else if (intval($preparazione) == 1) {//SPORTELLO_PREPARAZIONE $response = SPORTELLO_PREPARAZIONE; } else if (intval($presentazione) == 1) { $response = SPORTELLO_PRESENTAZIONE; } else if (intval($preparazione) == 0 && $end_prep < 0) { $response = SPORTELLO_PREPARAZIONE_PRE; } else if (intval($preparazione) == 0 && intval($presentazione) == 0 && $end_pres < 0) { $response = SPORTELLO_PRESENTAZIONE_PRE; } else if (intval($preparazione) == 0 && intval($presentazione) == 0 && $end_pres > 0) { $response = SPORTELLO_PRESENTAZIONE_POST; } return $response; } }