security.php 12.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
<?php
/**********************************************************************************
 Sistema e-SIC Livre: sistema de acesso a informação baseado na lei de acesso.
 
 Copyright (C) 2014 Prefeitura Municipal do Natal
 
 Este programa é software livre; você pode redistribuí-lo e/ou
 modificá-lo sob os termos da Licença GPL2.
***********************************************************************************/

require_once ("database.php");
require_once ("funcoes.php");


function sendMail($to, $subject,$body,$from="",$fromname="")
{
                //se nao for informado o remetente, recupera das configurações do sistema
		if(empty($from))
                {
                    $sql = "select nomeremetenteemail, emailremetente from lda_configuracao";
                    $rs = execQuery($sql);

                    $row = mysql_fetch_array($rs);
                    
                    $from = $row['emailremetente'];
                    $fromname = $row['nomeremetenteemail'];
                }
		$html = "<html>
					<body>
					$body
					</body>
				</html>";
				
	    
		//$headers = "Content-Type: text/plain\r\n"; 				
		$headers = "Content-type: text/html; charset=ISO-8859-1\r\n";
		$headers .= "Reply-To: $fromname <$from>\r\n";     
		$headers .= "Return-Path: $fromname <$from>\r\n";     
		$headers .= "From: $fromname <$from>\r\n";     
		$headers .= "Organization: Prefeitura do Natal\r\n";     
		

		if (mail($to, $subject, $html, $headers))
			return true;
		else 
			return false;

}

//Funcao email para Linux - PHP MAILER 


function sendMail($to, $subject, $body, $from="", $fromname=""){
    require_once("../class/PHPMailerAutoload.php");
    $mail = new PHPMailer();
     $mail->isSMTP();                    // Define que a mensagem será SMTP
    $mail->Host = "0.0.0.0";          //hostname ou IP do Servidor
    //$mail->SMTPAuth = true;      //Caso seu email precise de autenticação, no nosso caso não.
    //$mail->Username = "seuemail@dominio.com";
    //$mail->Passowrd = "sua senha";
    if(empty($from)){
        $sql = "SELECT nomeremetenteemail, emailremetente FROM lda_configuracao"; 
        $rs = execQuery($sql);
        $row = mysql_fetch_array($rs);
         $mail->From = $row['emailremetente'];
         $mail->FromName = $row['nomeremetenteemail'];
    }else{
        $mail->From = $from;
         $mail->FromName = $fromname;
    }
     $mail->addAddress($to);
    $mail->isHTML(true);                      //Define que o email será HTML
    $mail->CharSet = "iso-8859-1";       //Charset da mensagem (opcional)
    $mail->Subject = $subject;
    $html = "<html>
                    <body>
                        $body
                    </body>
                </html>";
     $mail->Body = $html;
    $mail->AltBody = $body;               //Texto Plano (opcional)
    $envia = $mail->send();                //Envia o email
    $mail->clearAllRecipients();          //Limpa os destinatarios
     if($envia){                                    //Retorno do email
        return TRUE;
    }else{
        return FALSE;
    }
}



function sendMailAnexo($to, $subject,$body,$arquivos=array(),$from="",$fromname="",$cc="")
{
                //se nao for informado o remetente, recupera das configurações do sistema
		if(empty($from))
                {
                    $sql = "select nomeremetenteemail, emailremetente from lda_configuracao";
                    $rs = execQuery($sql);

                    $row = mysql_fetch_array($rs);
                    
                    $from = $row['emailremetente'];
                    $fromname = $row['nomeremetenteemail'];
                }
		$html = "<html>
					<body>
					$body
					</body>
				</html>";


		$boundary = strtotime('NOW');

		$headers .= "Content-Type: multipart/mixed; boundary=\"" . $boundary . "\"".PHP_EOL;		
		$headers .= "Reply-To: $fromname <$from>".PHP_EOL;     
		$headers .= "Return-Path: $fromname <$from>".PHP_EOL;     
		$headers .= "From: $fromname <$from>".PHP_EOL;  
		$headers .= "Cc: $cc".PHP_EOL;
		$headers .= "MIME-Version: 1.0".PHP_EOL;		
		$headers .= "Organization: Prefeitura do Natal".PHP_EOL;     
		
		 
		$msg = "--" . $boundary . PHP_EOL;
		$msg .= "Content-Type: text/html; charset=\"ISO-8859-1\"".PHP_EOL;
		$msg .= "Content-Transfer-Encoding: 8bit".PHP_EOL.PHP_EOL; 
		$msg .= stripslashes($html).PHP_EOL;
		 

		for($i=1; $i <= count($arquivos); $i++)
		{
			$finfo = finfo_open(FILEINFO_MIME_TYPE);
			
			$tipoarquivo = finfo_file($finfo, $arquivos['arquivo'][$i]); 		

			$msg .= "--" . $boundary . PHP_EOL;
			$msg .= "Content-Transfer-Encoding: base64".PHP_EOL;
			$msg .= "Content-Type: \"".$tipoarquivo."\"; name=\"".$arquivos['nome'][$i]."\"".PHP_EOL;
			$msg .= "Content-Disposition: attachment; filename=\"".$arquivos['nome'][$i]."\"".PHP_EOL.PHP_EOL;
		
			ob_start();
			   readfile($arquivos['arquivo'][$i]);
			   $enc = ob_get_contents();
			ob_end_clean();

			$msg_temp = base64_encode($enc). PHP_EOL;
			$tmp[1] = strlen($msg_temp);
			$tmp[2] = ceil($tmp[1]/76);

			for ($b = 0; $b <= $tmp[2]; $b++) {
				$tmp[3] = $b * 76;
				$msg .= substr($msg_temp, $tmp[3], 76) . PHP_EOL;
			}

			unset($msg_temp, $tmp, $enc);
			
		}
		return mail($to, $subject, $msg, $headers);

		
}

//registra na tabela de erros de login, a tentativa sem sucesso de acesso ao sistema
function setTentativaLogin($usuario)
{
	 $ipaddr = $_SERVER["REMOTE_ADDR"];
	 $sistema = SISTEMA_CODIGO;
	 $query = "insert into sis_errologin (sistema, usuario,ip) values('$sistema','$usuario','$ipaddr')";
	 execQuery($query) or die("Ocorreu um erro inesperado ao logar erro de entrada");
}

//exclui da tabela de erros de login, as tentativa sem sucesso de acesso ao sistema
function delTentativaLogin($usuario)
{
	 $sistema = SISTEMA_CODIGO;
	 $query = "delete from sis_errologin  where usuario='$usuario' and sistema = '$sistema'";
	 execQuery($query) or die("Ocorreu um erro inesperado ao excluir tentativas de acesso");
}

/*---------------------------------------------------------------------------
* verifica da existencia de uma tentativa de acesso, sem sucesso, ao sistema
* e retorna se deve ser usado o recaptcha para proxima tentativa de acesso
*---------------------------------------------------------------------------*/
function usaRecaptcha($usuario)
{
	if (empty($usuario)) return false;
	
	$sistema = SISTEMA_CODIGO;
	
	$query = "select * from sis_errologin
                  where usuario='$usuario' and sistema = '$sistema'";

	$rs = execQuery($query);

	//se houver tentativas registradas retorna true para exibir o controle recaptcha
	return (mysql_num_rows($rs) >0) ;
	
}

//atualizar a unidade do usuario logado com a unidade selecionada no meu topo
function atualizaUnidadeUsuario($idsecretaria)
{

        $var = $_SESSION[SISTEMA_CODIGO];    
	
        $sql="select nomesecretaria, siglasecretaria, idsecretaria
              from vw_secretariausuario und
              where md5(idsecretaria) = '$idsecretaria'
                    and idusuario = ".getSession('uid');
    
        $rs = execQuery($sql);
        
        if(mysql_num_rows($rs)>0)
        {
            $row = mysql_fetch_array($rs);

            $var["idsecretaria"] = $row['idsecretaria'];
            $var["siglasecretaria"] = $row['siglasecretaria'];
            $var["nomesecretaria"] = $row['nomesecretaria'];

            $_SESSION[SISTEMA_CODIGO] = $var;
            
            $rs = null;
            $row = null;
            
            return true;
        }
        else
        {
            return false;
        }

}

function autentica($login, $pwd, $tipo)
{
	if (empty($login) or empty($pwd))
	{
		if(!empty($login))
			setTentativaLogin($login);
			
		return false;
	}
	
	
        $query = "select u.idusuario as id, u.nome, u.idsecretaria, s.sigla, s.nome as secretaria
                            from sis_usuario u, sis_secretaria s
                            where u.idsecretaria = s.idsecretaria 
                                  and u.login='$login' and u.chave = '".md5($pwd)."'
                                  and u.status = 'A'";

        $rs = execQuery($query);

        if (mysql_num_rows($rs) !=0) 
        {
                $row = mysql_fetch_array($rs);
        }
        else
        {
                //inclui tentativa de acesso ao sistema, para usar o recaptcha no proximo login
                setTentativaLogin($login);
                return false;
        }

	//exclui tentativas de acesso ao sistema do usuario (para evitar o recaptcha no proximo login)
	delTentativaLogin($login);
	
	$apelido = explode(" ",$row['nome']);
	
	$var = array();
	
	$var["uid"] = $row['id'];
	$var["nomeusuario"] = $row['nome'];		
	$var["apelidousuario"] = $apelido[0];
        $var["idsecretaria"] = $row['idsecretaria'];
        $var["siglasecretaria"] = $row['sigla'];
        $var["nomesecretaria"] = $row['secretaria'];
	
	$_SESSION[SISTEMA_CODIGO] = $var;

        return true;
	
}



/*pega o diretorio padrao para gravação de arquivos
$sis = sistema para busca do diretorio na tabela de parametros
*/
function getDiretorio($sis = "lda"){
	
	$query = "select diretorioarquivos from lda_configuracao";

	$rs = execQuery($query);

	if (mysql_num_rows($rs) !=0) 
	{
		$row = mysql_fetch_array($rs);
		$retorno = $row['diretorioarquivos'];
	}
	
	return $retorno;
}

/*paga o URL padrao para exibição de arquivos
$sis = sistema para busca do diretorio na tabela de parametros
*/
function getURL($sis = "lda"){
	
	$query = "select urlarquivos from lda_configuracao";

	$rs = execQuery($query);

	if (mysql_num_rows($rs) !=0) 
	{
		$row = mysql_fetch_array($rs);
		$retorno = $row['urlarquivos'];
	}
	
	return $retorno;
}


function prepData($var) {
  $conn = db_open();
  
  if (get_magic_quotes_gpc()) {
    $var = stripslashes($var);
  }
  
  $retorno = mysql_real_escape_string($var);
  
  db_close($conn);
  
  return $retorno;
}

function logger($msg) {
 $usuario = getSession("uid");
 $usuario = empty($usuario)?"SYSTEM":$usuario;

 // Ugly fix pra nao permitir salvar senha em banco.
 unset($_POST["senha"]);

 $mensagem = $msg;
 $datahora = "now()";
 $dados_post = prepData(serialize($_POST));
 $dados_get = prepData(serialize($_GET));
 $dados_session = prepData(serialize($_SESSION));
 $ipaddr = $_SERVER["REMOTE_ADDR"];

 $query = "insert into sis_log (usuario,mensagem,datahora,dados_get,dados_post,ipaddr) values('$usuario','$mensagem',$datahora,'$dados_get','$dados_post','$ipaddr')";
 execQuery($query) or die("Erro logando");
}


function getErro($msg){
	//Exibe mensagem de erro passado pelas telas de manutenção
	if (trim($msg) != "")
		echo "<script>alert('$msg'); </script>";
}

function getConfirmacao($msg,$funcaoConfirmacao){
	//Exibe mensagem de confirmação passado pelas telas de manutenção
	//funcaoConfirmacao -> função javascript com o alert de confirmação e procedimentos a serem seguidos.
	if (trim($msg) != "")
		echo "<script> $funcaoConfirmacao('$msg'); </script>";		
}

function checkPerm($operacao,$retornapag=true) {
	$uid = getSession("uid");
	$query = "select permissao.idacao from sis_acao acao,sis_permissao permissao, sis_grupo g, sis_grupousuario gu
			  where acao.idacao=permissao.idacao 
					and g.idgrupo = permissao.idgrupo
					and gu.idgrupo = g.idgrupo
				    and acao.status = 'A'
					and gu.idusuario = '$uid' 
					and acao.operacao='$operacao'";
					
	$rs = execQuery($query);

	if (mysql_num_rows($rs) !=0) {
		return true;
	} else {
		//se for passado o parametro false, nao retorna pagina de acesso negado, e sim o valor false.
		if ($retornapag){
			include "topo.php";
			echo "<h1>Acesso Negado</h1><br><center>
			<li>Voce nao tem permissao para acessar o modulo $operacao</li>
			<div align='center'><a href=\"#\" onclick=\"history.go(-1)\" >Voltar</a></p></center>";
			include "rodape.php";
			exit;
		}else{
			return false;
		}
	}
}
function Redirect($url) {
	Header("Location:$url");
}

function isauth($tipo="consumidor") {
    session_start();
	if(!isset($_SESSION[SISTEMA_CODIGO])) {
		Redirect(SITELNK."index/?t=".$tipo);
		exit;
	}
}

session_start();

?>