PageRenderTime 44ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/config/funcoes.php

https://bitbucket.org/cristianhaas/sistemaescolar
PHP | 273 lines | 162 code | 50 blank | 61 comment | 28 complexity | 079f0653cc5e2908e7b4d007b8e99eda MD5 | raw file
Possible License(s): BSD-2-Clause, Apache-2.0, MIT, GPL-3.0
  1. <?php
  2. function crip($msg){
  3. $date="08:36:21";
  4. $chave="X1C3fh50";
  5. $iv = md5( md5(($date)) );
  6. return base64_encode(utf8_encode( mcrypt_encrypt(
  7. MCRYPT_RIJNDAEL_256, md5( $chave ),
  8. $msg, MCRYPT_MODE_CBC, $iv
  9. )));
  10. }
  11. function descrip($msg){
  12. $date="08:36:21";
  13. $chave="X1C3fh50";
  14. return rtrim(
  15. mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5($chave), utf8_decode(base64_decode($msg)), MCRYPT_MODE_CBC, md5( md5($date))),
  16. "\x00..\x1F"
  17. );
  18. }
  19. function notificacao($titulo,$mensagem,$tipo){
  20. echo "<script>";
  21. echo "new PNotify({";
  22. echo "title: '".$titulo."',";
  23. echo "text: '".$mensagem."',";
  24. echo " type: '".$tipo."',";
  25. echo " styling: 'bootstrap3'";
  26. echo "});";
  27. echo "</script>";
  28. }
  29. //funcao de envio do email
  30. function enviarEmail( $para, $assunto, $corpo ) {
  31. //importa o phpmailer
  32. require '../classes/PHPMailerAutoload.php';
  33. //define o usuario e senha do gmail
  34. define( 'GUSER', "cristianhassfretes@gmail.com" ); // <-- Insira aqui o seu GMail
  35. define( 'GPWD', "euquerocafe" ); // <-- Insira aqui a senha do seu GMail
  36. global $error;
  37. $mail = new PHPMailer();
  38. $mail->IsSMTP(); // Ativar SMTP
  39. $mail->SMTPDebug = 0; // Debugar: 1 = erros e mensagens, 2 = mensagens apenas
  40. $mail->SMTPAuth = true; // Autenticação ativada
  41. $mail->SMTPSecure = 'tls'; // SSL REQUERIDO pelo GMail
  42. $mail->Host = 'smtp.gmail.com'; // SMTP utilizado
  43. $mail->Port = 587; // A porta 587 deverá estar aberta em seu servidor
  44. $mail->Username = GUSER;
  45. $mail->Password = GPWD;
  46. $mail->SetFrom(GUSER, "Sistema Escolar");
  47. $mail->Subject = $assunto;
  48. $mail->Body = $corpo;
  49. $mail->AddAddress( $para );
  50. $mail->CharSet = 'utf-8';
  51. if ( !$mail->Send() ) {
  52. $error = 'Mail error: ' . $mail->ErrorInfo;
  53. return false;
  54. } else {
  55. return true;
  56. }
  57. }
  58. function validaEmail($email){
  59. //verifica se e-mail esta no formato correto de escrita
  60. if (!preg_match('/^([a-zA-Z0-9.-_])*([@])([a-z0-9]).([a-z]{2,3})/',$email)){
  61. return false;
  62. }
  63. else{
  64. //Valida o dominio
  65. $dominio=explode('@',$email);
  66. if(!checkdnsrr($dominio[1],'MX')){
  67. return false;
  68. }
  69. else{return true;} // Retorno true para indicar que o e-mail é valido
  70. }
  71. }
  72. function remover_caracter($string) {
  73. // matriz de entrada
  74. $what = array( 'ä','ã','à','á','â','ê','ë','è','é','ï','ì','í','ö','õ','ò','ó','ô','ü','ù','ú','û','À','Á','É','Í','Ó','Ú','ñ','Ñ','ç','Ç',' ','-','(',')',',',';',':','|','!','"','#','$','%','&','/','=','?','~','^','>','<','ª','º','.' );
  75. // matriz de saída
  76. $by = array( 'a','a','a','a','a','e','e','e','e','i','i','i','o','o','o','o','o','u','u','u','u','A','A','E','I','O','U','n','n','c','C','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','','-','-','-','-','-','-','-' );
  77. // devolver a string
  78. return str_replace($what, $by, $string);
  79. }
  80. function textoLink($txt){
  81. $saida=remover_caracter($txt);
  82. $saida=explode('--',$saida);
  83. $saida=implode('-',$saida);
  84. $saida=strtolower($saida);
  85. return $saida;
  86. }
  87. function texto ($texto,$maximo){
  88. $texto = strip_tags($texto);
  89. $conta = strlen($texto);
  90. if($conta <= $maximo){
  91. return $texto;
  92. }
  93. else{
  94. $limita =substr($texto, 0,$maximo);
  95. return $limita.'...';
  96. }}
  97. function ProcurarImagensNoHTML( $html) {
  98. $pattern='/<img.*src="(.*?)".*\/?>/';
  99. $result=preg_match_all($pattern,$html,$matches);
  100. if(!$result){
  101. return false;
  102. }
  103. $matches=$matches[0];
  104. return $matches;
  105. }
  106. function limpaTexto ($texto){
  107. return mysql_real_escape_string(strip_tags(trim(stripslashes($texto))));
  108. }
  109. /**
  110. * @author Luís Fred
  111. * @mail fred.alphax@gmail.com
  112. */
  113. /*Esta é a função que se encarregará de criar as imagens menores, ela contem
  114. *5 variáveis como parâmetros, que são:
  115. * $filetype: o tipo de arquivo envolvido, se gif, jpeg ou png;
  116. * $origfile: E o arquivo de imagem original, que você indicou para upload e que dará
  117. * origem à uma imagem menor(thumb);
  118. * $thumbfile: Este parâmetro irá conter o caminho/nome da imagem que será a nossa imegem
  119. * de tamanho reduzido(thumb);
  120. * $new_w: Esta variável irá conter o valor de configuração para a largura da imagem menor;
  121. * $new_h: Está variável irá conter o valor de configuração para a altura da imagem menor;
  122. */
  123. function createthumbnail($filetype, $origfile, $thumbfile, $new_w, $new_h, $compress) {
  124. /*Nas três linhas que seguem, são feitas algumas verificações acerca do tipo de arquivo de imagem.
  125. *Para cada verificação bem sucedida, é criado um novo arquivo de imagem apartir da imagem original.
  126. *a função imagecreatefrom*() retorna um identificador de imagem representando a imagem obtida através do nome de *arquivo dado.
  127. **/
  128. if ($filetype == 1) { $origimage = imagecreatefromgif($origfile); }
  129. elseif ($filetype == 2) { $origimage = imagecreatefromjpeg($origfile); }
  130. elseif ($filetype == 3) { $origimage = imagecreatefrompng($origfile); }
  131. /*Nestas duas linhas que seguem, note que são obtidas largura e altura da imagem com as funções
  132. *imagesx() e imagesy() respectivamente. para mais informações sobre as funções utilizadas neste
  133. *script, acesse www.php.net
  134. */
  135. $old_x = imagesx($origimage);
  136. $old_y = imagesy($origimage);
  137. /*verifica se a largura e altura obtidas anteriormente são maiores
  138. *que a largura e a altura estabelecidas estabelecidas para as imagens menores
  139. *que serão criadas.
  140. *Em seguida, estabelece as novas dimensões para a imagem original. veja o uso
  141. *da funcção round() na terceira linha do laço if():
  142. *$thumb_w = round(($old_x * $new_h) / $old_y).
  143. *multiplica-se o valor da largura que foi obtida da imagem, usando imagesx() pelo
  144. *valor da altura estabelecido para a imagem menor. em seguida divide-se o valor obtido
  145. *pela altura da imagem original, a função roud() arredonda o valor do resultado nesta
  146. *operação. Este resultado é então armazenado na variável $thumb_w, que será a largura
  147. *da imagem pequena.
  148. *a operação $thumb_h = round(($old_y * $new_w) / $old_x); segue o mesmo raciocínio.
  149. */
  150. if ($old_x > $new_w || $old_y > $new_h) {
  151. if ($old_x < $old_y) {
  152. $thumb_w = round(($old_x * $new_h) / $old_y);
  153. $thumb_h = $new_h;
  154. } elseif ($old_x > $old_y) {
  155. $thumb_w = $new_w;
  156. $thumb_h = round(($old_y * $new_w) / $old_x);
  157. } else {
  158. $thumb_w = $new_w;
  159. $thumb_h = $new_h;
  160. }
  161. } else {
  162. $thumb_w = $old_x;
  163. $thumb_h = $old_y;
  164. }
  165. /*apartir daqui, temos a criação propriamente dita, das imagens pequenas.
  166. *Repare nas funções imagecreate() e imagecreatetruecolor(). Esta ultima requer
  167. *versão GD 2.0.1 ou maiores. se não for possível usar gd1, então será usada gd2 para
  168. *diminuir a imagem original.
  169. *a função imagecopyresized() redimensiona e copia a imagem.
  170. *imagecreatetruecolor() tem um efeito similar a imagecreate().
  171. *Para mais informações a respeito de imagecreatetruecolor(), imagecreate() e imagecopyresampled(),
  172. *acesse www.php.net.
  173. */
  174. if ($compress == "gd1") {
  175. $thumbimage = imagecreate($thumb_w,$thumb_h);
  176. $result = imagecopyresized($thumbimage, $origimage, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
  177. } else {
  178. $thumbimage = imagecreatetruecolor($thumb_w,$thumb_h);
  179. $result = imagecopyresampled($thumbimage, $origimage, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
  180. }
  181. /*Muda o tempo de acesso e modificação do arquivo de imagem fornecido como terceiro parâmetro da função *createthumbnail() para o tempo atual.
  182. */
  183. touch($thumbfile);
  184. /*a função imagegif() cria uma imagem gif em $thumbfile apartir de $thumbimage
  185. *que guarda a imagem que foi criada com novas dimensões.
  186. *imagejpeg() e imagepng() tem efeitos similares a função imagegif().
  187. */
  188. if ($filetype == 1) { imagegif($thumbimage, $thumbfile); }
  189. elseif ($filetype == 2) { imagejpeg($thumbimage, $thumbfile); }
  190. elseif ($filetype == 3) { imagepng($thumbimage, $thumbfile); }
  191. }
  192. /*Esta função checa se uma imagem existe em um determinado diretório.
  193. *se a imagem procurada existir, então será criado um nome diferente para ela
  194. */
  195. function image_exists($dir, $image) {
  196. $i = 1;
  197. $image_name = substr($image, 0, strrpos($image, "."));
  198. $image_ext = strrchr($image,".");
  199. while (file_exists($dir.$image)) {
  200. $image = $image_name."_".$i.$image_ext;
  201. $i++;
  202. }
  203. return $image;
  204. }
  205. function data($d1, $d2, $type='', $sep='-')
  206. {
  207. $d1 = explode($sep, $d1);
  208. $d2 = explode($sep, $d2);
  209. $segundos= ( ( ( mktime($d2[3], $d2[4], $d2[5], $d2[0], $d2[1], $d2[2]) - mktime($d1[3], $d1[4], $d1[5], $d1[0], $d1[1], $d1[2]) ) ));
  210. if($segundos>=86400){
  211. return intval($segundos/86400)." dia (s)";
  212. }
  213. else if($segundos>=3600){
  214. return intval($segundos/3600)." hora (s)";
  215. }
  216. else if($segundos>=60){
  217. return intval($segundos/60)." min (s)";
  218. }
  219. else{
  220. return "agora";
  221. }
  222. }
  223. ?>