PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/class/Helpers/Valida.class.php

https://bitbucket.org/sounet/otimizar
PHP | 234 lines | 193 code | 36 blank | 5 comment | 37 complexity | c852355b931aa9eb863efb0a54c18caf MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception
  1. <?php
  2. /**
  3. * <strong>Valida.class</strong>
  4. * Classe responsável por validar informações do sistema
  5. * @copyright (c) 2016, André Cristhian
  6. */
  7. class Valida{
  8. private static $Data;
  9. private static $Format;
  10. public static function Email($email){
  11. self::$Data = (string) $email;
  12. self::$Format = "/^[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*\\.[A-Za-z0-9]{2,4}$/";
  13. if (preg_match(self::$Format, self::$Data)) {
  14. return true;
  15. } else {
  16. return false;
  17. }
  18. }
  19. public static function validaCPF($cpf){
  20. $cpf = preg_replace('/[^0-9]/is', '', $cpf);
  21. if (strlen($cpf) != 11) {
  22. return false;
  23. }
  24. if (preg_match('/(\d)\1{10}/', $cpf)) {
  25. return false;
  26. }
  27. for ($t = 9; $t < 11; $t++) {
  28. for ($d = 0, $c = 0; $c < $t; $c++) {
  29. $d += $cpf{$c} * (($t + 1) - $c);
  30. }
  31. $d = ((10 * $d) % 11) % 10;
  32. if ($cpf{$c} != $d) {
  33. return false;
  34. }
  35. }
  36. return true;
  37. }
  38. public static function validaCNPJ($cnpj){
  39. $cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj);
  40. $invalidos = ['00000000000000', '11111111111111', '22222222222222', '33333333333333', '44444444444444', '55555555555555', '66666666666666', '77777777777777', '88888888888888', '99999999999999'];
  41. if(strlen($cnpj) <> 14){
  42. return false;
  43. }elseif (in_array($cnpj, $invalidos)){
  44. return false;
  45. }
  46. for ($i = 0, $j = 5, $soma = 0; $i < 12; $i++){
  47. $soma += $cnpj{$i} * $j;
  48. $j = ($j == 2) ? 9 : $j - 1;
  49. }
  50. $resto = $soma % 11;
  51. if ($cnpj{12} <> ($resto < 2 ? 0 : 11 - $resto)){
  52. return false;
  53. }
  54. for ($i = 0, $j = 6, $soma = 0; $i < 13; $i++){
  55. $soma += $cnpj{$i} * $j;
  56. $j = ($j == 2) ? 9 : $j - 1;
  57. }
  58. $resto = $soma % 11;
  59. return $cnpj{13} == ($resto < 2 ? 0 : 11 - $resto);
  60. }
  61. public static function validaData($data){
  62. $data = explode("/", $data);
  63. if (checkdate($data[1], $data[0], $data[2])) {
  64. return true;
  65. }else{
  66. return false;
  67. }
  68. }
  69. public static function StrUrl($string){
  70. $a = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜüÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ"!@#$%&*()_-+={[}]/?;:.,\\\'<>°ºª';
  71. $b = 'aaaaaaaceeeeiiiidnoooooouuuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyrr ';
  72. $string = utf8_decode($string);
  73. $string = strtr($string, utf8_decode($a), $b);
  74. $string = strip_tags(trim($string));
  75. $string = str_replace(" ","-",$string);
  76. $string = str_replace(array("-----","----","---","--"),"-",$string);
  77. return strtolower(utf8_encode($string));
  78. }
  79. public static function UrlAtual(){
  80. return "http://" . $_SERVER['SERVER_NAME'] . $_SERVER ['REQUEST_URI'];
  81. }
  82. public static function DataForSql($data){
  83. return implode("-", array_reverse(explode("/", $data)));
  84. }
  85. public static function DataForUser($data){
  86. return str_replace("-", "/", implode('-', array_reverse(explode('-', $data))));
  87. }
  88. public static function GeraAes($pass){
  89. self::$Data = $pass;
  90. self::$Data = AesCtr::encrypt(self::$Data, "mi@dia#", 256);
  91. self::$Data = base64_encode(self::$Data);
  92. return self::$Data;
  93. }
  94. public static function CheckAes($pass){
  95. self::$Data = $pass;
  96. self::$Data = base64_decode(self::$Data);
  97. self::$Data = AesCtr::decrypt(self::$Data, "mi@dia#", 256);
  98. return self::$Data;
  99. }
  100. public static function GeraCodigo($lenght = 8){
  101. $returnCode = '';
  102. $chars = '';
  103. $chars .= strtoupper('abcdefghijkmnpqrstuvwxyz');
  104. $chars .= 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  105. $chars .= '123456789';
  106. $count = strlen($chars);
  107. for ($n = 1; $n <= $lenght; $n++) {
  108. $rand = mt_rand(1, $count);
  109. $returnCode .= $chars[$rand - 1];
  110. }
  111. return $returnCode;
  112. }
  113. public static function EnviarEmail($assunto,$msg_mail,$emailremetente,$nomeremetente,$emaildestino,$nomedestino){
  114. require_once(__DIR__."/../../class/Library/PHPMailer/class.phpmailer.php");
  115. $mail = new PHPMailer();
  116. $mail->IsSMTP();
  117. $mail->SMTPDebug = 1;
  118. $mail->SMTPAuth = true;
  119. $mail->IsHTML(true);
  120. $mail->Host = MAILHOST;
  121. $mail->Username = MAILUSER;
  122. $mail->Password = MAILPASS;
  123. $mail->Port = 587;
  124. $mail->CharSet = 'UTF-8';
  125. $mail->FromName = $nomeremetente;
  126. $mail->From = MAILUSER;
  127. $mail->AddReplyTo($emailremetente, $nomeremetente);
  128. $mail->Subject = $assunto;
  129. $mail->MsgHTML($msg_mail);
  130. $mail->AddAddress($emaildestino,$nomedestino);
  131. if($mail->Send()){
  132. return true;
  133. }else{
  134. return false;
  135. }
  136. }
  137. public static function GeraHash($tempo, $slat, $senha){
  138. return crypt($senha, '$2a$'.$tempo.'$'.$slat.'$');
  139. }
  140. public static function CheckHash($senha_post, $senha_bdcrypt){
  141. return (crypt($senha_post, $senha_bdcrypt) === $senha_bdcrypt);
  142. }
  143. public static function Base3($senha){
  144. return base64_encode(base64_encode(base64_encode($senha)));
  145. }
  146. public static function Rebase3($senha){
  147. return base64_decode(base64_decode(base64_decode($senha)));
  148. }
  149. public static function StatusCompra($status){
  150. if($status == "pending"){return array("Aguardando", "Fatura pendente, ainda não paga", "label-warning");}
  151. elseif($status == "paid"){return array("Aprovado", "Fatura paga", "label-success");}
  152. elseif($status == "canceled"){return array("Cancelada", "Cobrança cancelada", "label-danger");}
  153. elseif($status == "draft"){return array("Rascunho", "Ao criar uma fatura pelo painel somente, pode usar a chave rascunho para salvar os dados de uma fatura, a fatura em si ainda não foi gerada, não há uma cobrança, apenas dados salvos que podem se tornar uma cobrança.", "label-rascunho");}
  154. elseif($status == "partially_paid"){return array("Parcial", "Fatura parcialmente paga; em geral, quando um boleto não é pago o valor total da cobrança ou não é pago o valor da multa e juros pelo atraso. (pagamento após o vencimento).", "label-default");}
  155. elseif($status == "refunded"){return array("Reembolsada", "Fatura reembolsada", "label-muted");}
  156. elseif($status == "expired"){return array("Expirada", "Cobrança atingiu o tempo limite após o vencimento e expirou; não pode mais ser paga.", "label-muted");}
  157. elseif($status == "in_protest"){return array("Protesto", "Quando uma fatura já paga recebe uma notificação de não reconhecimento da compra.", "label-purple");}
  158. elseif($status == "chargeback"){return array("Reembolsada", "Reembolsado para o cliente, que ganhou a disputa.", "label-inverse");}
  159. else{return array("Erro", "Houve algum erro com o pagamento", "label-black");}
  160. }
  161. public static function StatusAutomacao($status){
  162. if($status == "0"){return array("Iniciada", "Automação iniciada", "label-assativa");}
  163. elseif($status == "1"){return array("Não iniciada", "Automação não iniciada", "label-assinativa");}
  164. else{return array("Erro", "Houve algum erro", "label-black");}
  165. }
  166. public static function StatusAssinatura($status){
  167. if($status == "0"){return array("Aguardando", "Aguardando inclusão de recorrência", "label-muted");}
  168. elseif($status == "1"){return array("Inativa", "Assinatura inativa", "label-assinativa");}
  169. elseif($status == "2"){return array("Ativa", "Assinatura ativa", "label-assativa");}
  170. else{return array("Erro", "Houve algum erro", "label-black");}
  171. }
  172. public static function criptografia_segura($data) {
  173. $first_key = base64_decode(FIRSTKEY);
  174. $second_key = base64_decode(SECONDKEY);
  175. $method = "aes-256-cbc";
  176. $iv_length = openssl_cipher_iv_length($method);
  177. $iv = openssl_random_pseudo_bytes($iv_length);
  178. $first_encrypted = openssl_encrypt($data, $method, $first_key, OPENSSL_RAW_DATA, $iv);
  179. $second_encrypted = hash_hmac('sha512', $first_encrypted, $second_key, TRUE);
  180. $output = self::Base3($iv.$second_encrypted.$first_encrypted);
  181. return $output;
  182. }
  183. public static function descriptografia_segura($input) {
  184. $first_key = base64_decode(FIRSTKEY);
  185. $second_key = base64_decode(SECONDKEY);
  186. $mix = self::Rebase3($input);
  187. $method = "aes-256-cbc";
  188. $iv_length = openssl_cipher_iv_length($method);
  189. $iv = substr($mix,0,$iv_length);
  190. $second_encrypted = substr($mix,$iv_length,64);
  191. $first_encrypted = substr($mix,$iv_length+64);
  192. $data = openssl_decrypt($first_encrypted,$method,$first_key,OPENSSL_RAW_DATA,$iv);
  193. $second_encrypted_new = hash_hmac('sha512', $first_encrypted, $second_key, TRUE);
  194. if (hash_equals($second_encrypted,$second_encrypted_new))
  195. return $data;
  196. return false;
  197. }
  198. }