· 6 years ago · Apr 23, 2019, 08:44 PM
1<?php
2
3/**
4 * Model Validação
5 */
6class ValidacaoModel
7{
8
9 var $campo;
10 var $valor;
11 var $msg = array();
12 var $possui_erro;
13
14 // Mensagens de erro
15 function mensagens($num, $campo = "", $min = "", $max = "")
16 {
17 $this->msg[0] = _("Preencha o campo com um <b>E-mail</b> válido"); // EMAIL
18 $this->msg[1] = _("CEP com formato inválido (Ex: XXXXX-XXX)"); // CEP
19 $this->msg[2] = _("Data inválida use dd/mm/aaaa"); // DATA
20 $this->msg[3] = _("Telefone inválido (Ex: 01433333333)"); // TELEFONE
21 $this->msg[4] = _("CPF inválido!"); // CPF
22 $this->msg[5] = _("IP inválido (Ex: 192.168.10.1)"); // IP
23 $this->msg[6] = _("Preencha <b>" . $campo . "</b> com somente números"); // APENAS NUMEROS
24 $this->msg[7] = _("URL especificada é inválida (Ex: http://www.google.com)"); // URL
25 $this->msg[8] = _("Preencha <b>" . $campo . "</b>"); // CAMPO VAZIO
26 $this->msg[9] = _("O <b>" . $campo . "</b> deve ter no máximo <b>" . $max . "</b> caracteres"); // MÃXIMO DE CARACTERES
27 $this->msg[10] = _("O <b>" . $campo . "</b> deve ter no mÃnimo <b>" . $min . "</b> caracteres"); // MÃNIMO DE CARACTERES
28 $this->msg[11] = _("O nome de usuário deve ter de 6 a 20 caracteres.<br />Deve iniciar por letra. Não utilize acentuação, \"_\", \"-\" e números.<br /> Sem espaço em branco");
29 $this->msg[12] = _("O nome de usuário <b>\"<b>" . $campo . "</b>\"</b> não está disponÃvel escolha outro.");
30 $this->msg[13] = _("A senha deve ter de 6 a 20 caracteres e pelo menos um número.");
31 $this->msg[14] = _("A senha repetida não está igual repita o processo.");
32 $this->msg[15] = _("O e-mail <b>\"<b>" . $campo . "</b>\"</b> já foi cadastrado. Se você esqueceu sua senha solicite uma nova <a href=\"/secao/esqueceu_senha&email=" . $campo . "\">clicando aqui!</a>.");
33 $this->msg[16] = _("Selecione uma opção no campo <b>" . $campo . "</b>");
34 $this->msg[17] = _("Digite o código de verificação do formulário corretamente");
35 $this->msg[18] = _("O e-mail <b>\"<b>" . $campo . "</b>\"</b> já foi cadastrado. Se necessário solicite ao administrador a reativação do cadastro.");
36 $this->msg[19] = _("Selecione um arquivo");
37 $this->msg[20] = _("Preencha <b>" . $campo . "</b>");
38 $this->msg[21] = _("CNPJ inválido");
39 $this->msg[22] = _("O captcha deve ser preenchido corretamente");
40 $this->possui_erro = true;
41 return $this->msg[$num];
42 }
43
44 // Validar Email
45 function validarEmail($email)
46 {
47 if (!preg_match("/^[a-z0-9_\.\-]+@[a-z0-9_\.\-]*[a-z0-9_\-]+\.[a-z]{2,4}$/", $email)) {
48 return $this->mensagens(0, 'email', null, null);
49 }
50 }
51
52 // Validar CEP (xxxxx-xxx)
53 function validarCep($cep)
54 {
55 if (!preg_match("/^[0-9]{5}-[0-9]{3}$/", $cep)) {
56 return $this->mensagens(1, 'cep', null, null);
57 }
58 }
59
60 // Validar login somente letras e número sem espaço
61 function validarUsuario($usuario)
62 {
63 #if (!preg_match('/^[a-z\_\-]{3,5}$/',$usuario)) {
64 if (!preg_match('/^[a-zA-Z][a-zA-Z0-9\_\-]{5,19}$/', $usuario)) {
65 return $this->mensagens(11);
66 }
67 if ($this->verifica_se_usuario_existe($usuario)) {
68 return $this->mensagens(12, $usuario);
69 }
70 }
71
72 // Validar senha do usuário
73 function validarSenha($senha, $repita_senha)
74 {
75 if (!preg_match("/^.*(?=.{6,10})(?=.*\d)(?=.*[0-9]).*$/", $senha)) {
76 return $this->mensagens(13);
77 }
78 if ($senha != $repita_senha) {
79 return $this->mensagens(14);
80 }
81 }
82
83 /**
84 * Verficica se a data informanda é válida
85 * @param date $data data formato dd/mm/yyyy
86 */
87 function check_data($data)
88 {
89 if ($data) {
90 $explode = explode("/", $data);
91 if (@checkdate($explode[1], $explode[0], $explode[2])) {
92 return true;
93 } else {
94 return false;
95 }
96 } else {
97 return false;
98 }
99 }
100
101 // Validar Datas (DD/MM/AAAA)
102 function validarData($data)
103 {
104 if (!$this->check_data($data)) {
105 return $this->mensagens(2, 'data', null, null);
106 }
107 }
108
109 // Valida Arquivo
110 function validarArquivo()
111 {
112 if (!$_FILES["arquivo"]["tmp_name"]) {
113 return $this->mensagens(19, 'arquivo', null, null);
114 }
115 }
116
117 // Valida Arquivo
118 function validarArquivoMultiplos()
119 {
120 if (!$_FILES["arquivo"]["tmp_name"][0]) {
121 return $this->mensagens(19, 'arquivo', null, null);
122 }
123 }
124
125 // Validar Telefone (01432363810)
126 function validarTelefone($telefone)
127 {
128 if (!preg_match("/^[0-9]{11}$/", $telefone)) {
129 return $this->mensagens(3, 'telefone', null, null);
130 }
131 }
132
133 /**
134 * Validar CPF
135 * @param $cpf int
136 */
137 function validarCpf($cpf)
138 {
139 $cpf_invalido = array("00000000000", "11111111111", "22222222222",
140 "44444444444", "55555555555", "66666666666",
141 "77777777777", "88888888888", "99999999999");
142 if (!is_numeric($cpf) || in_array($cpf, $cpf_invalido)) {
143 $status = false;
144 } else {
145 // Pega o digito verificador
146 $dv_informado = substr($cpf, 9, 2);
147
148 for ($i = 0; $i <= 8; $i++) {
149 $digito[$i] = substr($cpf, $i, 1);
150 }
151 // Calcula o valor do 10° digito de verificação
152 $posicao = 10;
153 $soma = 0;
154
155 for ($i = 0; $i <= 8; $i++) {
156 $soma = $soma + $digito[$i] * $posicao;
157 $posicao = $posicao - 1;
158 }
159
160 $digito[9] = $soma % 11;
161
162 if ($digito[9] < 2) {
163 $digito[9] = 0;
164 } else {
165 $digito[9] = 11 - $digito[9];
166 }
167
168 // Calcula o valor do 11° digito de verificação
169 $posicao = 11;
170 $soma = 0;
171
172 for ($i = 0; $i <= 9; $i++) {
173 $soma = $soma + $digito[$i] * $posicao;
174 $posicao = $posicao - 1;
175 }
176
177 $digito[10] = $soma % 11;
178
179 if ($digito[10] < 2) {
180 $digito[10] = 0;
181 } else {
182 $digito[10] = 11 - $digito[10];
183 }
184
185 // Verifica de o dv é igual ao informado
186 $dv = $digito[9] * 10 + $digito[10];
187
188 if ($dv != $dv_informado) {
189 $status = false;
190 } else
191 $status = true;
192 }
193
194 // Se houver erro
195 if (!$status) {
196 return $this->mensagens(4, 'cpf', null, null);
197 }
198 }
199
200 /**
201 * Validar CNPJ
202 * @param $cpf int
203 */
204 function validarCnpj($cnpj)
205 {
206
207 if (strlen($cnpj) <> 14 || $cnpj == 0) {
208 return $this->mensagens(21, 'cnpj', null, null);
209 }
210 $soma = 0;
211 $soma += ($cnpj[0] * 5);
212 $soma += ($cnpj[1] * 4);
213 $soma += ($cnpj[2] * 3);
214 $soma += ($cnpj[3] * 2);
215 $soma += ($cnpj[4] * 9);
216 $soma += ($cnpj[5] * 8);
217 $soma += ($cnpj[6] * 7);
218 $soma += ($cnpj[7] * 6);
219 $soma += ($cnpj[8] * 5);
220 $soma += ($cnpj[9] * 4);
221 $soma += ($cnpj[10] * 3);
222 $soma += ($cnpj[11] * 2);
223
224 $d1 = $soma % 11;
225 $d1 = $d1 < 2 ? 0 : 11 - $d1;
226
227 $soma = 0;
228 $soma += ($cnpj[0] * 6);
229 $soma += ($cnpj[1] * 5);
230 $soma += ($cnpj[2] * 4);
231 $soma += ($cnpj[3] * 3);
232 $soma += ($cnpj[4] * 2);
233 $soma += ($cnpj[5] * 9);
234 $soma += ($cnpj[6] * 8);
235 $soma += ($cnpj[7] * 7);
236 $soma += ($cnpj[8] * 6);
237 $soma += ($cnpj[9] * 5);
238 $soma += ($cnpj[10] * 4);
239 $soma += ($cnpj[11] * 3);
240 $soma += ($cnpj[12] * 2);
241
242 $d2 = $soma % 11;
243 $d2 = $d2 < 2 ? 0 : 11 - $d2;
244
245 if ($cnpj[12] == $d1 && $cnpj[13] == $d2) {
246 return false;
247 } else {
248 return $this->mensagens(21, 'cnpj', null, null);
249 }
250 }
251
252 // Validar IP (200.200.200.200)
253 function validarIp($ip)
254 {
255 if (!preg_match("/^([0-9]){1,3}.([0-9]){1,3}.([0-9]){1,3}.([0-9]){1,3}$/", $ip)) {
256 return $this->mensagens(5, 'ip', null, null);
257 }
258 }
259
260 // Validar radio
261 function validarRadio($campo, $valor)
262 {
263 if (!$valor) {
264 return $this->mensagens(16, $campo);
265 }
266 }
267
268 // Validar select
269 function validarSelect($campo, $valor)
270 {
271 if ($valor == "") {
272 return $this->mensagens(16, $campo);
273 }
274 }
275
276 // Validar checkbox
277 function validarCheckbox($campo, $valor)
278 {
279 if ($valor == "") {
280 return $this->mensagens(16, $campo);
281 }
282 }
283
284 // Validar radio
285 function validarCodigoValidacao($valor)
286 {
287 if (strtoupper($valor) != strtoupper($_SESSION[gd_code]) || !$valor) {
288 return $this->mensagens(17);
289 }
290 }
291
292 // Validar Numero
293 function validarNumero($campo, $numero)
294 {
295 if (!is_numeric($numero)) {
296 return $this->mensagens(6, $campo, null, null);
297 }
298 }
299
300 // Validar URL
301 function validarUrl($url)
302 {
303 if (!preg_match('|^http(s)?://[a-z0-9-]+(\.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url)) {
304 return $this->mensagens(7, $campo, null, null);
305 }
306 }
307
308 // Verificação simples (Campo vazio, maximo/minimo de caracteres)
309 function validarCampo($campo, $valor, $min, $max = "")
310 {
311 if ($valor == "") {
312 return $this->mensagens(8, $campo, $min, $max);
313 } elseif ($valor && $min == 0) {
314 return false;
315 } elseif ($max && strlen($valor) > $max) {
316 return $this->mensagens(9, $campo, $min, $max);
317 } elseif (strlen($valor) < $min) {
318 return $this->mensagens(10, $campo, $min, $max);
319 }
320 }
321
322 // Verifica se há erros
323 function verifica()
324 {
325 if (sizeof($this->msg) == 0) {
326 return true;
327 } else {
328 return false;
329 }
330 }
331
332 /**
333 * Seta imagem e rótulo da mensagem de validação
334 * @param array $vet = POST
335 */
336 function seta_img_rotulo($vet, $valida)
337 {
338 if (count($valida) > 0) {
339 $_SESSION["print_rotulo_value"] = array();
340 foreach ($vet as $rotulo => $value) {
341 $_SESSION["print_rotulo_value"][] = $rotulo . " - " . $value;
342 if (empty($valida[$rotulo])) {
343 $rotulo_valida[$rotulo] = "campo_ok";
344 $img_check[$rotulo] = "<i class=\"fa fa-check\" style=\"color: green\"></i>";
345 } else {
346 if (array_key_exists($rotulo, $valida)) {
347 $rotulo_valida[$rotulo] = "campo_erro";
348 $img_check[$rotulo] = "<i class=\"fa fa-exclamation-triangle\" style=\"color: red\"></i>";
349 }
350 }
351 }
352 }
353 $_SESSION["print_rotulo_valida"] = $rotulo_valida;
354 return array($img_check, $rotulo_valida);
355 }
356
357 /**
358 * Verifica se o usuário já existe
359 * @param str $usuario = usuario
360 * @param str $usuario_ant = usuario anterior em caso de edição
361 */
362 function verifica_se_usuario_existe($usuario, $usuario_ant = "")
363 {
364 if (!strnatcasecmp($usuario, $usuario_ant)) {
365 return false;
366 } else {
367 $sql = "SELECT usuario
368 FROM sb_usuario
369 WHERE usuario = '$usuario'";
370 //
371 list($db, $num) = QueryDB($sql);
372 //
373 if ($num) {
374 return true;
375 } else {
376 return false;
377 }
378 }
379 }
380
381 /**
382 * Verifica se o email já foi cadastrado
383 * @param str $email = email
384 * @param bool $retornar_id retorta o ID ou erro
385 */
386 function verifica_se_email_existe($email, $retornar_id = false)
387 {
388 $conn = new Connection;
389 $sql = "SELECT id_pessoa
390 FROM sb_pessoa
391 WHERE email = '$email'";
392 //echo "<pre>$sql</pre>";
393 list($res, $num) = $conn->QueryDB($sql);
394 //
395 if ($num) {
396 if ($retornar_id) {
397 $d = mysql_fetch_array($res);
398 return $d[id_pessoa];
399 } else {
400 return true;
401 }
402 } else {
403 return false;
404 }
405 }
406
407 /**
408 * Verifica se o cpf já existe
409 * @param str $cpf = cpf
410 */
411 function verifica_se_cpf_existe($cpf)
412 {
413 $obj_conn = new Connection;
414 $sql = "SELECT cpf
415 FROM sb_pessoa_fisica
416 WHERE cpf = '$cpf'";
417 list($db, $num) = $obj_conn->QueryDB($sql);
418 //
419 if ($num)
420 return true;
421 else
422 return false;
423 }
424
425 /**
426 * Verifica se o cpf de participante já existe
427 * @param str $cpf = cpf
428 */
429 function verifica_se_cpf_participante_existe($cpf)
430 {
431 $obj_conn = new Connection;
432 $sql = "SELECT doc_num
433 FROM participante
434 WHERE doc_num = '$cpf'";
435 list($db, $num) = $obj_conn->QueryDB($sql);
436 //
437 if ($num) {
438 return true;
439 } else {
440 return false;
441 }
442 }
443
444 /**
445 * Verifica se o email de participante já existe
446 * @param str $cpf = cpf
447 */
448 function valida_email_participante($email)
449 {
450 $obj_conn = new Connection;
451 $sql = "SELECT email
452 FROM participante
453 WHERE email = '$email'";
454 list($db, $num) = $obj_conn->QueryDB($sql);
455 //
456 if ($num) {
457 return true;
458 } else {
459 return false;
460 }
461 }
462
463 /**
464 * Limpa CPF ou CNPJ deixando somente números
465 */
466 function limpaCPF_CNPJ($valor)
467 {
468 $valor = preg_replace('/[\.\-\,\/]/', '', $valor);
469 return $valor;
470 }
471
472 /**
473 * formatada uma data informando o formato e a saida EX: format input "Y/m/d" output "d/m/Y"
474 * @param date $data
475 * @param str $input
476 * @param str $output
477 */
478 function data_formatada($data, $input, $output)
479 {
480 if ($data) {
481 $data_result = DateTime::createFromFormat($input, $data)->format($output);
482 return $data_result;
483 } else {
484 return false;
485 }
486 }
487
488 function Format($value, $style)
489 {
490 if (empty($value)) {
491 if ($style == "now")
492 return date("d/m/Y H:i:s");
493 else
494 return " ";
495 }
496 else {
497 if (is_string($value) || $style == "0")
498 $value = intval(strtotime($value) / 86400);
499
500 if ($style == "0")
501 $date = $value;
502 else if ($style == "now")
503 $date = date("d/m/Y H:i:s");
504 else
505 $date = date($style, ($value + 1) * 86400);
506
507 return $date;
508 }
509 }
510
511 /**
512 * Validar reCaptcha Google
513 * @return mensagem de erro
514 */
515 function valida_captcha_google($captcha)
516 {
517 if (!$captcha) {
518 return $this->mensagens(22);
519 }
520
521 $secretKey = "6Lc-sZsUAAAAAFksdrCFMEozn6QT_fELdVpWuLqy";
522 $ip = $_SERVER['REMOTE_ADDR'];
523 $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
524 $response = file_get_contents($url);
525 $responseKeys = json_decode($response, true);
526
527 if (!$responseKeys["success"]) {
528 return $this->mensagens(22);
529 }
530 }
531
532}