CODICE_FISCALE, 9, 2))); $response = ($sesso <= 31 ? 'M' : 'F'); } return $response; } public static function getIntestazioniFromSexByCF($codiceFiscale = '') { $response = array( 'sesso' => '', 'sottoscritto' => '', 'natoa' => '' ); if (!empty($codiceFiscale)) { $sesso = intval((substr($LoggedAccount->CODICE_FISCALE, 9, 2))); $response = array( 'sesso' => ($sesso <= 31 ? 'M ' : 'F'), 'sottoscritto' => ($sesso <= 31 ? 'Il sottoscritto ' : 'La sottoscritta '), 'natoa' => ($sesso <= 31 ? 'nato a ' : 'nata a ') ); } return $response; } public static function checkLoginCredentials($username = '', $password = '') { $response['esito'] = -999; if (!EmailSms::checkEmail($username)) { $response['erroreDescrizione'] = "Username/Email non valida"; } else if (!Utils::checkPassword($password)) { $response['erroreDescrizione'] = "Verificare la password inserita"; } else { $response['esito'] = 1; } // Utils::print_array($response); return $response; } public static function getDecodedField($value = "") { return html_entity_decode(htmlspecialchars_decode($value)); } public static function getStreamField($value = "") { return html_entity_decode(htmlspecialchars_decode(stream_get_contents($value))); } public static function checkPassword($password = "") { return (!empty($password) && strlen($password) >= MIN_PASSWORD_LENGHT ? true : false); } /** * Verifica la scelta di una password sicura * @param $password * @return boolean * */ public static function verificaPassword($password) { $response = Utils::initDefaultResponse(); // Lunghezza minima della password $lunghezzaMinima = MIN_PASSWORD_LENGHT; // Almeno una lettera maiuscola $contieneMaiuscole = preg_match('/[A-Z]/', $password); // Almeno una lettera minuscola $contieneMinuscole = preg_match('/[a-z]/', $password); // Almeno un numero $contieneNumeri = preg_match('/[0-9]/', $password); // Almeno un carattere speciale $contieneCaratteriSpeciali = preg_match('/[^A-Za-z0-9]/', $password); // Controllo sulla lunghezza minima if (strlen($password) < $lunghezzaMinima) { $response['esito'] = -1; $response['erroreDescrizione'] = "La password deve contenere almeno $lunghezzaMinima caratteri."; return $response; } // Controllo sulla presenza di lettere maiuscole if (!$contieneMaiuscole) { $response['esito'] = -1; $response['erroreDescrizione'] = "La password deve contenere almeno una lettera maiuscola."; return $response; } // Controllo sulla presenza di lettere minuscole if (!$contieneMinuscole) { $response['esito'] = -1; $response['erroreDescrizione'] = "La password deve contenere almeno una lettera minuscola."; return $response; } // Controllo sulla presenza di numeri if (!$contieneNumeri) { $response['esito'] = -1; $response['erroreDescrizione'] = "La password deve contenere almeno un numero."; return $response; } // Controllo sulla presenza di caratteri speciali if (!$contieneCaratteriSpeciali) { $response['esito'] = -1; $response['erroreDescrizione'] = "La password deve contenere almeno un carattere speciale."; return $response; } $response['esito'] = 1; // Se la password supera tutti i controlli, è considerata sicura return $response; } public static function checkLogin() { if (!isset($_SESSION['ID'])) { header("Location: " . PATH_LOGIN); } } public static function checkLoginWS() { return isset($_SESSION['ID']); } public static function IsAmministratore() { global $LoggedAccount; if ($LoggedAccount->SUPER_USER <> 1) { header("Location: " . BASE_HTTP . "login.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; } function stringEndsWith($string, $endString) { $len = strlen($endString); if ($len == 0) { return true; } return (substr($string, -$len) === $endString); } /* * Normalize default value for type & check field funzione */ public static function getArrayValueOrNull($array, $value) { return (!isset($array[$value]) ? NULL : $array[$value]); } public static function normalizeDefaultValueTypeString($value) { return $value == "" ? NULL : $value; } public static function normalizeDefaultValueTypeNumber($value) { return $value == "" ? 0 : $value; } public static function normalizeDefaultValueTypeDate($value, $format = "Y-m-d") { if (empty($value)) { $value = NULL; } else { $value = strtotime($value); $value = date($format, $value); } return $value; } public static function isNull($value) { return !empty($value) ? false : true; } 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 getCheckInputIntValue($inputArray = array(), $field = '') { return (isset($inputArray[$field]) && strtolower($_REQUEST[$field]) == 'on' ? 1 : 0); } /* * 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(self::get_filter_int($element)); $ritorno[$key] = $nuovoValorNumeric; } else { if ($key != "action" && $key != "module" && $key != "password") { $nuovoValorString = trim((Utils::get_filter_string($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; } /* * *********************** * controlli sulle stringe * *********************** */ 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_POST($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 } /* * Restituisce i valori da una funzione non da input */ public static function get_filter_int($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($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 } /** * 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_POST($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 } */ public static function is_base64_encoded($data) { // if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) { if ($data === base64_encode(base64_decode($data))) { return TRUE; } else { return FALSE; } } /* * decodifica il valora dalla string base64 (se codificato) */ public static function decodeBase64value($field = '') { $response = ''; if ($field != '' && self::is_base64_encoded($field)) { $response = base64_decode($field); } else { $response = $field; } return $response; } 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 getStrReplace($param = "") { $param = str_replace(".", ",", $param); return $param; } /** * 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] . "..."; } /** * 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)); 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; } return $newsrc; } 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; } /** * 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; } /* * ***************************************************** * DB UTILS * ***************************************************** */ public static function pdo_debugStrParams($stmt) { ob_start(); $stmt->debugDumpParams(); $r = ob_get_contents(); ob_end_clean(); return $r; } /** * 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 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); } /** * * @param type $text * @param type $exit default false */ public static function print_debug($text = "", $exit = false) { echo "
DEBUG:
" . $text . "";
if ($exit) {
exit();
}
}
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; } /* * 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:" . PERCORSO_CONSENSO); // } // } } /** * 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; } /** * 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 getClientIp() { $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 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), '+/', '-_'), '='); } public static function getUTF8($element = '') { $response = $element; if (!is_array($element)) { $response = utf8_encode($element); } return $response; } /** * * @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 static function normalizzaATECO($ateco = '') { $char = "0"; $res = ""; if ($ateco != "") { //echo "Originale ===> ".$ateco."