<?php
include("../sol/sessao.php");
//Verifica permissao
$nivelnecessario = 0;
//Conecta ao banco e abre query
$dados = new dados();
$dados->get_conexao();
if (!empty($_POST['outra_cidade']))
{
$sql = "INSERT INTO
cidades (id_uf, nome)
VALUES
(".$_POST['uf'].",'".TrataStr($_POST['outra_cidade'])."')";
mysql_query($sql);
$sql = "SELECT MAX(id_cidade) AS ult_cid FROM cidades";
$rs = mysql_query($sql);
$reg = mysql_fetch_array($rs);
$_POST['cidade'] = $reg['ult_cid'];
}
if ($_GET['acao'] == 'editar')
{
$sql = "UPDATE
usuarios
SET
id_instituicao = ".$_POST['unidade'].",
id_cidade = ".$_POST['cidade'].",
senha = '".$_POST['senha']."',
nome_completo = '".TrataStr($_POST['nome_completo'])."',
email = '".TrataStr($_POST['email'])."',
id_departamento = ".$_POST['departamento'].",
nivel = ".$_POST['nivel'].",
ativo = ".$_POST['ativo']."
WHERE
id_usuario = ".$_GET["id"];
mysql_query($sql);
header('Location:/sol/lista_usuarios.php');
}
$userjacadastrado = false;
if ($_GET['acao'] == 'inserir')
{
$sql = "SELECT * FROM usuarios WHERE username = '".TrataStr($_POST['username'])."'";
$rs = mysql_query($sql);
if (mysql_num_rows($rs) > 0)
{
$userjacadastrado = true;
$reg["nome_completo"] = TrataStr($_POST["nome_completo"]);
$reg["email"] = TrataStr($_POST['email']);
$reg["id_departamento"] = $_POST['departamento'];
$reg["id_instituicao"] = $_POST['unidade'];
}
else
{
$sql = "INSERT INTO usuarios
(id_instituicao, id_cidade, username, senha, nome_completo, email, id_departamento, nivel, ativo)
VALUES
(".$_POST['unidade'].", ".$_POST['cidade'].", '".TrataStr($_POST['username'])."',
'".$_POST['senha']."', '".TrataStr($_POST['nome_completo'])."', '".TrataStr($_POST['email'])."',
".$_POST['departamento'].", ".$_POST['nivel'].", ".$_POST['ativo'].")";
mysql_query($sql);
header('Location:/sol/lista_usuarios.php');
}
}
$sql = "SELECT
u.*, i.nome, c.id_uf, d.departamento
FROM
usuarios AS u
INNER JOIN
instituicao AS i ON (i.id_inst = u.id_instituicao)
INNER JOIN
cidades AS c ON (c.id_cidade = u.id_cidade)
INNER JOIN
departamentos AS d ON (d.id = u.id_departamento)
WHERE
u.id_usuario = ".$_GET["id"];
if (!empty($_GET["id"]))
{
$rs = mysql_query($sql);
$reg = mysql_fetch_array($rs);
}
$idx = str_replace ('#', '', $_GET["id"]);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>SolBT - <?=$sitenome?></title>
<link rel="StyleSheet" type="text/css" href="../sol/includes/estilos.css" id="estilo" />
<script language='JavaScript' src='../sol/includes/FuncoesTela.js' type="text/javascript"></script>
<script language='JavaScript' type="text/javascript">
var jaLoaded = false;
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
function Salvar()
{
<?php
if (empty($idx))
{
?>
ValidarDigitacaoUsuario();
if (document.forms[0].username.value.length < 7)
{
alert('Informe um username com pelo menos 7 caracteres.');
document.forms[0].username.focus();
return;
}
<?php
}
?>
document.forms[0].nome_completo.value = document.forms[0].nome_completo.value.trim();
if (document.forms[0].nome_completo.value.length == 0)
{
alert('Informe o nome completo.');
document.forms[0].nome_completo.focus();
return;
}
if (document.forms[0].senha.value.length < 6)
{
alert('Informe uma senha entre 6 e 8 caracteres.');
document.forms[0].senha.focus();
return;
}
if (document.forms[0].senha.value != document.forms[0].confirmar.value)
{
alert('A senha e a confirmação não batem.');
document.forms[0].confirmar.focus();
return;
}
if (document.forms[0].unidade.value == 0)
{
alert('Informe a unidade a qual o usuário pertence.');
document.forms[0].unidade.focus();
return;
}
document.forms[0].outra_cidade.value = document.forms[0].outra_cidade.value.trim();
if ((document.forms[0].cidade.value == 0) && (document.forms[0].outra_cidade.value.length == 0))
{
alert('Selecione uma cidade na lista ou informe uma nova.');
document.forms[0].outra_cidade.focus();
return;
}
//Validar o email
if (document.forms[0].email.value.length == 0)
{
alert('Informe o e-mail do usuário.');
document.forms[0].email.focus();
return;
}
else
{
var er = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
b = document.getElementById('email').value;
if(!er.test(b))
{
window.alert('O e-mail informado não é válido.');
document.getElementById('email').value = '';
document.getElementById('email').focus();
return;
}
}
if (document.forms[0].departamento.value == 0)
{
alert('Informe o departamento ao qual o usuário pertence.');
document.forms[0].departamento.focus();
return;
}
if (document.forms[0].nivel.value == -1)
{
alert('Informe o nÃvel de acesso.');
document.forms[0].nivel.focus();
return;
}
if (document.forms[0].inativo.checked)
{
document.forms[0].inativo.value = 0;
document.forms[0].ativo.value = false;
if ('<?=$idx?>' == '<?=$_SESSION["usuario"]?>')
{
alert('Você não pode desativar seu próprio usuário.');
document.forms[0].inativo.focus();
return;
}
}
else
{
document.forms[0].inativo.value = 1;
document.forms[0].ativo.value = true;
}
document.forms[0].submit();
}
function ValidarDigitacaoUsuario()
{
document.forms[0].username.value = document.forms[0].username.value.trim();
document.forms[0].username.value = document.forms[0].username.value.toUpperCase();
}
function Dados(valor)
{
ajax = InstanciaAJAX();
//Se tiver suporte a AJAX
if(ajax)
{
//Deixa apenas o elemento 1 no option, os outros são excluÃdos
document.forms[0].cidade.options.length = 1;
idOpcao = document.getElementById('opcoes');
if (valor == -1)
{
//Desabilita a lista de cidades
document.forms[0].cidade.disabled = 'disabled';
idOpcao.innerHTML = 'Selecione um estado na lista.';
}
else
{
//Define a chamada via POST ao XML criado pelo PHP com as cidades
ajax.open('POST', 'cidades.xml.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.onreadystatechange = function()
{
//Enquanto estiver processando emite a mensagem de aguarde
if(ajax.readyState == 1)
{
idOpcao.innerHTML = 'Aguarde...';
}
//Após ser processado chama função processXML que vai varrer os dados
if(ajax.readyState == 4 )
{
if(ajax.responseXML)
{
processXML(ajax.responseXML);
}
else
{
//Caso não consiga ler o arquivo XML emite a mensagem e desabilita a lista de cidades
idOpcao.innerHTML = 'Cidades não encontradas.';
document.forms[0].cidade.disabled = 'disabled';
}
}
}
}
//Passa o código do estado escolhido como parâmetro pro POST e envia
var params = 'id_uf=' + valor;
ajax.send(params);
}
function processXML(obj)
{
//Pega a TAG cidade
var dataArray = obj.getElementsByTagName('cidade');
//Verifica o total de elementos contidos na TAG cidade
if(dataArray.length > 0)
{
//Percorre o arquivo XML para extrair os dados
for(var i = 0 ; i < dataArray.length ; i++)
{
var item = dataArray[i];
//Contéudo dos campos no arquivo XML
var valorcid = item.getElementsByTagName('id_cidade')[0].firstChild.nodeValue;
var nome = item.getElementsByTagName('nome')[0].firstChild.nodeValue;
idOpcao.innerHTML = 'Selecione a cidade.';
//Cria um novo option dinamicamente
var novo = document.createElement('option');
//Atribui um ID a esse elemento
novo.setAttribute('id', 'opcoes');
//Atribui valor e texto
novo.value = valorcid;
novo.text = nome;
//Adiciona o novo elemento
document.forms[0].cidade.options.add(novo);
}
//Habilita a lista de cidades
document.forms[0].cidade.disabled = '';
<?php
if (!empty($reg["id_uf"]))
{
echo 'var idUF = '.$reg["id_uf"].';';
}
else
{
echo 'var idUF = 0;';
}
?>
if (idUF > 0)
{
if (!jaLoaded)
{
if (document.getElementById('uf').value == idUF)
{
<?php
if (!empty($reg["id_cidade"]))
{
echo 'var idCity = '.$reg["id_cidade"].';';
}
else
{
echo 'var idCity = 0;';
}
?>
document.getElementById('cidade').value = idCity;
}
}
}
jaLoaded = true;
}
else
{
//Caso o XML volte vazio, exibe a mensagem abaixo e desabilita a lista de cidades
idOpcao.innerHTML = 'Cidades não encontradas.';
document.forms[0].cidade.disabled = 'disabled';
}
}
}
function AtivaPermissao()
{
<?php
if ($_SESSION["univel"] > $nivelnecessario)
{
?>
document.getElementById('unidiv').style.display = 'none';
document.getElementById('depdiv').style.display = 'none';
<?php
}
?>
}
</script>
</head>
<body onload="document.getElementById('<? if (!empty($idx)) echo "nome_completo"; else echo "username"; ?>').focus(); AtivaPermissao();">
<?php
include("../sol/includes/menus.php");
?>
<table width="100%">
<?php
include("../sol/includes/top.php");
?>
<!-- CONTEUDO DA PAGINA -->
<tr>
<td id="Conteudo">
<br />
<span class="Titulo">Cadastro de usuário</span><br /> <br />
<form action="editar_user.php?acao=<? if (!empty($idx)) echo 'editar&id='.$idx; else echo 'inserir'; ?>" method="post">
<?php
if (!empty($idx))
{
echo 'Editando usuário '.str_pad($idx, 7, "0", STR_PAD_LEFT)." - ".utf8_encode($reg["username"])."<br /> <br />";
}
else
{
?>
Username <font size="1">(evite usar caracteres especiais)</font>:
<input type="text" name="username" id="username" value="" maxlength="20" onblur="ValidarDigitacaoUsuario();" />
<? if ($userjacadastrado) echo "<em style='color:#666666;'> * Informe outro username, ".$_POST['username']." já está cadastrado.</em>"; ?>
<br /> <br />
<?php
}
?>
Nome completo:
<input type="text" name="nome_completo" id="nome_completo" value="<?=utf8_encode($reg["nome_completo"])?>" maxlength="50" size="50" /><br /> <br />
Senha <font size="1">(evite usar caracteres especiais)</font>:
<input type="password" name="senha" id="senha" value="<?=$reg['senha']?>" maxlength="8" style="width:150px;" /> Confirmar:
<input type="password" name="confirmar" id="confirmar" value="<?=$reg['senha']?>" maxlength="8" style="width:150px;" /><br /> <br />
<div id="unidiv">
Unidade:
<select name="unidade" id="unidade">
<option value="0" selected>Selecione...</option>
<?php
$sqlx = "SELECT id_inst, nome FROM instituicao WHERE vinculado_unidade = 0 ORDER BY nome ASC";
$rsx = mysql_query($sqlx);
while ($regx = mysql_fetch_array($rsx))
{
echo '<option value="'.$regx["id_inst"].'"';
if ($reg['id_instituicao'] == $regx["id_inst"]) echo ' selected';
echo '>'.utf8_encode($regx["nome"]).'</option>';
}
?>
</select>
<br /> <br />
UF:
<select name="uf" id="uf" onChange="Dados(this.value);">
<option value="1"<? if ($reg["id_uf"] == 1) echo ' selected'; ?>>AC</option>
<option value="2"<? if ($reg["id_uf"] == 2) echo ' selected'; ?>>AL</option>
<option value="3"<? if ($reg["id_uf"] == 3) echo ' selected'; ?>>AP</option>
<option value="4"<? if ($reg["id_uf"] == 4) echo ' selected'; ?>>AM</option>
<option value="5"<? if ($reg["id_uf"] == 5) echo ' selected'; ?>>BA</option>
<option value="6"<? if ($reg["id_uf"] == 6) echo ' selected'; ?>>CE</option>
<option value="7"<? if ($reg["id_uf"] == 7) echo ' selected'; ?>>DF</option>
<option value="8"<? if ($reg["id_uf"] == 8) echo ' selected'; ?>>ES</option>
<option value="9"<? if ($reg["id_uf"] == 9) echo ' selected'; ?>>GO</option>
<option value="10"<? if ($reg["id_uf"] == 10) echo ' selected'; ?>>MA</option>
<option value="11"<? if (empty($reg["id_uf"])) echo ' selected'; if ($reg["id_uf"] == 11) echo ' selected'; ?>>MT</option>
<option value="12"<? if ($reg["id_uf"] == 12) echo ' selected'; ?>>MS</option>
<option value="13"<? if ($reg["id_uf"] == 13) echo ' selected'; ?>>MG</option>
<option value="14"<? if ($reg["id_uf"] == 14) echo ' selected'; ?>>PA</option>
<option value="15"<? if ($reg["id_uf"] == 15) echo ' selected'; ?>>PB</option>
<option value="16"<? if ($reg["id_uf"] == 16) echo ' selected'; ?>>PR</option>
<option value="17"<? if ($reg["id_uf"] == 17) echo ' selected'; ?>>PE</option>
<option value="18"<? if ($reg["id_uf"] == 18) echo ' selected'; ?>>PI</option>
<option value="19"<? if ($reg["id_uf"] == 19) echo ' selected'; ?>>RJ</option>
<option value="20"<? if ($reg["id_uf"] == 20) echo ' selected'; ?>>RN</option>
<option value="21"<? if ($reg["id_uf"] == 21) echo ' selected'; ?>>RS</option>
<option value="22"<? if ($reg["id_uf"] == 22) echo ' selected'; ?>>RO</option>
<option value="23"<? if ($reg["id_uf"] == 23) echo ' selected'; ?>>RR</option>
<option value="24"<? if ($reg["id_uf"] == 24) echo ' selected'; ?>>SC</option>
<option value="25"<? if ($reg["id_uf"] == 25) echo ' selected'; ?>>SP</option>
<option value="26"<? if ($reg["id_uf"] == 26) echo ' selected'; ?>>SE</option>
<option value="27"<? if ($reg["id_uf"] == 27) echo ' selected'; ?>>TO</option>
</select>
Cidade:
<select name="cidade" id="cidade" onchange="document.getElementById('outra_cidade').value = '';">
<option id="opcoes" value="0">Selecione...</option>
</select>
<script language='JavaScript' type="text/javascript">
Dados(document.getElementById('uf').value);
</script>
Outra: <input type="text" name="outra_cidade" id="outra_cidade" value="" maxlength="35" size="35" onchange="document.getElementById('cidade').value = 0;" />
<br /> <br />
</div>
E-mail:
<input type="text" name="email" id="email" value="<?=utf8_encode($reg["email"])?>" maxlength="50" size="50" />
<br /> <br />
<div id="depdiv">
Departamento:
<select name="departamento" id="departamento">
<option value="0">Selecione...</option>
<?php
//Lista todos os andamentos acima mais os de abertura
$sqlx = "SELECT id, departamento FROM departamentos ORDER BY departamento ASC";
$rsx = mysql_query($sqlx);
while ($regx = mysql_fetch_array($rsx))
{
echo '<option value="'.$regx["id"].'"';
if ($regx["id"] == $reg["id_departamento"]) echo ' selected';
echo '>'.utf8_encode($regx["departamento"]).'</option>';
}
?>
</select>
<br /> <br />
Nível de acesso:
<select id="nivel" name="nivel">
<option value="-1">Selecione...</option>
<?php
for ($i = 0; $i < 4; $i++)
{
echo '<option value="'.$i.'"';
if (!empty($idx)) if ($i == $reg['nivel']) echo ' selected';
echo '>'.StrUserNivel($i).'</option>';
}
?>
</select>
<br /> <br />
<input type="checkbox" id="inativo" name="inativo"<? if (!empty($idx)) if ($reg['ativo'] == false) echo 'checked="true"'; ?> />
<input type="hidden" id="ativo" name="ativo" value="0" /><font color="Red">Usuário desativado</font>
<br /> <br />
</div>
<input type="button" value="Salvar" id="btnSalvar" onclick="Salvar();" style="font-weight:bold;" />
<input type="button" value="Cancelar" onclick="window.open('lista_usuarios.php', '_self');" />
</form>
<br /> <br />
</td>
</tr>
<!-- FIM DE CONTEUDO DA PAGINA -->
<?php
include("../sol/includes/rp.php");
?>
</table>
</body>
</html>
<?php
@mysql_close();
?>