Viewing file: funcoes_uteis.php (13.19 KB) -rwxr-xr-x Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
// Funções
function db_stmt_bind_param_(&$stmt,$tipo_dados,$params)
{
array_unshift($params,$tipo_dados);
array_unshift($params,$stmt);
return call_user_func_array('mysqli_stmt_bind_param',$params);
}
/* Executa a query */
function ExecutaSQLStatment($conexao,$sql,$tipo_dados,$parametros)
{
if($stmt = $conexao->prepare($sql))
{
// Anexa os parâmetros na senteça sql
$res = db_stmt_bind_param_($stmt,$tipo_dados,$parametros);
if($res)
{
// Executa a query
$exec = $stmt->execute();
if($exec)
{
$stmt->close();
$conexao->commit();
return true;
}
else
{
$msg = $stmt->error;
$stmt->close();
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
/* Formata a data no formato escolhido */
function FormataData($data,$formato,$mostra_data = false)
{
if ($data == "")
return "";
list($data,$hora) = explode(" ",$data);
/*if(strpos(chr(32),$data) !== false)
{
echo "teste";
list($data,$hora) = explode(" ",$data);
}
*/
if($formato == "BD")
{
list($dia,$mes,$ano) = explode("/",$data);
$data = $ano . "-" . $mes . "-" . $dia;
}
elseif($formato == "SCREEN")
{
list($ano,$mes,$dia) = explode("-",$data);
$data = $dia . "/" . $mes . "/" . $ano;
}
if($mostra_data == true)
{
return $data . " " . $hora;
}
else
{
return $data;
}
}
/* Formata o telefone no formato escolhido */
function FormataTelefone($telefone,$formato,$ddd = false)
{
if($formato == "BD")
{
$telefone = str_replace("(","",$telefone);
$telefone = str_replace(")","",$telefone);
$telefone = str_replace(" ","",$telefone);
$telefone = str_replace("-","",$telefone);
return $telefone;
}
elseif($formato == "SCREEN")
{
if($ddd)
{
$telefone = "(" . substr($telefone,0,2) . ") " . substr($telefone,2,4) . "-" . substr($telefone,6,4);
}
else
{
$telefone = str_replace("-","",$telefone);
$telefone = substr($telefone,0,4) . "-" . substr($telefone,4,4);
}
return $telefone;
}
}
/* Formata o cep no formato escolhido */
function FormataCEP($cep,$formato)
{
if($formato == "BD")
{
$cep = str_replace("-","",$cep);
return $cep;
}
elseif($formato == "SCREEN")
{
$cep = substr($cep,0,5) . "-" . substr($cep,5,3);
return $cep;
}
}
/* Redireciona para uma página específica */
function Redireciona($pagina,$parametros = null)
{
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
if(!is_null($parametros))
{
$querystring = "?";
$num_parametro = 1;
foreach($parametros as $key => $valor)
{
if($num_parametro > 1)
{
$querystring .= "&";
}
$querystring .= "$key=$valor";
$num_parametro ++;
}
}
$url = "http://$host$uri/$pagina$querystring";
if(!headers_sent())
{
//If headers not sent yet... then do php redirect
header("Location: http://$host$uri/$pagina$querystring");
exit;
}
else
{
//If headers are sent... do java redirect... if java disabled, do html redirect.
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>';
exit;
}
}
//Adicionar WHERE ou AND a condição - AJUSTAR DEPOIS COM REGEX
function PreparaCondicaoSQL(&$ordem,&$condicao)
{
if($ordem > 0)
{
$condicao .= " AND ";
}
else
{
$condicao .= " WHERE ";
}
$ordem++;
}
//Prepara a querystring da requisição
function SerializaQuerystring($param)
{
if(count($param) > 0)
{
$querystring = "?";
foreach($param as $chave => $valor)
{
$querystring .= $chave . "=" . $valor . "&";
}
$querystring = substr($querystring, 0, strlen($querystring) - 1);
}
return $querystring;
}
//Verifica se o campo possui valor não padrão
function ValidaValor($valor)
{
if(in_array($valor,array(0,"00/00/0000")))
{
return $valor = "";
}
return $valor;
}
//Gera uma senha aleatória
function GeraSenhaAleatoria()
{
$caracteres_aceitos = 'abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ0123456789';
$max = strlen($caracteres_aceitos) - 1;
$senha = null;
for($i = 0; $i < 6; $i++)
{
$senha .= $caracteres_aceitos[mt_rand(0, $max)];
}
return $senha;
}
/* Exemplo de uso:
qtd_ou_mascara -> numérico, retorna uma senha totalmente aleatória
qtd_ou_mascara -> QQQ -> retorna tres numeros ou letras aleatórios
qtd_ou_mascara -> NNN -> retorna tres números aleatórios
qtd_ou_mascara -> AAA -> retorna tres letras aleatórias
qtd_ou_mascara -> NNNAAA -> retorna tres letras mais tres números aleatórios
*/
function GeraSenhaAleatoriaMascara($qtd_ou_mascara)
{
/*
Rodrigo J Polette
NetNigro
02/2009
Mascara:
A - Alfanumérico
N - Número
Q - Qualquer
*/
if (is_numeric($qtd_ou_mascara))
$qtd_ou_mascara = str_repeat("Q",$qtd_ou_mascara);
$qtd_ou_mascara = strtoupper($qtd_ou_mascara);
$senha = "";
for ($i=0;$i<strlen($qtd_ou_mascara);$i++) {
if ($qtd_ou_mascara[$i] == "Q") {
if (rand(1,100) > 50)
$qtd_ou_mascara[$i] = "A";
else
$qtd_ou_mascara[$i] = "N";
}
if ($qtd_ou_mascara[$i] == "A") {
if (rand(1,100) > 50)
$senha .= chr(rand(0,25)+65);//Maiusculo
else
$senha .= chr(rand(0,25)+97);//Minusculo
}
else
$senha .= chr(rand(0,9)+48);
}
return $senha;
}
//Funções
function EnviaEmail($assunto,$texto,$email_remetente,$email_destino)
{
//Cabeçalho
$headers = "From: $email_remetente\n";
//$headers .= "Bcc: ti@netnigro.com.br\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: text/html; charset=iso-8859-1\n";
$headers .= "Bcc : cron.irpen@netnigro.com.br\n";
$corpo_email = "<html>
<head>
<title>$assunto</title>
<style type=\"text/css\">
body {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
text-align: justify;
}
</style>
</head>
<body>
<p><img src=\"http://www.arpenpr.org.br/imagens/newsletter/cabecalho.png\"></p>"
. stripslashes($texto) .
"<p><img src=\"http://www.arpenpr.org.br/imagens/newsletter/rodape.png\"></p>
</body>
</html>";
if(mail($email_destino,$assunto,$corpo_email,$headers))
{
return true;
}
else
{
return false;
}
}
define("STR_REDUCE_LEFT", 1);
define("STR_REDUCE_RIGHT", 2);
define("STR_REDUCE_CENTER", 4);
/*
* function str_reduce (str $str, int $max_length [, str $append [, int $position [, bool $remove_extra_spaces ]]])
*
* @return string
*
* Reduz uma string sem cortar palavras ao meio. Pode-se reduzir a string pela
* extremidade direita (padrão da função), esquerda, ambas ou pelo centro. Por
* padrão, serão adicionados três pontos (...) à parte reduzida da string, mas
* pode-se configurar isto através do parâmetro $append.
* Mantenha os créditos da função.
*
* @autor: Carlos Reche
* @data: Jan 21, 2005
*/
function str_reduce($str, $max_length, $append = NULL, $position = STR_REDUCE_RIGHT, $remove_extra_spaces = true)
{
if (!is_string($str))
{
echo "<br /><strong>Warning</strong>: " . __FUNCTION__ . "() expects parameter 1 to be string.";
return false;
}
else if (!is_int($max_length))
{
echo "<br /><strong>Warning</strong>: " . __FUNCTION__ . "() expects parameter 2 to be integer.";
return false;
}
else if (!is_string($append) && $append !== NULL)
{
echo "<br /><strong>Warning</strong>: " . __FUNCTION__ . "() expects optional parameter 3 to be string.";
return false;
}
else if (!is_int($position))
{
echo "<br /><strong>Warning</strong>: " . __FUNCTION__ . "() expects optional parameter 4 to be integer.";
return false;
}
else if (($position != STR_REDUCE_LEFT) && ($position != STR_REDUCE_RIGHT) &&
($position != STR_REDUCE_CENTER) && ($position != (STR_REDUCE_LEFT | STR_REDUCE_RIGHT)))
{
echo "<br /><strong>Warning</strong>: " . __FUNCTION__ . "(): The specified parameter '" . $position . "' is invalid.";
return false;
}
if ($append === NULL)
{
$append = "...";
}
$str = html_entity_decode($str);
if ((bool)$remove_extra_spaces)
{
$str = preg_replace("/\s+/s", " ", trim($str));
}
if (strlen($str) <= $max_length)
{
return htmlentities($str);
}
if ($position == STR_REDUCE_LEFT)
{
$str_reduced = preg_replace("/^.*?(\s.{0," . $max_length . "})$/s", "\\1", $str);
while ((strlen($str_reduced) + strlen($append)) > $max_length)
{
$str_reduced = preg_replace("/^\s?[^\s]+(\s.*)$/s", "\\1", $str_reduced);
}
$str_reduced = $append . $str_reduced;
}
else if ($position == STR_REDUCE_RIGHT)
{
$str_reduced = preg_replace("/^(.{0," . $max_length . "}\s).*?$/s", "\\1", $str);
while ((strlen($str_reduced) + strlen($append)) > $max_length)
{
$str_reduced = preg_replace("/^(.*?\s)[^\s]+\s?$/s", "\\1", $str_reduced);
}
$str_reduced .= $append;
}
else if ($position == (STR_REDUCE_LEFT | STR_REDUCE_RIGHT))
{
$offset = ceil((strlen($str) - $max_length) / 2);
$str_reduced = preg_replace("/^.{0," . $offset . "}|.{0," . $offset . "}$/s", "", $str);
$str_reduced = preg_replace("/^[^\s]+|[^\s]+$/s", "", $str_reduced);
while ((strlen($str_reduced) + (2 * strlen($append))) > $max_length)
{
$str_reduced = preg_replace("/^(.*?\s)[^\s]+\s?$/s", "\\1", $str_reduced);
if ((strlen($str_reduced) + (2 * strlen($append))) > $max_length)
{
$str_reduced = preg_replace("/^\s?[^\s]+(\s.*)$/s", "\\1", $str_reduced);
}
}
$str_reduced = $append . $str_reduced . $append;
}
else if ($position == STR_REDUCE_CENTER)
{
$pattern = "/^(.{0," . floor($max_length / 2) . "}\s)|(\s.{0," . floor($max_length / 2) . "})$/s";
preg_match_all($pattern, $str, $matches);
$begin_chunk = $matches[0][0];
$end_chunk = $matches[0][1];
while ((strlen($begin_chunk) + strlen($append) + strlen($end_chunk)) > $max_length)
{
$end_chunk = preg_replace("/^\s?[^\s]+(\s.*)$/s", "\\1", $end_chunk);
if ((strlen($begin_chunk) + strlen($append) + strlen($end_chunk)) > $max_length)
{
$begin_chunk = preg_replace("/^(.*?\s)[^\s]+\s?$/s", "\\1", $begin_chunk);
}
}
$str_reduced = $begin_chunk . $append . $end_chunk;
}
return htmlentities($str_reduced);
}
?>
|