Commit 787c8d5f1b0fd40ab2dc4cde176d3969543aa078

Authored by Leandro Arndt
1 parent 30c98f06
Exists in mysqli

Classe DB

Utilização da classe DB pelos arquivos da interface pública (por enquanto, à excessão das demais classes).
acompanhamento/cadastro.php
... ... @@ -8,6 +8,7 @@
8 8 modificá-lo sob os termos da Licença GPL2.
9 9 ***********************************************************************************/
10 10  
  11 + include_once("../class/db.class.php");
11 12 include("manutencao.php");
12 13 include("../inc/topo.php");
13 14 ?>
... ... @@ -226,9 +227,9 @@
226 227 <td width="100%" colspan="4">
227 228 <table align="center" width="100%" cellpadding="0" cellspacing="1" class="tabListaDetalhe">
228 229 <?php
229   - $rsAnexo = execQuery("select * from lda_anexo where idsolicitacao=$idsolicitacao order by idanexo");
  230 + $rsAnexo = DB::execQuery("select * from lda_anexo where idsolicitacao=".DB::esc($idsolicitacao)." order by idanexo");
230 231 $i=0;
231   - while($row = mysql_fetch_array($rsAnexo)){
  232 + while($row = mysqli_fetch_array($rsAnexo)){
232 233 $i++;
233 234 ?>
234 235 <tr>
... ...
acompanhamento/index.php
... ... @@ -10,6 +10,7 @@
10 10  
11 11 include("../inc/autenticar.php");
12 12 include_once("../class/solicitacao.class.php");
  13 +include_once("../class/db.class.php");
13 14 include("../inc/topo.php");
14 15 include("../inc/paginacaoPorPostIni.php");
15 16  
... ... @@ -21,8 +22,8 @@ $situacao = $_REQUEST[&quot;fltsituacao&quot;];
21 22  
22 23 $parametrosIndex = "fltnumprotocolo=$numprotocolo&fltsituacao=$situacao"; //parametros a ser passado para a pagina de detalhamento, fazendo com que ao voltar para o index traga as informações passadas anteriormente
23 24  
24   -if (!empty($numprotocolo)) $filtro.= " and concat(sol.numprotocolo,'/',sol.anoprotocolo) = '$numprotocolo'";
25   -if (!empty($situacao)) $filtro.= " and sol.situacao = '$situacao'";
  25 +if (!empty($numprotocolo)) $filtro.= " and concat(sol.numprotocolo,'/',sol.anoprotocolo) = '".DB::esc($numprotocolo)."'";
  26 +if (!empty($situacao)) $filtro.= " and sol.situacao = '".DB::esc($situacao)."'";
26 27  
27 28  
28 29  
... ... @@ -33,8 +34,8 @@ if (!empty($situacao)) $filtro.= &quot; and sol.situacao = &#39;$situacao&#39;&quot;;
33 34 $sql = "select sol.*, tip.nome as tiposolicitacao
34 35 from lda_solicitacao sol, lda_tiposolicitacao tip
35 36 where tip.idtiposolicitacao = sol.idtiposolicitacao
36   - and sol.idsolicitante = $idsolicitante
37   - $filtro
  37 + and sol.idsolicitante = ".DB::esc($idsolicitante)."
  38 + ".DB::esc($filtro)."
38 39 order by sol.anoprotocolo, sol.numprotocolo, sol.idsolicitacao";
39 40  
40 41 /*if ($_REQUEST['imprimir']) {
... ... @@ -47,7 +48,6 @@ $rs = execQueryPag($sql);
47 48 <h1>Consulta de Solicitações Realizadas</h1>
48 49 <br><br>
49 50 <form action="<?php echo URL_BASE_SISTEMA;?>/acompanhamento/index.php" method="post" id="formulario">
50   -<input type="hidden" name="pagina" id="pagina" value="<?php echo $pagina?>">
51 51 <fieldset style="width: 50%;">
52 52 <legend>Buscar:</legend>
53 53 <table align="center">
... ... @@ -90,7 +90,7 @@ $rs = execQueryPag($sql);
90 90 </tr>
91 91 <?php
92 92 $cor=false;
93   - while ($registro = mysql_fetch_array($rs)) {
  93 + while ($registro = mysqli_fetch_array($rs)) {
94 94 $click = "editar('".$registro["idsolicitacao"]."&$parametrosIndex','".URL_BASE_SISTEMA."acompanhamento/cadastro');";
95 95  
96 96 if($cor)
... ...
class/db.class.php
... ... @@ -19,9 +19,13 @@ class DB {
19 19 return self::$mysqli;
20 20 }
21 21  
22   - static function execQuery($query) {
23   - // Resolve o problema da injeção de SQL:
24   - $rs = mysqli_query(self::conn(), mysqli_real_escape_string(self::CONN(), $query));
  22 + // Escapa os caracteres especiais, evitando injeção de SQL e HTML:
  23 + static function esc($param) {
  24 + return mysqli_real_escape_string(self::conn(), htmlentities($param));
  25 + }
  26 +
  27 + static function execQuery($query, $style = MYSQLI_USE_RESULT) {
  28 + $rs = self::conn()->query($query, $style);
25 29 return $rs;
26 30 }
27 31  
... ...
enquete/manutencao.php
... ... @@ -10,6 +10,7 @@
10 10  
11 11 include_once("../inc/autenticar.php");
12 12 include_once("../class/solicitacao.class.php");
  13 +include_once("../class/db.class.php");
13 14  
14 15 function validaDados()
15 16 {
... ... @@ -39,9 +40,9 @@ if ($_POST[&quot;Enviar&quot;]) {
39 40 $sql="INSERT INTO lda_enquete
40 41 (idsolicitante, resposta, comentario, dataresposta)
41 42 VALUES
42   - (".getSession("uid").", '".$resposta."','".(str_replace("'","\'",$comentario))."',NOW())";
  43 + (".getSession("uid").", '".DB::esc($resposta)."','".DB::esc($comentario)."',NOW())";
43 44  
44   - if (!execQuery($sql))
  45 + if (!DB::execQuery($sql))
45 46 $erro = "Erro ao gravar enquete";
46 47  
47 48 }
... ...
estatistica/index.php
... ... @@ -8,19 +8,19 @@
8 8 modificá-lo sob os termos da Licença GPL2.
9 9 ***********************************************************************************/
10 10  
11   -
12 11 include("../inc/database.php");
13   -
  12 + include_once("../class/db.class.php");
  13 +
14 14 //recupera o quantitativo de solicitações em aberto e respondidas por ano
15 15 $sql = "SELECT anoprotocolo as ano,
16 16 count(*) as qtde
17 17 FROM lda_solicitacao
18 18 GROUP BY anoprotocolo
19 19 ORDER BY anoprotocolo";
20   -
21   - $rs = execQuery($sql);
  20 +
  21 + $rs = DB::execQuery($sql, MYSQLI_STORE_RESULT);
22 22  
23   - $numRegistros = mysql_num_rows($rs);
  23 + $numRegistros = mysqli_num_rows($rs);
24 24  
25 25 if ($numRegistros>0)
26 26 {
... ... @@ -28,13 +28,13 @@
28 28 $anos="";
29 29 $dados="";
30 30 $maiornumero = 0;
31   - while ($row = mysql_fetch_assoc($rs)) {
  31 + while ($row = mysqli_fetch_assoc($rs)) {
32 32 $i++;
33 33  
34 34 //recupera o quantitativo de solicitações no ano da iteração que foram respondidas
35 35 $sql="select count(*) as tot from lda_solicitacao where anoprotocolo = ".$row['ano']." and situacao in('R','N')";
36   - $rsResp = execQuery($sql);
37   - $rowResp = mysql_fetch_array($rsResp);
  36 + $rsResp = DB::execQuery($sql);
  37 + $rowResp = mysqli_fetch_array($rsResp);
38 38  
39 39 //se for o ultimo registro nao imprime a virgula no final
40 40 if ($i==$numRegistros)
... ... @@ -54,7 +54,7 @@
54 54  
55 55 }
56 56  
57   - }
  57 + }
58 58  
59 59 include("../inc/topo.php");
60 60 ?>
... ...
inc/buscacep.php
... ... @@ -8,6 +8,7 @@
8 8 modificá-lo sob os termos da Licença GPL2.
9 9 ***********************************************************************************/
10 10  
  11 + include_once("../class/db.class.php");
11 12 include "../inc/database.php";
12 13  
13 14 $f = $_REQUEST['f'];
... ... @@ -16,11 +17,11 @@
16 17 tipologradouro, bairro,
17 18 cidade, uf
18 19 from vw_cep
19   - where cep = '$f'
  20 + where cep = '".DB::esc($f)."'
20 21 ";
21 22  
22   - $resultado = execQuery($sql);
23   - $row = mysql_fetch_array($resultado);
  23 + $resultado = DB::execQuery($sql);
  24 + $row = mysqli_fetch_array($resultado);
24 25  
25 26 ?>
26 27 <script>
... ...
inc/funcoes.php
... ... @@ -8,6 +8,8 @@
8 8 modificá-lo sob os termos da Licença GPL2.
9 9 ***********************************************************************************/
10 10  
  11 +include_once("../class/db.class.php");
  12 +
11 13 function isEmail($eMailAddress)
12 14 {
13 15 if (eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,3}$", $eMailAddress, $check))
... ... @@ -178,9 +180,9 @@ function validaTipoArquivo($mime, $extensoes)
178 180 {
179 181 $sql = "select * from sis_mime where extensao in($extensoes) and mime = '$mime'";
180 182  
181   - $rs = execQuery($sql);
  183 + $rs = DB::execQuery($sql);
182 184  
183   - if(mysql_num_rows($rs)>0)
  185 + if(mysqli_num_rows($rs)>0)
184 186 return true;
185 187 else
186 188 return false;
... ...
inc/paginacaoIni.php
... ... @@ -9,12 +9,15 @@
9 9 ***********************************************************************************/
10 10  
11 11 //PAGINACAO - PARTE INICIAL
  12 +
  13 +include_once("../class/db.class.php");
12 14  
13 15 $total="";
14 16 //retorna a quantidade de registros da consulta
15 17 function execQueryPag($consulta){
16 18 global $total;
17 19 global $limit;
  20 + global $maximo;
18 21  
19 22 $consulta = strtolower($consulta);
20 23  
... ... @@ -25,10 +28,17 @@
25 28 $row = mysql_fetch_assoc($resultado);
26 29 $total = $row["total"];*/
27 30  
28   - $rs = execQuery($consulta);
29   - $total = mysql_num_rows($rs);
  31 + $rs = DB::execQuery($consulta, MYSQLI_STORE_RESULT);
  32 + $total = $rs->num_rows;
  33 +
  34 + return db::execQuery($consulta.$limit);
30 35  
31   - return execQuery($consulta.$limit);
  36 + if ( $total > $maximo ) {
  37 + return DB::execQuery($consulta.$limit);
  38 + } else {
  39 + return $rs;
  40 + }
  41 +
32 42  
33 43 }
34 44  
... ...
inc/paginacaoPorPostFim.php
... ... @@ -82,7 +82,7 @@ if($pgs &gt; 1 )
82 82 }
83 83  
84 84 ?>
85   - &nbsp;&nbsp;Pág.:
  85 + &nbsp;&nbsp;P&aacute;g.:
86 86 <select onchange="document.getElementById('pagina').value=this.value;document.getElementById('formulario').submit();">
87 87 <?php for($x=1;$x<=$pgs;$x++){?>
88 88 <option value="<?php echo $x;?>" <?php echo ($pagina==$x)?"selected":"";?>><?php echo $x;?></option>
... ...
inc/paginacaoPorPostIni.php
... ... @@ -10,11 +10,14 @@
10 10  
11 11 //PAGINACAO - PARTE INICIAL
12 12  
  13 +include_once("../class/db.class.php");
  14 +
13 15 $total="";
14 16 //retorna a quantidade de registros da consulta
15 17 function execQueryPag($consulta){
16 18 global $total;
17 19 global $limit;
  20 + global $maximo;
18 21  
19 22 $consulta = strtolower($consulta);
20 23  
... ... @@ -25,15 +28,18 @@
25 28 $row = mysql_fetch_assoc($resultado);
26 29 $total = $row["total"];*/
27 30  
28   - $rs = execQuery($consulta);
29   - $total = mysql_num_rows($rs);
30   -
31   - return execQuery($consulta.$limit);
32   -
  31 + $rs = DB::execQuery($consulta, MYSQLI_STORE_RESULT);
  32 + $total = $rs->num_rows;
  33 +
  34 + if ( $total > $maximo ) {
  35 + return DB::execQuery($consulta.$limit);
  36 + } else {
  37 + return $rs;
  38 + }
33 39 }
34 40  
35 41 // Declaração da pagina inicial
36   - $pagina = $_POST["pagina"];
  42 + $pagina = $_POST["pagina"];
37 43 if($pagina == "")
38 44 {
39 45 $pagina = "1";
... ...
inc/security.php
... ... @@ -10,6 +10,7 @@
10 10  
11 11 require_once ("database.php");
12 12 require_once ("funcoes.php");
  13 +include_once("../class/db.class.php");
13 14  
14 15 function sendMail($to, $subject,$body,$from="",$fromname="")
15 16 {
... ... @@ -17,9 +18,9 @@ function sendMail($to, $subject,$body,$from=&quot;&quot;,$fromname=&quot;&quot;)
17 18 if(empty($from))
18 19 {
19 20 $sql = "select nomeremetenteemail, emailremetente from lda_configuracao";
20   - $rs = execQuery($sql);
  21 + $rs = DB::execQuery($sql);
21 22  
22   - $row = mysql_fetch_array($rs);
  23 + $row = mysqli_fetch_array($rs);
23 24  
24 25 $from = $row['emailremetente'];
25 26 $fromname = $row['nomeremetenteemail'];
... ... @@ -54,9 +55,9 @@ function sendMailAnexo($to, $subject,$body,$arquivos=array(),$from=&quot;&quot;,$fromname=
54 55 if(empty($from))
55 56 {
56 57 $sql = "select nomeremetenteemail, emailremetente from lda_configuracao";
57   - $rs = execQuery($sql);
  58 + $rs = DB::execQuery($sql);
58 59  
59   - $row = mysql_fetch_array($rs);
  60 + $row = mysqli_fetch_array($rs);
60 61  
61 62 $from = $row['emailremetente'];
62 63 $fromname = $row['nomeremetenteemail'];
... ... @@ -124,16 +125,16 @@ function setTentativaLogin($usuario)
124 125 {
125 126 $ipaddr = $_SERVER["REMOTE_ADDR"];
126 127 $sistema = SISTEMA_CODIGO;
127   - $query = "insert into sis_errologin (sistema, usuario,ip) values('$sistema','$usuario','$ipaddr')";
128   - execQuery($query) or die("Ocorreu um erro inesperado ao logar erro de entrada");
  128 + $query = "insert into sis_errologin (sistema, usuario,ip) values('".DB::esc($sistema)."','".DB::esc($usuario)."','".DB::esc($ipaddr)."')";
  129 + DB::execQuery($query) or die("Ocorreu um erro inesperado ao logar erro de entrada");
129 130 }
130 131  
131 132 //exclui da tabela de erros de login, as tentativa sem sucesso de acesso ao sistema
132 133 function delTentativaLogin($usuario)
133 134 {
134 135 $sistema = SISTEMA_CODIGO;
135   - $query = "delete from sis_errologin where usuario='$usuario' and sistema = '$sistema'";
136   - execQuery($query) or die("Ocorreu um erro inesperado ao excluir tentativas de acesso");
  136 + $query = "delete from sis_errologin where usuario='".DB::esc($usuario)."' and sistema = '".DB::esc($sistema)."'";
  137 + DB::execQuery($query) or die("Ocorreu um erro inesperado ao excluir tentativas de acesso");
137 138 }
138 139  
139 140 /*---------------------------------------------------------------------------
... ... @@ -147,12 +148,12 @@ function usaRecaptcha($usuario)
147 148 $sistema = SISTEMA_CODIGO;
148 149  
149 150 $query = "select * from sis_errologin
150   - where usuario='$usuario' and sistema = '$sistema'";
  151 + where usuario='".DB::esc($usuario)."' and sistema = '".DB::esc($sistema)."'";
151 152  
152   - $rs = execQuery($query);
  153 + $rs = DB::execQuery($query, MYSQLI_STORE_RESULT);
153 154  
154 155 //se houver tentativas registradas retorna true para exibir o controle recaptcha
155   - return (mysql_num_rows($rs) >0) ;
  156 + return ($rs->num_rows >0) ;
156 157  
157 158 }
158 159  
... ... @@ -170,13 +171,13 @@ function autentica($login, $pwd, $tipo)
170 171  
171 172 $query = "select idsolicitante as id, nome, confirmado, email
172 173 from lda_solicitante
173   - where cpfcnpj='$login' and chave = '".md5($pwd)."' ";
  174 + where cpfcnpj='".DB::esc($login)."' and chave = '".DB::esc(md5($pwd))."' ";
174 175  
175   - $rs = execQuery($query);
  176 + $rs = DB::execQuery($query, MYSQLI_STORE_RESULT);
176 177  
177   - if (mysql_num_rows($rs) !=0)
  178 + if ($rs->num_rows !=0)
178 179 {
179   - $row = mysql_fetch_array($rs);
  180 + $row = mysqli_fetch_array($rs);
180 181 }
181 182 else
182 183 {
... ... @@ -213,11 +214,11 @@ function getDiretorio($sis = &quot;lda&quot;){
213 214  
214 215 $query = "select diretorioarquivos from lda_configuracao";
215 216  
216   - $rs = execQuery($query);
  217 + $rs = DB::execQuery($query, MYSQLI_STORE_RESULT);
217 218  
218   - if (mysql_num_rows($rs) !=0)
  219 + if ($rs->num_rows !=0)
219 220 {
220   - $row = mysql_fetch_array($rs);
  221 + $row = mysqli_fetch_array($rs);
221 222 $retorno = $row['diretorioarquivos'];
222 223 }
223 224  
... ... @@ -231,20 +232,21 @@ function getURL($sis = &quot;alb&quot;){
231 232  
232 233 $query = "select urlarquivos from lda_configuracao";
233 234  
234   - $rs = execQuery($query);
  235 + $rs = DB::execQuery($query);
235 236  
236   - if (mysql_num_rows($rs) !=0)
  237 + if ($rs->num_rows !=0)
237 238 {
238   - $row = mysql_fetch_array($rs);
  239 + $row = mysqli_fetch_array($rs);
239 240 $retorno = $row['urlarquivos'];
240 241 }
241 242  
242 243 return $retorno;
243 244 }
244 245  
245   -
  246 +// Transformada em caminho alternativo para DB::esc($param)
246 247 function prepData($var) {
247   - $conn = db_open();
  248 + return DB::esc($var);
  249 + /*$conn = db_open();
248 250  
249 251 if (get_magic_quotes_gpc()) {
250 252 $var = stripslashes($var);
... ... @@ -254,22 +256,22 @@ function prepData($var) {
254 256  
255 257 db_close($conn);
256 258  
257   - return $retorno;
  259 + return $retorno;*/
258 260 }
259 261  
260 262 function logger($msg) {
261 263 $usuario = getSession("uid");
262   - $usuario = empty($usuario)?"SYSTEM":$usuario;
  264 + $usuario = prepData(empty($usuario)?"SYSTEM":$usuario);
263 265  
264 266 // Ugly fix pra nao permitir salvar senha em banco.
265 267 unset($_POST["senha"]);
266 268  
267   - $mensagem = $msg;
  269 + $mensagem = prepData($msg);
268 270 $datahora = "now()";
269 271 $dados_post = prepData(serialize($_POST));
270 272 $dados_get = prepData(serialize($_GET));
271 273 $dados_session = prepData(serialize($_SESSION));
272   - $ipaddr = $_SERVER["REMOTE_ADDR"];
  274 + $ipaddr = prepData($_SERVER["REMOTE_ADDR"]);
273 275  
274 276 $query = "insert into sis_log (usuario,mensagem,datahora,dados_get,dados_post,ipaddr) values('$usuario','$mensagem',$datahora,'$dados_get','$dados_post','$ipaddr')";
275 277 execQuery($query) or die("Erro logando");
... ...
restrito/alterasenha/manutencao.php
... ... @@ -9,8 +9,9 @@
9 9 ***********************************************************************************/
10 10  
11 11 include_once("../inc/autenticar.php");
12   - include_once("../class/solicitante.class.php");
13   -
  12 + include_once("../inc/config.php");
  13 + include_once(DIR_CLASSES_LEIACESSO."/solicitante.class.php");
  14 + include_once(DIR_CLASSES_LEIACESSO."/db.class.php");
14 15  
15 16 $erro = ""; //grava o erro, se houver, e exibe por meio de alert (javascript) atraves da funcao getErro() chamada no arquivo do formulario. ps: a função é declara em inc/security.php
16 17  
... ... @@ -26,16 +27,16 @@
26 27  
27 28  
28 29 $sql = "select chave from sis_usuario where idusuario = $idusuario";
29   - $rs = execQuery($sql);
  30 + $rs = DB::execQuery($sql);
30 31  
31   - if(mysql_num_rows($rs) == 0)
  32 + if(mysqli_num_rows($rs) == 0)
32 33 {
33 34 $erro = "Usuário não encontrado";
34 35 return false;
35 36 }
36 37 else
37 38 {
38   - $row = mysql_fetch_array($rs);
  39 + $row = mysqli_fetch_array($rs);
39 40 $chave = $row['chave'];
40 41  
41 42 if(md5($senhaatual) != $chave)
... ... @@ -55,9 +56,9 @@
55 56 chave = '".md5($novasenha)."'
56 57 WHERE idusuario = $idusuario";
57 58  
58   - if (!execQuery($sql))
  59 + if (!DB::execQuery($sql))
59 60 {
60   - $erro = "Erro ao alterar senha do solicitante";
  61 + $erro = "Erro ao alterar senha do solicitante. ".mysqli_error(DB::conn());
61 62 }
62 63 else
63 64 {
... ...
solicitacao/formulario.php
... ... @@ -8,6 +8,8 @@
8 8 modificá-lo sob os termos da Licença GPL2.
9 9 ***********************************************************************************/
10 10  
  11 +include_once("../class/db.class.php");
  12 +
11 13 ?>
12 14 <input type="hidden" name="idsolicitante" value="<?php echo $idsolicitante;?>">
13 15 <table align="center" cellpadding="0" cellspacing="1">
... ... @@ -19,8 +21,8 @@
19 21 Destino:
20 22 <select name="idsecretariaselecionada" id="idsecretaria">
21 23 <option value="">----</option>
22   - <?php $rsSic = execQuery("select idsecretaria, nome from sis_secretaria where ativado = 1 order by nome"); ?>
23   - <?php while($rowSic=mysql_fetch_array($rsSic)){?>
  24 + <?php $rsSic = DB::execQuery("select idsecretaria, nome from sis_secretaria where ativado = 1 order by nome"); ?>
  25 + <?php while($rowSic=mysqli_fetch_array($rsSic)){?>
24 26 <option value="<?php echo $rowSic['idsecretaria'];?>" <?php echo $rowSic['idsecretaria']==$idsecretariaselecionada?"selected":""; ?>><?php echo $rowSic['nome'];?></option>
25 27 <?php }?>
26 28 </select>
... ...