<?php

	include ("formatter.php");

/**
 * Sostituisce gli invii a capo e gli apici singoli con il relativo in HTML.
 *
 * @param unknown $text
 * @return mixed
 */
function fix_str($text) {
	$text = str_replace("\r\n", "<br/>", $text);
	$text = str_replace("'", "&rsquo;", $text);
	$text = mres($text);
	return $text;
}

/**
 * Funzione di sostituzione a mysql_real_escape_string()/mysql_escape_string().
 *
 * @param string $value
 * @return mixed
 */
function mres($value) {
	$search = array("\\","\x00","\n","\r","'",'"',"\x1a");
	$replace = array("\\\\","\\0","\\n","\\r","\'",'\"',"\\Z");
	return str_replace($search, $replace, $value);
}

/**
 * Rimuove eventuali carattari speciali dalla stringa.
 *
 * @param unknown $text
 * @return mixed
 */
function clean($string) {
	$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
	$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
	return preg_replace('/-+/', ' ', $string);
	// Replaces multiple hyphens with single one.
}

/**
 * Trasforma un testo in un nome di id valido per l'html (sostituisce gli spazi).
 *
 * @param unknown $text
 * @return mixed
 */
function makeid($text) {
	$text = strtolower($text);
	$text = str_replace(" ", "_", $text);
	return $text;
}

/**
 * Sostituisce ", < e > per evitare hacking del database e risolvere vari problemi.
 *
 * @param unknown $text
 * @return string
 */
function save($text) {
	$text = htmlentities($text, ENT_QUOTES, "UTF-8");
	return $text;
}

/**
 * Legge il valore di un'impostazione dalla tabella zz_impostazioni.
 * Se descrizione = 1 e il tipo è 'query=' mi restituisce il valore del campo descrizione della query.
 *
 * @param unknown $name
 * @param string $sezione
 * @param string $descrizione
 * @return mixed
 */
function get_var($name, $sezione = "", $descrizione = "") {
	global $dbo;
	if ($sezione == '') $rs = $dbo->fetchArray("SELECT valore,tipo FROM zz_impostazioni WHERE nome=\"$name\"");
	else $rs = $dbo->fetchArray("SELECT valore,tipo FROM zz_impostazioni WHERE nome=\"$name\" AND sezione=\"$sezione\" ");
	if (($descrizione == '') or ($descrizione == 0)) {
		return $rs[0]['valore'];
	}
	else {
		if (strpos($rs[0]['tipo'], 'query=') !== false) {
			$q2 = str_replace('query=', '', $rs[0]['tipo']);
			$rs2 = $dbo->fetchArray($q2);
			if (sizeof($rs2) > 0) {
				return $rs2[0]['descrizione'];
			}
			else {
				return $rs2[0]['valore'];
			}
		}
		else {
			return $rs2[0]['valore'];
		}
	}
}

/**
 * Sostituisce la sequenza &quot; con " (da HTMLEntities a visualizzabile)
 *
 * @param unknown $text
 */
function read($text) {
	return str_replace("&quot;", "\"", $text);
}

/**
 * Taglia un testo ($str) al numero di caratteri stabilito ($length), fermandosi però al primo spazio successivo
 * per non troncare una parola se specificato $at_next_space=1
 *
 * @param unknown $str
 * @param unknown $length
 * @param number $at_next_space
 * @return string|unknown
 */
function cut_text($str, $length, $at_next_space = 0) {
	if (strlen($str) > $length) {
		$s = substr($str, 0, $length);
		if ($at_next_space) {
			for($i = $length; $i < strlen($str); $i ++) {
				$carattere = substr($str, $i, 1);
				if ($carattere == " " || $carattere == ",") return $s . "...";
				else $s .= $carattere;
			}
		}
		else
			$s .= "...";
		return $s;
	}
	else
		return $str;
}

/**
 * Esegue il redirect.
 *
 * @param unknown $url
 * @param string $type
 * @return boolean
 */
function redirect($url, $type = "php") {
	switch ($type) {
		case "php" :
			header("Location: $url");
			break;
		case "js" :
			echo "<script type=\"text/javascript\">location.href='$url';</script>";
	}
	return true;
}

/**
 * Crea il formato della data modificanto il campo di input (JQuery Datepicker).
 *
 * @param unknown $data
 */
function saveDate($data) {
	if ($data == '') {
		return '0000-00-00';
	}
	else {
		$date = explode('/', $data);
		$date = $date[1] . '/' . $date[0] . '/' . $date[2];
		$date = strtotime($date);
		return date('Y-m-d', $date);
	}
}

/**
 * Crea il formato della data leggendo dal database (?) e modificanto il campo di input (JQuery Datepicker).
 *
 * @param unknown $data
 */
function readDate($data) {
	$date = $data;
	if ($date != '') {
		$date = explode('-', $date);
		$date = $date[2] . '/' . $date[1] . '/' . $date[0];
	}
	return $date;
}

/**
 * Carica gli script JavaScript inclusi nell'array indicato.
 *
 * @param unknown $jscript_modules_array
 */
function loadJscriptModules($jscript_modules_array) {
	foreach ($jscript_modules_array as $jsname) {
		echo "<script type=\"text/javascript\" charset=\"utf-8\" src=\"$jsname\"></script>\n";
	}
}

/**
 * Carica i file di stile CSS inclusi nell'array indicato.
 *
 * @param unknown $jscript_modules_array
 */
function loadCSSModules($css_modules_array) {
	foreach ($css_modules_array as $css) {
		if (is_array($css)) echo "<link rel=\"stylesheet\" type=\"text/css\" media=\"" . $css['media'] . "\" href=\"" . $css['dir'] . "\"/>\n";
		else echo "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"$css\"/>\n";
	}
}

/**
 * Legge la versione del software in uso
 *
 * @param string $file
 * @return mixed
 */
function getVersion($file = 'VERSION') {
	global $docroot;
	$version = file_get_contents($docroot . "/" . $file);
	$version = str_replace("\r\n", '', $version);
	$version = str_replace("\n", '', $version);
	return $version;
}

/**
 * Legge la revisione del software in uso
 *
 * @param string $file
 * @return mixed
 */
function getRevision($file = 'REVISION') {
	global $docroot;
	$revision = file_get_contents($docroot . "/" . $file);
	$revision = str_replace("\r\n", '', $revision);
	$revision = str_replace("\n", '', $revision);
	return $revision;
}

/**
 * Legge l'ora nel formato hh:mm
 *
 * @param unknown $time
 * @return string
 */
function readTime($time) {
	$vtime = explode(':', $time);
	$hour = $vtime[0];
	$minutes = $vtime[1];
	$seconds = $vtime[2];
	return "$hour:$minutes";
}

/**
 * Salva l'ora controllando che non vi siano inseriti contenuti inappropriati.
 *
 * @param unknown $time
 * @return mixed
 */
function saveTime($time) {
	// scrive solo l'ora (16, oppure 9)
	$result = $time;
	if (preg_match("/^([0-9]{1,2})$/", $time)) $result = "$time:00:00";
	$result = str_replace(',', ':', $result);
	$result = str_replace('.', ':', $result);
	return $result;
}

/**
 * Verifica e corregge il nome di un file.
 *
 * @param unknown $filename
 * @return mixed
 */
function sanitizeFilename($filename) {
	$filename = str_replace(" ", "-", $filename);
	$filename = preg_replace("/[^A-Za-z0-9_\-\.?!]/", "", $filename);
	return $filename;
}

/**
 * Rimuove ricorsivamente una directory.
 *
 * @param unknown $path
 * @return boolean
 */
function deltree($path) {
	if (is_dir($path)) {
		if (version_compare(PHP_VERSION, '5.0.0') < 0) {
			$entries = array();
			if ($handle = opendir($path)) {
				while ( false !== ($file = readdir($handle)) )
					$entries[] = $file;
				closedir($handle);
			}
		}
		else {
			$entries = scandir($path);
			if ($entries === false) $entries = array(); // just in case scandir fail...
		}
		foreach ($entries as $entry) {
			if ($entry != '.' && $entry != '..') {
				deltree($path . '/' . $entry);
			}
		}
		return rmdir($path);
	}
	else {
		return unlink($path);
	}
}

/**
 * Copy a file, or recursively copy a folder and its contents
 *
 * @author Aidan Lister <aidan@php.net>
 * @version 1.0.1
 * @link http://aidanlister.com/repos/v/function.copyr.php
 * @param string $source
 *        	Source path
 * @param string $dest
 *        	Destination path
 * @param string $exclude
 *        	Path to exclude
 * @return bool Returns TRUE on success, FALSE on failure
 */
function copyr($source, $dest, $exclude) {
	if (! is_array($exclude)) $exclude = array($exclude);
	// Simple copy for a file
	if (is_file($source) && (! in_array($source, $exclude))) {return copy($source, $dest);}
	// Make destination directory
	if (! is_dir($dest)) {
		mkdir($dest);
	}
	// If the source is a symlink
	if (is_link($source)) {
		$link_dest = readlink($source);
		return symlink($link_dest, $dest);
	}
	// Loop through the folder
	$dir = dir($source);
	while ( false !== $entry = $dir->read() ) {
		// Skip pointers
		if ($entry == '.' || $entry == '..') {
			continue;
		}
		// Deep copy directories
		if ($dest !== $source . "/" . $entry) {
			$go = true;
			foreach ($exclude as $excluded) {
				if (strstr($source . "/" . $entry . "/", $excluded)) $go = false;
			}
			if ($go) copyr($source . "/" . $entry, $dest . "/" . $entry, $exclude);
		}
	}
	// Clean up
	$dir->close();
	return true;
}

/**
 * Crea un file zip comprimendo ricorsivamente tutte le sottocartelle a partire da una cartella specificata
 *
 * @link http://stackoverflow.com/questions/1334613/how-to-recursively-zip-a-directory-in-php
 * @param unknown $source
 * @param unknown $destination
 */
function create_zip($source, $destination) {
	if (! extension_loaded('zip') || ! file_exists($source)) {
		array_push($_SESSION['errors'], "Estensione zip non supportata!");
		return false;
	}
	
	$zip = new ZipArchive();
	
	if ($zip->open($destination, ZIPARCHIVE::CREATE)) {
		$source = str_replace(array('\\','/'), DIRECTORY_SEPARATOR, realpath($source));
		
		if (is_dir($source) === true) {
			$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
			
			foreach ($files as $file) {
				$file = str_replace(array('\\','/'), DIRECTORY_SEPARATOR, realpath($file));
				$file = str_replace($source . DIRECTORY_SEPARATOR, '', $file);
				
				if (is_dir($file) === true) {
					$zip->addEmptyDir($file);
				}
				else if (is_file($file) === true) {
					$zip->addFromString($file, file_get_contents($file));
				}
			}
			
		}
		else if (is_file($source) === true) {
			$zip->addFromString(basename($source), file_get_contents($source));
		}

		$zip->close();

		return true;
	}
	else {
		array_push($_SESSION['errors'], "Errore durante la creazione dell'archivio!");
		return false;
	}
}

/**
 * Individua la differenza tra le date indicate.
 * $interval può essere:
 * 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)
 *
 * @param unknown $interval
 * @param unknown $datefrom
 * @param unknown $dateto
 * @param string $using_timestamps
 */
function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
	if (! $using_timestamps) {
		$datefrom = strtotime($datefrom, 0);
		$dateto = strtotime($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 $datediff;
}

/**
 * Controllo dei file zip e gestione errori
 *
 * @param unknown $zip_file
 * @return string|boolean
 */
function checkZip($zip_file) {
	$errno = zip_open($zip_file);
	zip_close($errno);
	if (! is_resource($errno)) {
		// using constant name as a string to make this function PHP4 compatible
		$zipFileFunctionsErrors = array('ZIPARCHIVE::ER_MULTIDISK' => 'archivi multi-disco non supportati','ZIPARCHIVE::ER_RENAME' => 'ridenominazione del file temporaneo fallita','ZIPARCHIVE::ER_CLOSE' => 'impossibile chiudere il file zip','ZIPARCHIVE::ER_SEEK' => 'errore durante la ricerca dei file','ZIPARCHIVE::ER_READ' => 'errore di lettura','ZIPARCHIVE::ER_WRITE' => 'errore di scrittura','ZIPARCHIVE::ER_CRC' => 'errore CRC','ZIPARCHIVE::ER_ZIPCLOSED' => 'l&rsquo;archivio zip &eacute; stato chiuso','ZIPARCHIVE::ER_NOENT' => 'file non trovato','ZIPARCHIVE::ER_EXISTS' => 'il file esiste gi&agrave;','ZIPARCHIVE::ER_OPEN' => 'impossibile aprire il file','ZIPARCHIVE::ER_TMPOPEN' => 'impossibile creare il file temporaneo','ZIPARCHIVE::ER_ZLIB' => 'errore nella libreria Zlib','ZIPARCHIVE::ER_MEMORY' => 'fallimento nell&rsquo;allocare memoria','ZIPARCHIVE::ER_CHANGED' => 'voce modificata','ZIPARCHIVE::ER_COMPNOTSUPP' => 'metodo di compressione non supportato','ZIPARCHIVE::ER_EOF' => 'fine del file non prevista','ZIPARCHIVE::ER_INVAL' => 'argomento non valido','ZIPARCHIVE::ER_NOZIP' => 'file zip non valido','ZIPARCHIVE::ER_INTERNAL' => 'errore interno','ZIPARCHIVE::ER_INCONS' => 'archivio zip inconsistente','ZIPARCHIVE::ER_REMOVE' => 'impossibile rimuovere la voce','ZIPARCHIVE::ER_DELETED' => 'voce eliminata');
		foreach ($zipFileFunctionsErrors as $constName => $errorMessage) {
			if (defined($constName) and constant($constName) === $errno) {return "Errore: $errorMessage";}
		}
	}
	else
		return true;
}

/**
 * Funzione per fare il dump del database
 *
 * @link http://davidwalsh.name/backup-mysql-database-php
 * @param string $tables
 * @return string
 */
function backup_tables($tables = '*') {
	global $dbo;
	if ($tables == '*') {
		$tables = array();
		$result = $dbo->fetchRows("SHOW TABLES");
		if ($result != null) {
			foreach ($result as $res)
				$tables[] = $res[0];
		}
	}
	else {
		$tables = is_array($tables) ? $tables : explode(',', $tables);
	}
	// Eliminazione di tutte le tabelle
	foreach ($tables as $table) {
		$return .= "delete from  `$table`;\n";
	}
	// Ricreazione della struttura di ogni tabella e ri-popolazione database
	foreach ($tables as $table) {
		$result = $dbo->fetchRows('SELECT * FROM ' . $table);
		$num_fields = count($result[0]);
		$row2 = $dbo->fetchArray('SHOW CREATE TABLE ' . $table);
		$return .= "\n" . $row2[1] . ";\n";
	
		$num_record="1";
	//	for($i = 0; $i < sizeof($result); $i ++) {
		 for($i = 0; $i < $num_record; $i ++) {
			if ($result != false) {
				foreach ($result as $row) {
					$return .= 'INSERT INTO ' . $table . ' VALUES(';
					for($j = 0; $j < $num_fields; $j ++) {
						$row[$j] = addslashes($row[$j]);
						$row[$j] = str_replace("\r\n", "\\n", $row[$j]);
						$row[$j] = str_replace("\n", "\\n", $row[$j]);
						if (isset($row[$j])) {
							$return .= '"' . $row[$j] . '"';
						}
						else {
							$return .= '""';
						}
						if ($j < ($num_fields - 1)) {
							$return .= ',';
						}
					}
					$return .= ");\n";
				}
			}
		}
		$return .= "\n";
	}
	return $return;
	// save file
	// $handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
	// fwrite($handle,$return);
	// fclose($handle);
}

/**
 * Scurisce un determinato colore.
 *
 * @param unknown $color
 * @param number $dif
 * @return string
 */
function ColorDarken($color, $dif = 20) {
	$color = str_replace('#', '', $color);
	if (strlen($color) != 6) {return '000000';}
	$rgb = '';
	for($x = 0; $x < 3; $x ++) {
		$c = hexdec(substr($color, (2 * $x), 2)) - $dif;
		$c = ($c < 0) ? 0 : dechex($c);
		$rgb .= (strlen($c) < 2) ? '0' . $c : $c;
	}
	return '#' . $rgb;
}

/**
 * Recupera informazioni sistema operativo dell'utente.
 *
 * @return string
 */
function GetSistemaOperativo() {
	$os = array('Windows NT 6.1' => 'Windows 7','Windows NT 6.0' => 'Windows Vista','Windows NT 5.1' => 'Windows XP','Windows NT 5.0' => 'Windows 2000','Windows NT 4.90' => 'Windows ME','Win95' => 'Windows 95','Win98' => 'Windows 98','Windows NT 5.2' => 'Windows NET','WinNT4.0' => 'Windows NT','Mac' => 'Mac','PPC' => 'Mac','Linux' => 'Linux','FreeBSD' => 'FreeBSD','SunOS' => 'SunOS','Irix' => 'Irix','BeOS' => 'BeOS','OS/2' => 'OS/2','AIX' => 'AIX');
	foreach ($os as $chiave => $valore) {
		if (strpos($_SERVER['HTTP_USER_AGENT'], $chiave)) {return $valore;}
	}
	return "Altro";
}

/**
 * Legge una stringa presumibilmente codificata (tipo "8D001") e, se possibile, restituisce il codice successivo ("8D002")
 *
 * @param $str string
 *        	Codice di partenza da incrementare
 * @param $qty int
 *        	Unità da aggiungere alla parte numerica del codice (di default incrementa di 1).
 * @param $mask string
 *        	Specifica i caratteri da sostituire con numeri nel caso di generazione di codici complessi (esempio: se un codice attuale fosse 56/D e volessi calcolare il successivo (57/D), dovrei usare una maschera. La maschera in questo caso potrebbe essere ##/D. In questo modo so che i caratteri ## vanno sostituiti da numeri e il totale di caratteri sarà 2. Quindi il primo codice non sarebbe 1/D, ma 01/D).
 */
function get_next_code($str, $qty = 1, $mask = '') {
	// Se è il primo codice che sto inserendo sostituisco gli zeri al carattere jolly #
	if ($str == '') $str = str_replace("#", "0", $mask);
	// Se non uso una maschera, estraggo l'ultima parte numerica a destra della stringa e la incremento
	if ($mask == '') {
		preg_match("/(.*?)([\d]*$)/", $str, $m);
		$first_part = $m[1];
		$numeric_part = $m[2];
		// Se non c'è una parte numerica ritorno stringa vuota
		if ($numeric_part == '') return '';
		else {
			$pad_length = strlen($numeric_part);
			$second_part = str_pad(intval($numeric_part) + $qty, $pad_length, "0", STR_PAD_LEFT);
			return $first_part . $second_part;
		}
	}
	// Utilizzo della maschera
	else {
		// Calcolo prima parte (se c'è)
		$pos1 = strpos($mask, "#");
		$first_part = substr($str, 0, $pos1);
		// Calcolo terza parte (se c'è)
		$pos2 = strlen($str) - strpos(strrev($mask), "#");
		$third_part = substr($str, $pos2, strlen($mask));
		// Calcolo parte numerica
		$numeric_part = substr($str, $pos1, $pos2);
		$pad_length = intval(strlen($numeric_part));
		$first_part_length = intval(strlen($first_part));
		$third_part_length = intval(strlen($third_part));
		$numeric_part = str_pad(intval($numeric_part) + intval($qty), $pad_length, "0", STR_PAD_LEFT);
		// $numeric_part = str_pad( intval($numeric_part)+intval($qty), ( $pad_length - $third_part_length ), "0", STR_PAD_LEFT );
		return $first_part . $numeric_part . $third_part;
	}
}

/**
 * Restituisce l'ultima directory prima della pagina php richiamata
 *
 * @param string $url
 * @return string
 */
function getLastPathSegment($url) {
	$path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
	$pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
	$pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash
	if (substr($path, - 1) !== '/') {
		array_pop($pathTokens);
	}
	return end($pathTokens);
	// get the last segment
}

/**
 * Legge i permessi del modulo selezionato e dell'utente corrente e li ritorna come stringa.
 *
 * @param string $nome_modulo
 * @return string
 */
function get_permessi($nome_modulo) {
	global $dbo;
	$query = "SELECT *, (SELECT idanagrafica FROM zz_utenti WHERE idutente='" . $_SESSION['idutente'] . "') AS idanagrafica FROM zz_permessi WHERE idgruppo=(SELECT idgruppo FROM zz_utenti WHERE idutente='" . $_SESSION['idutente'] . "') AND idmodule=(SELECT id FROM zz_modules WHERE name='" . $nome_modulo . "')";
	$rs = $dbo->fetchArray($query);
	if (sizeof($rs) <= 0) {
		// Ultimo tentativo: se non ci sono i permessi ma sono l'amministratore posso comunque leggere il modulo
		if (isAdminAutenticated()) {
			return 'rw';
		}
		else {
			return '-';
		}
	}
	else {
		if ($rs[0]['permessi'] == '-') {
			return '-';
		}
		else if ($rs[0]['permessi'] == 'r') {
			return 'r';
		}
		else if ($rs[0]['permessi'] == 'rw') {return 'rw';}
	}
}

/**
 * Esegue le operazioni di accesso e di log a gest366.
 *
 * @param string $idutente
 * @param string $username
 * @param string $password
 * @param string $autenticato
 * @param string $abilitato
 * @param string $gruppo
 */
function logaccessi($idutente, $username, $password, $autenticato, $abilitato, $gruppo) {
	global $dbo;
	$password = "*****";
	if ($autenticato <= 0) {
		$stato = 0;
	}
	else {
		$stato = 1;
		if ($abilitato == 0) {
			$stato = 2;
		}
		if ($gruppo != 'Amministratori') {
			$q = "SELECT id, module_dir, options FROM zz_modules WHERE parent='0' AND enabled='1' AND id IN (SELECT idmodule FROM zz_permessi WHERE idgruppo=(SELECT id FROM zz_gruppi WHERE nome='" . $gruppo . "') AND permessi IN ('r', 'rw') ) AND type='menu' ORDER BY `order` ASC";
			$rs = $dbo->fetchArray($q);
			if (sizeof($rs) <= 0) $stato = 3;
		}
	}

	$dbo->query("INSERT INTO zz_log( idutente, username, password, timestamp, ip, stato ) VALUES( \"" . $idutente . "\", \"" . $username . "\", \"" . $password . "\", NOW(), \"" . $_SERVER['REMOTE_ADDR'] . "\", \"" . $stato . "\" )");
}

/**
 * Restituisce l'estensione del file
 *
 * @param string $string
 */
function estensione_del_file($string) {
	$f = pathinfo($string);
	return $f['extension'];
}
/**
 * Se il server non supporta "parse_ini_string" lo simulo
 */
if (! function_exists('parse_ini_string')) {

	/**
	 * Simulazione di "parse_ini_string".
	 *
	 * @param unknown $ini
	 * @param string $process_sections
	 * @param unknown $scanner_mode
	 */
	function parse_ini_string($ini, $process_sections = false, $scanner_mode = null) {
		// Generate a temporary file.
		$tempname = tempnam('/tmp', 'ini');
		$fp = fopen($tempname, 'w');
		fwrite($fp, $ini);
		$ini = parse_ini_file($tempname, ! empty($process_sections));
		fclose($fp);
		@unlink($tempname);
		return $ini;
	}
}

/**
 * Forza una string a essere un numero decimale (sostituisce , con .)
 *
 * @param unknown $str
 * @return number
 */
function force_decimal($str) {
	$str = str_replace(",", ".", $str);
	return floatval($str);
}

/**
 *
 * @param unknown $datetime
 * @return string
 */
function saveDateTime($datetime) {
	$data = substr($datetime, 0, - 6);
	$date = explode('/', $data);
	$date = $date[1] . '/' . $date[0] . '/' . $date[2];
	$date = strtotime($date);
	$date = date('Y-m-d', $date);
	$time = substr($datetime, - 5);
	$result = $time;
	$result = str_replace(',', ':', $result);
	$result = str_replace('.', ':', $result);
	$time = date('H:i', strtotime($result));
	$datetime = $date . " " . $time;
	return $datetime;
}

/**
 *
 * @param unknown $datetime
 * @return string
 */
function readDateTime($datetime) {
	$data = substr($datetime, 0, - 9);
	$date = explode('-', $data);
	$date = $date[2] . '/' . $date[1] . '/' . $date[0];
	$time = substr($datetime, - 8);
	$result = $time;
	$result = str_replace(',', ':', $result);
	$result = str_replace('.', ':', $result);
	$time = date('H:i', strtotime($result));
	$datetime = $date . " " . $time;
	return $datetime;
}

/**
 * Converte una stringa da un formato ad un altro
 * "2010-01-15 08:30:00" => "15/01/2010 08:30" (con $view='')
 * "2010-01-15 08:30:00" => "15/01/2010" (con $view='date')
 * "2010-01-15 08:30:00" => "08:30" (con $view='time')
 *
 * @param unknown $datetime
 * @param unknown $view
 * @return string
 */
function readDateTimePrint($datetime, $view) {
	$data = substr($datetime, 0, - 9);
	$date = explode('-', $data);
	$date = $date[2] . '/' . $date[1] . '/' . $date[0];
	$time = substr($datetime, - 8);
	$result = $time;
	$result = str_replace(',', ':', $result);
	$result = str_replace('.', ':', $result);
	$time = date('H:i', strtotime($result));
	$datetime = $date . " " . $time;
	if ($view == "date") return $date;
	if ($view == "time") return $time;
}

/**
 * Verifica che il nome del file non sia già usato nella cartella inserita, nel qual caso aggiungo un suffisso
 *
 * @param unknown $filename
 * @param unknown $dir
 * @return string
 */
function unique_filename($filename, $dir) {
	$f = pathinfo($filename);
	$suffix = 1;
	while ( file_exists($dir . "/" . $filename) ) {
		$filename = $f['filename'] . "_" . $suffix . "." . $f['extension'];
		$suffix ++;
	}
	return $filename;
}

/**
 * Crea le thumbnails di $filename da dentro $dir e le salva in $dir
 *
 * @param unknown $tmp
 * @param unknown $filename
 * @param unknown $dir
 * @return boolean
 */
function create_thumbnails($tmp, $filename, $dir) {
	$f = pathinfo($filename);
	$name = $f['filename'];
	$ext = strtolower($f['extension']);
	$photo = new Photo(array("name" => $name . "_thumb100." . $ext,"tmp_name" => $tmp));
	$photo->doThumb(100, $dir . "/");
	$photo = new Photo(array("name" => $name . "_thumb250." . $ext,"tmp_name" => $tmp));
	$photo->doThumb(250, $dir . "/");
	$photo = new Photo(array("name" => $name . "." . $ext,"tmp_name" => $tmp));
	$photo->doResize(600, $dir . "/");
	return true;
}

/**
 * Ottiene l'indirizzo IP del client.
 *
 * @return string|unknown
 */
function get_client_ip() {
	$ipaddress = '';
	if ($_SERVER['HTTP_CLIENT_IP']) $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
	else if ($_SERVER['HTTP_X_FORWARDED_FOR']) $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
	else if ($_SERVER['HTTP_X_FORWARDED']) $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
	else if ($_SERVER['HTTP_FORWARDED_FOR']) $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
	else if ($_SERVER['HTTP_FORWARDED']) $ipaddress = $_SERVER['HTTP_FORWARDED'];
	else if ($_SERVER['REMOTE_ADDR']) $ipaddress = $_SERVER['REMOTE_ADDR'];
	else $ipaddress = 'UNKNOWN';
	return $ipaddress;
}

/**
 * Esegue il backup dell'intero database.
 *
 * @return boolean
 */
function do_backup() {
	global $docroot;
	global $backup_dir;

	if (extension_loaded("zip")) {
		$tmp_backup_dir = "/tmp/";
	}
	else {
		$tmp_backup_dir = "/ges360 backup " . date("Y-m-d") . " " . date("H_i_s") . "/";
	}

	
	$tmp_backup_dir = "/Backup del " . date("Y-m-d") . " " . date("H_i_s") . "/";
	
	// Creazione cartella temporanea
	if (! file_exists($backup_dir . $tmp_backup_dir)) {
		if (@mkdir($backup_dir . $tmp_backup_dir)) {
			$do_backup = true;
		}
		else {
			$do_backup = false;
		}
	}
	else {
		$do_backup = true;
	}

	if ($do_backup) {
		$database_file = "bk_database.sql";
		$backup_file = "ges360_backup " . date("Y-m-d") . " " . date("H_i_s") . ".zip";
		// Dump database
		$dump = "SET foreign_key_checks = 0;\n";
		$dump .= backup_tables();
		file_put_contents($backup_dir . $tmp_backup_dir . $database_file, $dump);
		
		
		// Copia file di gest366 (escludendo la cartella di backup)
		copyr($docroot, $backup_dir . $tmp_backup_dir, array($backup_dir,"config.inc.php","mysql.log","setup.log"));
		// Creazione zip
		

		
		

	}

	return $do_backup;
}

/**
 * Inverte il colore inserito.
 *
 * @link http://www.splitbrain.org/blog/2008-09/18-calculating_color_contrast_with_php
 * @param unknown $start_colour
 * @return string
 */
function color_inverse($start_colour) {
	$R1 = hexdec(substr($start_colour, 1, 2));
	$G1 = hexdec(substr($start_colour, 3, 2));
	$B1 = hexdec(substr($start_colour, 5, 2));
	$R2 = 255;
	$G2 = 255;
	$B2 = 255;
	$L1 = 0.2126 * pow($R1 / 255, 2.2) + 0.7152 * pow($G1 / 255, 2.2) + 0.0722 * pow($B1 / 255, 2.2);
	$L2 = 0.2126 * pow($R2 / 255, 2.2) + 0.7152 * pow($G2 / 255, 2.2) + 0.0722 * pow($B2 / 255, 2.2);
	if ($L1 > $L2) {
		$lum = ($L1 + 0.05) / ($L2 + 0.05);
	}
	else {
		$lum = ($L2 + 0.05) / ($L1 + 0.05);
	}
	if ($lum >= 2.5) {
		return "#fff";
	}
	else {
		return "#000";
	}
}

/**
 * Dato un id, restituisce il nome del modulo relativo.
 *
 * @param unknown $filename
 * @param unknown $dir
 * @return string
 */
function get_module_name_by_id($id_module) {
	global $dbo;
	$rs = $dbo->fetchArray("SELECT name FROM zz_modules WHERE id = " . $id_module . " ");
	// Se c'è un modulo con questo id
	if (sizeof($rs) == 1) {
		$nome_modulo = $rs[0]['name'];
		return $nome_modulo;
	}
	else {
		array_push($_SESSION['errors'], "Controlla id del modulo!");
		return false;
	}
}

/**
 * Dato un elemento pricipale, costruisce tutti i sottomenu.
 *
 * @param string $filename
 * @param string $dir
 * @param string $dir
 * @return string
 */
function sidebarMenu($element, $permessi, $actual = "") {
	global $dbo;
	global $rootdir;

	$options = ($element['options2'] != "") ? $element['options2'] : $element['options'];
	$link = ($options != "" && $options != "menu") ? $rootdir . "/controller.php?id_module=" . $element['id'] : "javascript:;";
	$name = ($element['name2'] != '') ? $element['name2'] : $element['name'];
	$target = ($element['new'] == 1) ? "_blank" : "_self";

	$show = false;
	foreach ($permessi as $key => $value) {
		if ($value[0] == $element["id"]) $show = true;
	}

	$active = ($actual == $element['name']);

	$submenus = $dbo->fetchArray("SELECT * FROM zz_modules WHERE enabled='1' AND parent='" . $element['id'] . "' AND `type`='menu' ORDER BY `order` ASC");

	if ($submenus != null && count($submenus) != 0) {
		$temp = "";
		foreach ($submenus as $submenu) {
			$r = sidebarMenu($submenu, $permessi, $actual);
			$active = $active || $r[1];
			if (! $show && $r[2]) $link = "javascript:;";
			$show = $show || $r[2];
			$temp .= $r[0];
		}
	}

	$result = "";

	
	if ($show || isAdminAutenticated()) {
		$result .= '<li class="treeview';
		if ($active) $result .= ' active actual';
		$result .= '" id="' . $element['id'] . '">
			<a href="' . $link . '" target="' . $target . '" >
				<i class="' . $element['icon'] . '"></i>
				<span>' . $name . '</span>';
		if ($submenus != null && count($submenus) != 0) {
			$result .= '
				<i class="fa fa-angle-left pull-right"></i>
			</a>
			<ul class="treeview-menu">
				' . $temp . '
			</ul>';
		}
		else
			$result .= '
			</a>';
		$result .= '
		</li>';
	}

	return array($result,$active,$show);
}

/**
 * Traduce il template semplificato in componenti HTML.
 */
function translateTemplate() {
	global $id_module;
	global $dbo;

	$template = ob_get_clean();

	preg_match_all('/\{\[(.+?)\]\}/i', $template, $m);

	for($i = 0; $i < sizeof($m[0]); $i ++) {
		$template = str_replace($m[0][$i], build_html_element($m[0][$i]), $template);
	}

	if (isset($id_module)) $template = str_replace('$id_module$', $id_module, $template);

	if (isset($dbo)) $dbo->close();

	echo $template;
}

/**
 * Controlla se è stato effettuato il login.
 */
function isUserAutenticated() {
	return isset($_SESSION["idutente"]) && $_SESSION["idutente"] != "";
}

/**
 * Controlla se è stato effettuato il login come amministratore.
 */
function isAdminAutenticated() {
	return isUserAutenticated() && isset($_SESSION["is_admin"]) && $_SESSION["is_admin"] == 1;
}

/**
 * Esegue il logout se l'utente è autenticato.
 */
function logout() {
	if (isUserAutenticated()) {
		session_unset();
		session_destroy();
		setcookie("PHPSESSID", "", time() - 3600, "/"); // delete session cookie

		session_start();
		session_regenerate_id();
		$_SESSION['infos'] = array();
		array_push($_SESSION['infos'], _("Arrivederci!"));
	}
}

/**
 * restituisce un'insieme di array comprendenti le informazioni per la costruzione della query del modulo indicato.
 */
function getQuery($id_module) {
	global $dbo;

	$fields = array();
	$summable = array();
	$search_inside = array();
	$search = array();
	$slow = array();
	$order_by = array();
	$select = "*";

	$allineamento=array();
	$grassetto=array();
	$a_capo=array();
	
	$module = $dbo->fetchArray("SELECT * FROM zz_modules WHERE id=".prepare($id_module))[0];
	$module_query = ($module['options2'] != "") ? $module['options2'] : $module['options'];
	if(strpos($module_query, "|fields|") !== false){
		$datas = $dbo->fetchArray("SELECT * FROM `zz_viste` WHERE `id_module`=" . prepare($id_module) . " AND `id` IN (SELECT `id_vista` FROM `zz_gruppi_viste` WHERE `id_gruppo`=(SELECT `idgruppo` FROM `zz_utenti` WHERE `idutente`=" . prepare($_SESSION['idutente']) . ")) ORDER BY `order` ASC");
		if ($datas != null) {
			$select = "";
			foreach ($datas as $data) {
				$select .= $data["query"];
				if ($data["name"] != "") $select .= " AS '" . $data["name"] . "', ";
				if ($data["enabled"]) {
					array_push($fields, trim($data["name"]));
				
				
				if ($data["summable"]) array_push($summable, " FORMAT(SUM(REPLACE(REPLACE(`" . trim($data["name"] . "`, '.', ''), ',', '.')), " . get_var("Cifre decimali") . ") AS 'sum_" . (count($fields) - 1) . "'"));
				//if ($data["summable"]) array_push($summable, " FORMAT(SUM(REPLACE(REPLACE(REPLACE(`" . trim($data["name"] . "`, '.', '#'), ',', '.'), '#', ',')), " . get_var("Cifre decimali") . ") AS 'sum_" . (count($fields) - 1) . "'"));

					array_push($search_inside, trim($data["search_inside"]) != "" ? trim($data["search_inside"]) : trim($data["name"]));
					array_push($order_by, (trim($data["order_by"]) != "") ? trim($data["order_by"]) : trim($data["name"]));
					array_push($search, $data["search"]);
					array_push($slow, $data["slow"]);
					array_push($allineamento, $data["allineamento"]);
					array_push($grassetto, $data["grassetto"]);
					array_push($a_capo, $data["capo_caratteri"]);
				}
			}
			$select = substr($select, 0, strlen($select) - 2);
		}
	}
	else{
		$module_query = json_decode($module_query, true);
		$fields = explode(",", $module_query['main_query'][0]['fields']);
		foreach ($fields as $key => $value) {
			$fields[$key] = trim($value);
			array_push($search, 1);
			array_push($slow, 0);
		}
		$search_inside = $fields;
		$order_by = $fields;
	}

	$result = array();
	$result["select"] = $select;
	$result["fields"] = $fields;
	$result["search_inside"] = $search_inside;
	$result["order_by"] = $order_by;
	$result["search"] = $search;
	$result["slow"] = $slow;
	$result["summable"] = $summable;
	$result["allineamento"] = $allineamento;
	$result["grassetto"] = $grassetto;
	$result["a_capo"] = $a_capo;

	return $result;
}

/**
 * Sostituisce la prima occorenza di una determinata stringa.
 *
 * @param string $str_pattern
 * @param string $str_replacement
 * @param string $string
 * @return string
 */
function str_replace_once($str_pattern, $str_replacement, $string){
    if (strpos($string, $str_pattern) !== false){
        $occurrence = strpos($string, $str_pattern);
        return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
    }
    return $string;
}

function tr($string, $parameters = [], $operations = [])
{
    return $string;
	// return Translator::translate($string, $parameters, $operations);
}




/** ricerco niome utente */
	function username_name( $idutente , $campo ){		
		global $dbo;		
		$query = "SELECT ".$campo." FROM zz_utenti where idutente='".$idutente."'";
		$rs_parametri = $dbo->fetchArray($query);
		return $rs_parametri[0][$campo];						
	}
/** ricerco campo in mg_articoli utente */
	function get_var_articolo( $idarticolo , $campo ){		
		global $dbo;		
		$query = "SELECT ".$campo." FROM mg_articoli where id='".$idarticolo."'";
		$rs_parametri = $dbo->fetchArray($query);
		return $rs_parametri[0][$campo];						
	}


	function cerca_insoluti($idanagrafica){
		global $dbo;
		$year=date('Y');
		$month=date('m');
		$day=date('d');
		$data_test=$year."-".$month."-".$day." 00-00-00";
		
		$rw = $dbo->fetchArray( "SELECT * , co_scadenziario.id as id_scad  ,co_documenti.id as id_doc , co_tipidocumento.descrizione as des_doc
		FROM (co_scadenziario INNER JOIN (((co_documenti INNER JOIN an_anagrafiche ON co_documenti.idanagrafica=an_anagrafiche.idanagrafica) 
		INNER JOIN co_pagamenti ON co_documenti.idpagamento=co_pagamenti.id) 
		INNER JOIN co_tipidocumento ON co_documenti.idtipodocumento=co_tipidocumento.id) ON co_scadenziario.iddocumento=co_documenti.id) 
		INNER JOIN co_statidocumento ON co_documenti.idstatodocumento=co_statidocumento.id HAVING 1=1 AND (ABS(`pagato`) < ABS(`da_pagare`) ) 
		and co_documenti.idanagrafica='".$idanagrafica."' and scadenza < '".$data_test."' ORDER BY `scadenza` ASC");			
		
		return sizeof($rw);
	}
		
	
	
/**
* ricerco impostazioni tipo documento
*/
	function get_var_tipodoc( $idtipodocumento , $campo ){		
		global $dbo;		
		$query = "SELECT ".$campo." FROM co_tipidocumento where id='".$idtipodocumento."'";
		$rs_parametri = $dbo->fetchArray($query);
		return $rs_parametri[0][$campo];						
	}
	function get_var_tipodoc2( $iddocumento, $campo  ){		
		global $dbo;		
		$query = "SELECT ".$campo." FROM co_tipidocumento  LEFT JOIN co_documenti ON co_tipidocumento.id=co_documenti.idtipodocumento WHERE co_documenti.id='".$iddocumento."'";
		$rs_parametri = $dbo->fetchArray($query);
		return $rs_parametri[0][$campo];						
	}
	function get_var_documento( $iddocumento, $campo  ){		
		global $dbo;		
		$query = "SELECT ".$campo." FROM co_documenti where id='".$iddocumento."'";
		$rs_parametri = $dbo->fetchArray($query);
		return $rs_parametri[0][$campo];						
	}
	function query_secca( $str_query , $campo , $tabella ,$condizioni ){		
		global $dbo;		
		$query = "SELECT ".$campo." FROM ".$tabella."  ".$condizioni."";
		$rs_parametri = $dbo->fetchArray($query);
		return $rs_parametri[0][$campo];	
	
	}
	function query_secca2( $str_query , $campo , $tabella ,$condizioni,$campo_ritorno ){		
		global $dbo;		
		$query = "SELECT ".$campo." FROM ".$tabella."  ".$condizioni."";
		$rs_parametri = $dbo->fetchArray($query);
		return $rs_parametri[0][$campo_ritorno];	
	
	}
	function agg_doc_stato( $iddocumento, $idstatoold , $idstatonew  ){		
		global $dbo;		
		$query = "update co_documenti set idstatodocumento='".$idstatonew."' , idstatodocumento_prec='".$idstatoold."' where id='".$iddocumento."'";
		$dbo->query($query);					
	}
	function agg_doc_stato_rip( $iddocumento ){		
		global $dbo;		
		$query = "update co_documenti set idstatodocumento= idstatodocumento_prec   where id='".$iddocumento."'";
		$dbo->query($query);					
	}
	function cerca_modulo( $nome_modulo  ){		
		global $dbo;		
		$query = "SELECT id FROM zz_modules WHERE name='".$nome_modulo."'";
		$rs_testmodulo = $dbo->fetchArray($query);																			
		return sizeof($rs_testmodulo);					
	}

	
	function cerca_canone_qta( $idcontratto , $idarticolo ){		
		global $dbo;		
		$q = "SELECT sum(qta) as tot_qta  FROM `co_righe_documenti` WHERE idcontratto='".$idcontratto."' and riga_canone='1' and idarticolo='".$idarticolo."'";
		$rs_consumato= $dbo->fetchArray( $q );	
		return $rs_consumato[0]['tot_qta'];
	}
	function cerca_canone_prezzo( $idcontratto , $idarticolo ){		
		global $dbo;
		$rs_contratto = $dbo->fetchArray("SELECT id_tipocanone FROM co_contratti WHERE id=\"".$idcontratto."\"");		
		$id_tipocontratto=$rs_contratto[0]['id_tipocanone'];	
		$q = "SELECT subtotale  FROM `co_contratti_tipi_righe` WHERE idtipocontratto='".$id_tipocontratto."' and idarticolo='".$idarticolo."'";
		$rs_consumato= $dbo->fetchArray( $q );		
		return $rs_consumato[0]['subtotale'];
	}
	function cerca_canone_qta_scalare( $idcontratto , $idarticolo ){		
		global $dbo;
		$rs_contratto = $dbo->fetchArray("SELECT id_tipocanone FROM co_contratti WHERE id=\"".$idcontratto."\"");		
		$id_tipocontratto=$rs_contratto[0]['id_tipocanone'];	
		$q = "SELECT qta FROM `co_contratti_tipi_righe_qta` WHERE idtipocontratto='".$id_tipocontratto."' and idarticolo='".$idarticolo."'";
		$rs = $dbo->fetchArray( $q );
		return $rs[0]['qta'];
	}
	
	function cerca_contratti_attivi($idcontratto){
		global $dbo;		
		$rw = $dbo->fetchArray("SELECT * FROM co_contratti 	WHERE id_tipocanone='".$idcontratto."'  AND idstato ='3'");
		return sizeof($rw);
	}	
	function cerca_contratti_documenti($idcontratto){
		global $dbo;		
		$rw = $dbo->fetchArray("SELECT id FROM co_documenti WHERE id_contratto='".$idcontratto."'");
		return sizeof($rw);
	}	
	function cerca_contratti_a_zero($idcontratto){
		global $dbo;
		$rs_contratto = $dbo->fetchArray("SELECT id_tipocanone FROM co_contratti WHERE id=\"".$idcontratto."\"");		
		$id_tipocontratto=$rs_contratto[0]['id_tipocanone'];			
		$rs = $dbo->fetchArray("SELECT v_ins_righe_zero FROM co_contratti_tipi WHERE id='".$id_tipocontratto."'");
		return $rs[0]['v_ins_righe_zero'];
	}	
	function cerca_contratti($idanagrafica){
		global $dbo;
		$year=date('Y');
		$month=date('m');
		$day=date('d');
		$data_test=$year."-".$month."-".$day." 00-00-00";
		$rw = $dbo->fetchArray("SELECT co_contratti.id AS idcontratto, an_anagrafiche.idanagrafica, numero, nome FROM co_contratti INNER JOIN an_anagrafiche ON co_contratti.idanagrafica=an_anagrafiche.idanagrafica 
		WHERE an_anagrafiche.idanagrafica='".$idanagrafica."'  AND idstato NOT IN (SELECT `id` FROM co_staticontratti WHERE descrizione='Bozza' OR descrizione='Rifiutato' OR descrizione='Pagato') ORDER BY id");
		return sizeof($rw);
	}	
	
	
	function traduzione($lablel){
		global $dbo;
	//	$_SESSION['idlingua']= get_var("Lingua");
		$rs_traduci = $dbo->fetchArray("SELECT label_tr FROM lng_traduzioni WHERE idlingua='".$_SESSION['idlingua']."' and label=\"".$lablel."\"");	
		if ( sizeof($rs_traduci)	== '0' ){	
			$dbo->query("INSERT INTO lng_traduzioni( idlingua, label, label_tr ) VALUES( \"".$_SESSION['idlingua']."\", \"".$lablel."\",\"".$lablel."\" )");
			$tradotto=$lablel;			
		}
		else {
			$tradotto=$rs_traduci[0]['label_tr'];
		}
		return ($tradotto);
	}	
	

	
	function testa_query_sql($id_module) {
		global $dbo;
		
		$start = '1';
		$length = '3';
		$columns = filter("columns");
		$order = filter("order")[0];
		$_SESSION['id_module'] = $id_module;
		$total = getQuery($id_module);
		// Lettura parametri modulo
		$module = $dbo->fetchArray("SELECT * FROM zz_modules WHERE id=" . prepare($id_module))[0];
		$module_query = ($module['options2'] != "") ? $module['options2'] : $module['options'];
		if(strpos($module_query, "|fields|") === false){
			$module_query = json_decode($module_query, true);
			$module_query = $module_query['main_query'][0]['query'];
		}
		$module_query = str_replace("|period_start|", $_SESSION['period_start'], $module_query);
		$module_query = str_replace("|period_end|", $_SESSION['period_end'], $module_query);
		$module_query = str_replace("|fields|", $total["select"], $module_query);

		$results = array();
		$results["data"] = array();
		$results["recordsTotal"] = 0;
		$results["recordsFiltered"] = 0;
		$results["summable"] = array();

		/*
		 * Modifico la query principale per limitare i record nel caso l'utente abbia permessi da limitare
		 */
		$permessi = $dbo->fetchArray("SELECT clause FROM zz_gruppi_modules WHERE idgruppo=(SELECT id FROM zz_gruppi WHERE nome=" . prepare($_SESSION['gruppo']) . ") AND idmodule=" . prepare($id_module));
		if (sizeof($permessi) == 1) {
			// Includo il file init.php che contiene già i replace corretti di $additional_where[]
			if (file_exists($docroot . "/modules/" . $module['module_dir'] . "/".$modulo_custom."/init.php")) include ($docroot . "/modules/" . $module['module_dir'] . "/".$modulo_custom."/init.php");
			else if (file_exists($docroot . "/modules/" . $module['module_dir'] . "/init.php"))  include ($docroot . "/modules/" . $module['module_dir'] . "/init.php");
		}

		if ($module_query != '' && $module_query != 'menu' && $module_query != 'custom') {
			$query = str_replace_once("SELECT", "SELECT COUNT(*) as tot, ", $module_query);
			$cont = $dbo->fetchArray($query);
			if($cont!= null) $results["recordsTotal"] = $cont[0]['tot'];

			// Se ci sono dei parametri di ricerca per questo modulo li accodo alla query
			$search_filters = array();
			for($i = 0; isset($columns[$i]["search"]["value"]); $i ++) {
				if ($columns[$i]["search"]["value"] != "") {
					if(strpos($total["search_inside"][$i], "|search|") !== false){
						$sears = explode(",", $columns[$i]["search"]["value"]);
						foreach ($sears as $sear) {
							$sear = trim($sear);
							array_push($search_filters, str_replace("|search|", prepare("%".$sear."%"), $total["search_inside"][$i]));	
						}
					}
					else array_push($search_filters, "`".$total["search_inside"][$i] . "` LIKE ".prepare("%" . trim($columns[$i]["search"]["value"]) . "%"));
				}
			}


			if (sizeof($search_filters) > 0) {
				$module_query = str_replace("1=1", "1=1 AND (" . implode(" AND ", $search_filters) . ") ", $module_query);
			}

			// cerco se sono previsti dei filtri per i moduli esempio documenti
			$query_documenti="select  * from  zz_modules_documenti where idmodule='".$id_module."'";
			$rs_filtro = $dbo->fetchArray( $query_documenti );				
			if ( sizeof($rs_filtro)	== '1' ){			
				$module_query = str_replace( $rs_filtro[0]['cerca'], $rs_filtro[0]['sostituisci'] , $module_query );	
				if ( ($_SESSION['gruppo'] != 'Amministratori') && ($_SESSION['gruppo'] != 'Agenti') && ($_SESSION['gruppo'] != 'Tecnici') ){			
					$module_query = str_replace("1=1", "1=1 and co_documenti.idanagrafica='".$_SESSION['idanagrafica']."'", $module_query);
				}
			}
			

		
			$id_gruppo=query_secca("","id","zz_gruppi","where nome ='".$_SESSION['gruppo']."'");
			$query_filtri="select  * from  zz_gruppi_modules where idmodule='".$id_module."' and idgruppo='".$id_gruppo."' and enabled='1'";
			
			$rs_filtro = $dbo->fetchArray( $query_filtri );				
			if ( sizeof($rs_filtro)	== '1' ){			
				$filtro=$rs_filtro[0]['clause'];
				$filtro=str_replace("|idanagrafica|", $_SESSION['idanagrafica'] , $filtro);
				$filtro=str_replace("|idagente|", $_SESSION['idanagrafica'] , $filtro);
				$filtro=str_replace("|idtecnico|", $_SESSION['idanagrafica'] , $filtro);
				$module_query = str_replace("1=1", "1=1 " . $filtro, $module_query);
			}
			

			if (isset($order["dir"]) && isset($order["column"])) {
				$module_query = explode("ORDER", $module_query)[0] . "ORDER BY `" . $total["order_by"][$order["column"]] . "` " . $order["dir"];
			}

			if(count ($total["summable"])!=0){
				$query = str_replace_once("SELECT", "SELECT ".implode(",",$total["summable"])." FROM(SELECT ", $module_query).") AS `z`";
				$sums = $dbo->fetchArray($query)[0];
				if($sums != null){
					$r = array();
					foreach ($sums as $key => $sum) {
						if(strpos($key, "sum_") !== false) $r[str_replace("sum_", "", $key)] = $sum;
					}
					$results["summable"] = $r;
				}
			}

			// Paginazione
			$module_query .= " LIMIT " . $start . ", " . $length;
			
			
			$module_query = str_replace("and co_documenti.idanagrafica=|idanagrafica|", "" , $module_query);
			
			$query = str_replace_once("SELECT", "SELECT SQL_CALC_FOUND_ROWS", $module_query);
	

			return ($query );
		}
	

	
	
}