<?php
session_start();

######## VARS ########

$path = realpath(dirname(__FILE__) . '/../');
define('ROOT',$path);
define('BASE_GLOBAL_URL',getBaseurl());
define('BASE_URL',getBaseurl(true));

####### FUNCTIONS ############

include(ROOT."/includes/config.inc.php");

function my_autoloader($class) {
	require_once ROOT.'/includes/classes/' . strtolower($class) . '.php';
}

spl_autoload_register('my_autoloader');

function dbConnect(){
	
	if(is_object($GLOBALS['mysqli']))
		return;

	//connessione al database
	global $mysqli;
	$mysqli = new mysqli($GLOBALS['db_host'], $GLOBALS['db_user'], $GLOBALS['db_password'], $GLOBALS['db_name']);

	
	/* check connection */
	if (mysqli_connect_errno()) {
		header("Location: /?e=1");
		exit();
	}
}
function is_codfis($str){
	return preg_match('/^[a-z]{6}[0-9]{2}[a-z][0-9]{2}[a-z][0-9]{3}[a-z]$/iu',$str);
}
function is_cro($str){
	$len = strlen(trim($str));
	if(!preg_match('/^[a-z]{4}[\s]?[0-9]{4}$/iu',$str))
		return false;
	else
		return true;	
	
}
function is_clean_word($str){
	return preg_match("/^[\p{L}\d][\p{L}\s\d']*$/iu", $str);
}
function clean_str($str){
	return preg_replace('/[^A-Za-z0-9\-]/', '', $str);
}
function is_fname($str){
	return preg_match('/^[\w,\s-]+\.[a-z]{2,4}/', $str);	
}
function is_date($str){
	if(preg_match('/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/', $str)){
		list($dd,$mm,$yyyy) = explode("/",$str);
		if(checkdate($mm,$dd,$yyyy))
			return $yyyy.'-'.$mm.'-'.$dd;
	}
	return false;
}
function date_ita($str){
	if(strlen($str) <> 10) return false;
	list($yyyy,$mm,$dd) = explode("-",$str);
	return $dd.'/'.$mm.'/'.$yyyy;
}
function is_password($str){
	return preg_match("/^[\w-\.!@#$%]{6,20}$/iu", $str);	
}
function is_email($str){
	return preg_match("/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/iu", $str);
}
function entities($str){
	return htmlspecialchars($str,ENT_QUOTES);
}
function entities_xls($str){
	return htmlspecialchars($str,ENT_NOQUOTES);
}
function entities_pdf($str){
 return iconv('UTF-8', 'windows-1252', html_entity_decode($str));
}

function is_empty($str){
	$str = trim($str);
	return empty($str);
}
function printMsg($msg,$type,$die=true){
	echo '<div class="alert alert-'.$type.'">'.$msg.'</div>';	
	if($die)
		die();
}
function dbClean($str,$addQuotes=true,$limit=false,$setNullOnEmptyValue = true){
	if($setNullOnEmptyValue && trim($str) == ''){
		return 'NULL';
	}else{
		$str = trim($str);
		if($limit)
			$str = substr($str,0,$limit);
		
		$str = $GLOBALS['mysqli']->real_escape_string(htmlspecialchars_decode($str,ENT_QUOTES));

		if($addQuotes)
			return "'".$str."'";
		else
			return $str;
	}
}
function dbFloat($strNumber){
	$strNumber = trim($strNumber);
	if(empty($strNumber))
		return 'NULL';
	$n = str_replace(',','.',$strNumber);
	$n = floatval($n);
	return $n;
}
function importo($float){
	if($float != NULL)
	return number_format($float,2,',','');
}
function is_importo($str){
	return preg_match('/^[0-9]+([\.,][0-9]{1,2})?$/',$str);
}
function pagination($limit){
	$result = $GLOBALS['mysqli']->query("SELECT FOUND_ROWS() AS tot");
	$tot = $result->fetch_object()->tot;
	$pag_str = 'visualizzati da %1$d a %2$d di %3$d';
	
	if($tot > $limit){

		$max_pages = ceil($tot/$limit) - 1;
		$current_page = intval($_GET['p']);

		$qs_params = preg_replace('/(?|&)p=([0-9]+)/','', parse_url($_SERVER['REQUEST_URI'],PHP_URL_QUERY));
		$qs = '?'. $qs_params . (!empty($qs_params) ? '&' : '') . 'p=';
		
		if($current_page > 0)
			$btns = '<li class="pre"><a href="'. $qs.($current_page-1) . '"><span class="glyphicon glyphicon-chevron-left"></span> indietro</a></li> ';
		
		if($current_page < $max_pages)
			$btns .= ' <li class="nex"><a href="'. $qs.($current_page+1) . '">avanti <span class="glyphicon glyphicon-chevron-right"></span></a></li>';
			
		$n_start = $current_page * $limit;
		$n_end = $n_start + $limit;
		if($n_end > $tot)
			$n_end = $tot;

		$str = '<div>'.sprintf($pag_str,($n_start+1),$n_end,$tot).'</div>';
		
		return '<ul class="pager"><li class="pagination-descr">'.$str.'</li>'.$btns.'</ul>';
	}

}

function checkLogin(){
	$permitted_groups = func_get_args();
	if($_SESSION['user']['logged'] !== true || count($permitted_groups) > 0 && !in_array($_SESSION['user']['grp'],$permitted_groups)){
		$url = getBaseurl() . ($_GET['e'] ? '/ente/'.$_GET['e'] : '') .'/?session_expired';
		header("Location: ".$url);
		Js('if(!window.parent) window.location="'.$url.'"; else window.parent.location="'.$url.'"');
		die();
	}
}
function Js($js_code){
	echo '<script language="javascript">'.$js_code.'</script>';
}

function getBaseurl($userRelative=false){
	$site_base = $userRelative ? '/ente/'. ($_SESSION['user']['logged'] ? $_SESSION['user']['ente_url'] : $_GET['e']) : '';
	return sprintf(
		"%s://%s%s",
		isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
		$_SERVER['HTTP_HOST'],
		$site_base
	);
}

function print_optMenu($k){
	if(!($array = $GLOBALS['opts_menu'][$k]))
		return;
	
	echo '
	<div class="btn-group pull-right list-opts-menu">
		<button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"><span class="hidden-xs">Opzioni </span><span class="glyphicon glyphicon-cog"></span></button>
		<ul class="dropdown-menu" role="menu">';
		
	foreach($array as $v){
		$icon = $v['ico'] ? ' <span class="glyphicon glyphicon-'.$v['ico'].'"></span>' : '';
		echo '<li><a href="'.$v['url'].'" '.$v['opts'].'>'.$icon.$v['label'].'</a></li>';
	}
		
	echo '
		</ul>
	</div>
	';
}

function print_province_opts($default_value=false){
	$result = $GLOBALS['mysqli']->query("SELECT * FROM province ORDER BY provincia");
	while($row=$result->fetch_assoc()){
		$sel = $row['provincia_id'] == $default_value ? ' selected' : '';
		echo '<option value="'.$row['provincia_id'].'"'. $sel .'>'.utf8_encode($row['provincia']).'</option>';
	}
}
function print_comuni_opts($prov_id=false, $default_value=false){
	if(!$prov_id) return;
	$result = $GLOBALS['mysqli']->query("SELECT * FROM comuni WHERE provincia_id = ".intval($prov_id)." ORDER BY comune");
	while($row=$result->fetch_assoc()){
		$sel = $row['comune_id'] == $default_value ? ' selected' : '';
		echo '<option value="'.$row['comune_id'].'"'. $sel .'>'.utf8_encode($row['comune']).'</option>';
	}
}

function get_ente_servizi($all_services=false){
	$servizi = array();
	
	if(!$all_services)
		$w=" WHERE servizi_enti.ente_id = ".$_SESSION['user']['ente_id'];
		
	$result = $GLOBALS['mysqli']->query("
	SELECT * FROM servizi_enti 
	LEFT JOIN servizi ON servizi_enti.serv_id = servizi.serv_id 
	".$w." ORDER BY servizi.serv_ord");
	while($row=$result->fetch_assoc())
		$servizi[$row['serv_id']] = $row;

	return $servizi;
}

function get_serv_name($serv_cod){
	$result = $GLOBALS['mysqli']->query("SELECT serv_name FROM servizi WHERE serv_cod = ".dbClean($serv_cod)." LIMIT 1");
	if($result)
		return $result->fetch_object()->serv_name;
}

function get_serv_id($serv_cod){
	$result = $GLOBALS['mysqli']->query("SELECT serv_id FROM servizi WHERE serv_cod = ".dbClean($serv_cod));
	return $result->fetch_object()->serv_id;
}
function checkEnteService($serv_cod){
	if($serv_cod && !$_SESSION['user']['services'][$serv_cod])
		die();
}

function rearrange( $arr ){
    if(!is_array($arr))
		return false;
	foreach( $arr as $key => $all ){
        foreach( $all as $i => $val ){
            $new[str_replace("'", "", $i)][$key] = $val;   
        }   
    }
    return $new;
}

function getExt($fname){
	return strtolower(pathinfo($fname, PATHINFO_EXTENSION));	
}
function printParentJsError($str,$type='danger',$dest_id='result_anagr_serv'){
	Js('parent.document.getElementById("'.$dest_id.'").innerHTML = "<div class=\'alert alert-'.$type.'\'>'.$str.'<div>"; history.back();');
	die();
}
function get_ente($ente_url){
	$result = $GLOBALS['mysqli']->query("SELECT * FROM enti WHERE ente_url = ".dbClean($ente_url));
	if($result->num_rows == 1)
		return $result->fetch_assoc();
	
	return false;
}
function generatePassword($length=6, $strength=0) {
	$vowels = 'aeiu';
	$consonants = 'bcdfghlmnpqrstvz23456789';
 
	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $password;
}

function is_cellulare($n){
	return preg_match('/^\d{10}$/',$n);
}
function welltxt($str){
	return ucwords(mb_strtolower($str,'UTF-8'));
}
function check_my_anagr($id){
	
	if($_SESSION['user']['grp'] == 'usr'){
		$w = " AND user_id = ".$_SESSION['user']['id']." AND anno = ".$_SESSION['user']['ente_anno'];
	}
		
	$result = $GLOBALS['mysqli']->query("SELECT COUNT(*) AS tot FROM anagrafiche WHERE anagr_id = ".dbClean($id)." AND ente_id = ".$_SESSION['user']['ente_id'].$w);
	if($result->fetch_object()->tot <> 1)
		die();
}
function check_my_user($id){
	$result = $GLOBALS['mysqli']->query("SELECT COUNT(*) AS tot FROM users WHERE user_id = ".dbClean($id)." AND ente_id = ".$_SESSION['user']['ente_id']);
	if($result->fetch_object()->tot <> 1)
		die();
}
function mese_ita($n,$short=false){
	$arr = array(1=>'Gennaio',2=>'Febbraio',3=>'Marzo',4=>'Aprile',5=>'Maggio',6=>'Giugno',7=>'Luglio',8=>'Agosto',9=>'Settembre',10=>'Ottobre',11=>'Novembre',12=>'Dicembre');
	$m = $arr[intval($n)];
	return $short ? substr($m,0,3) : $m;
}
function giorno_ita($date){
	$arr = array(1=>'Luned&igrave;',2=>'Marted&igrave;',3=>'Mercoled&igrave;',4=>'Gioved&igrave;',5=>'Venerd&igrave;',6=>'Sabato',7=>'Domenica');
	return $arr[date('N',strtotime($date))];
}
function usrlog($log_msg,$anagr_id=false,$mail_alert=false){
	
	//non mando email se l'azione la compie un addetto
	if($_SESSION['user']['grp'] <> 'usr')
		$mail_alert = false;
		
	dbConnect();
	
	//anagrafica utente corrente
	$user_name = $_SESSION['user']['cognome'].' '.$_SESSION['user']['nome'];
	//anagrafica destinatario
	if($anagr_id){
		$anagr_id = intval($anagr_id);
		$result=$GLOBALS['mysqli']->query("SELECT anagr_id, CONCAT_WS(' ',anagr_nome, anagr_cognome) AS anagr FROM anagrafiche WHERE anagr_id = ".$anagr_id);
		$anagr_name = dbClean($result->fetch_object()->anagr,false);
		$log_msg = sprintf($log_msg,$anagr_name);
	}
		
	date_default_timezone_set('Europe/Rome');
	$date = date("Y-m-d H:i:s");
	$GLOBALS['mysqli']->query($q="INSERT INTO logs VALUES (NULL, ".$_SESSION['user']['ente_id'].", ".$_SESSION['user']['id'].",".dbClean($user_name).",".dbClean($anagr_id).", ".dbClean($log_msg).",".dbClean($_SERVER['REMOTE_ADDR']).", '".$date."')");

	if($mail_alert){
		
		include(ROOT."/includes/classes/phpmailer/class.phpmailer.php");
		$result=$GLOBALS['mysqli']->query("SELECT ente_mailalert FROM enti WHERE ente_id = ".$_SESSION['user']['ente_id']);
		$mail_ente = $result->fetch_object()->ente_mailalert;
		if($mail_ente <> NULL){
			
			$body = '<div style="border:2px solid #ffa915; border-radius:5px; background:#f8f8f8; padding:10px; font-family:Arial, sans-serif; font-size:13px; color:#666;">
<strong>'.$date.'</strong><br><br>'.$log_msg.'</div><br><br><a style="color:#00f;font-family:Arial, sans-serif; font-size:13px;" href="http://www.servizicittadino.it/ente/'.$_SESSION['user']['ente_url'].'/" target="_blank" title="Servizi Cittadino">http://www.servizicittadino.it/ente/'.$_SESSION['user']['ente_url'].'/</a>';
			
			$mail = new PHPMailer();
			//$mail->SMTPDebug  = 0;
			$mail->SetFrom('avvisi@servizicittadino.it', 'Servizi Cittadino');
			$mail->AddReplyTo('avvisi@servizicittadino.it','noreply');
			$mail->AddAddress($mail_ente);
			$mail->Subject = "Nuova azione - Servizi Cittadino";
			$mail->MsgHTML($body);
			$mail->Send();
		}
	}
}

function urlFormat($str){
	$newstr = html_entity_decode($str,ENT_QUOTES);
	$newstr = str_replace(array("à","è","é","ì","ò","ù"," ","'",'"'),array("a","e","e","i","o","u","_","_","_"),$newstr);
	$newstr = strtolower($newstr);
	$newstr = ereg_replace("[^A-Za-z0-9_-]", "", $newstr);
	$newstr =  preg_replace('{([_-])\1+}','$1',$newstr);
	return $newstr;
}


?>