$array){ $retorno[$array['tipo']] = $array; } return $retorno; } function getConfig($tipo, $retorno = null){ global $configs; $retorno = $retorno == "" ? "texto" : $retorno; return stripslashes($configs[$tipo][$retorno]); } function getConfigJSON($tipo, $key){ global $configs; $array = utf8_decode_array(json_decode(base64_decode(h_decode($configs[$tipo]['texto'])), true)); return $array[$key]; } function getConfigJSONAll($tipo, $key = "texto"){ global $configs; return utf8_decode_array(json_decode(base64_decode(h_decode($configs[$tipo][$key])), true)); } ##### function h($var){ if(get_magic_quotes_gpc()) $var = stripslashes($var); return htmlspecialchars($var, ENT_QUOTES, "iso-8859-1"); } function h_decode($string){ return htmlspecialchars_decode($string, ENT_QUOTES); } function pr($array){ $dbgt = debug_backtrace(); echo "Line: ".$dbgt[0]['line']; echo "
";
	print_r($array);
	echo "
"; } function checkbox($array, $checked, $separador = "; "){ $resultados = explode($separador, $array); for($i = 0; $i < count($resultados); $i++){ if($checked == $resultados[$i]) return " checked=\"checked\""; } } function selected($array, $checked, $separador = "; "){ $resultados = explode($separador, $array); foreach($resultados as $i => $resultado){ if((string)$checked == (string)$resultado) return " selected=\"selected\""; } } function tgAtivo2($id, $situacao, $tipo = "status", $block = false, $reload = false){ global $var_pagina; if(libera($var_pagina, "altera") && !$block){ if($situacao == "1") return "

SIM

"; else return "

NÃO

"; }else{ if($situacao == "1") return "SIM"; else return "NÃO"; } } function ni($var){ if($var == "") return "Não Informado"; return $var; } function ne($var){ if($var == "") return "-"; return $var; } function indesejado($nome){ $nome = str_replace("'", "", $nome); $nome = str_replace("´", "", $nome); $nome = str_replace("`", "", $nome); return $nome; } function acento($v){ $v = html_entity_decode($v, ENT_QUOTES, 'ISO-8859-1'); return preg_replace("[^a-zA-Z0-9]", "", strtr($v, "áàãâéêíóôõúüçÁÀÃÂÉÊÍÓÔÕÚÜÇ&", "aaaaeeiooouucAAAAEEIOOOUUCe")); } function acentoI($v){ $v = html_entity_decode($v, ENT_QUOTES, 'ISO-8859-1'); return preg_replace("[^a-zA-Z0-9_]", "", strtr($v, "aaaaeeiooouucAAAAEEIOOOUUC", "áàãâéêíóôõúüçÁÀÃÂÉÊÍÓÔÕÚÜÇ")); } function acentoM($v){ $v = html_entity_decode($v, ENT_QUOTES, 'ISO-8859-1'); return preg_replace("[^a-zA-Z0-9_]", "", strtr($v, "áàãâéêíóôõúüç", "ÁÀÃÂÉÊÍÓÔÕÚÜÇ")); } function valor($valor){ global $centsLimit; $centsLimit = empty($centsLimit) ? 2 : $centsLimit; $v = number_format($valor, $centsLimit, ',','.'); $valor = empty($valor) ? "0,00" : $v; return $valor; } function valorform($valor){ global $centsLimit; $centsLimit = empty($centsLimit) ? 2 : $centsLimit; $v = number_format($valor, $centsLimit, ',','.'); $valor = empty($valor) ? "" : $v; return $valor; } function valorsemponto($valor){ $v = str_replace(".", "", $valor); $v = str_replace(",", ".", $v); return $v; } function double($valor){ $valor = preg_replace("/[^0-9,\.]/", "", $valor); if(preg_match("/,/", $valor)){ $v = str_replace(".", "", $valor); $v = str_replace(",", ".", $v); }else{ $v = $valor; } return $v == "0.00" ? 0 : $v; } function data($date){ if(!empty($date) && $date != "0000-00-00" && $date != "0000-00-00 00:00:00"){ $date = @date("d/m/Y", strtotime($date)); }else{ $date = ""; } return $date; } function invertedata($date){ $data = explode("/", $date); $dia = $data[0]; $mes = $data[1]; $ano = $data[2]; $diacerto = $ano."-".$mes."-".$dia; return $diacerto; } function quebra($quebra){ $quebra = str_replace("\n", "
", $quebra); return $quebra; } function dia($date){ return date("d", strtotime($date)); } function setMeses(){ return array("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"); } function mes($date, $short = true){ $mes = date("n", strtotime($date)); $array = setMeses(); $retorno = $array[$mes - 1]; if($short) $retorno = substr($retorno, 0, 3); return $retorno; } function ano($str){ return date("Y", strtotime($str)); } function retorna_mes($mes, $short = true){ if($mes == "01"){ $month = "Janeiro"; }elseif($mes == "02"){ $month = "Fevereiro"; }elseif($mes == "03"){ $month = "Março"; }elseif($mes == "04"){ $month = "Abril"; }elseif($mes == "05"){ $month = "Maio"; }elseif($mes == "06"){ $month = "Junho"; }elseif($mes == "07"){ $month = "Julho"; }elseif($mes == "08"){ $month = "Agosto"; }elseif($mes == "09"){ $month = "Setembro"; }elseif($mes == "10"){ $month = "Outubro"; }elseif($mes == "11"){ $month = "Novembro"; }elseif($mes == "12"){ $month = "Dezembro"; } if($short) return substr($month, 0, 3); return $month; } function foto_mini($foto){ return semFormato($foto)."_mini.".formato($foto); } function video($video){ $quebra = explode("v=", $video); $vi = $quebra[1]; if(preg_match("/&/", $vi)){ $v = explode("&", $vi); $v = $v[0]; }else{ $v = $vi; } return $v; } function checkEmail($email){ if(!preg_match("/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/", $email)) return false; list($Username, $Domain) = preg_split("/@/",$email); if(getmxrr($Domain, $MXHost)){ return true; }else{ if(fsockopen($Domain, 25, $errno, $errstr, 30)){ return true; }else{ return false; } } } function retornaEmail($email){ return checkEmail($email); } function estadosLista(){ $estados = array( "AC" => "Acre", "AL" => "Alagoas", "AM" => "Amazonas", "AP" => "Amapá", "BA" => "Bahia", "CE" => "Ceará", "DF" => "Distrito Federal", "ES" => "Espírito Santo", "GO" => "Goiás", "MA" => "Maranhão", "MT" => "Mato Grosso", "MS" => "Mato Grosso do Sul", "MG" => "Minas Gerais", "PA" => "Pará", "PB" => "Paraíba", "PR" => "Paraná", "PE" => "Pernambuco", "PI" => "Piauí", "RJ" => "Rio de Janeiro", "RN" => "Rio Grande do Norte", "RS" => "Rio Grande do Sul", "SC" => "Santa Catarina", "SP" => "São Paulo", "SE" => "Sergipe", "RO" => "Rondônia", "RR" => "Roraima", "TO" => "Tocantins" ); return $estados; } function estado($select = null){ $estados = estadosLista(); foreach($estados as $abr => $nome){ $selected = $select == $abr ? " selected=\"selected\"" : ""; $option .= "\n"; } return $option; } function semFormato($arquivo){ $ext = strrchr($arquivo, "."); $nome = preg_replace("/{$ext}/", "", $arquivo); return $nome; } function formato($arquivo){ $ext = substr(strrchr($arquivo, "."), 1); return $ext; } function milhar($array){ $milhar = number_format($array, "", "", "."); return $milhar; } function hora($q){ $hora = date("H", strtotime($q)); $minuto = date("i", strtotime($q)); $date = $hora = $hora."h".$minuto; return $date; } function horaNormal($q){ return date("H:i:s", strtotime($q)); } function horario($q){ return date("H:i", strtotime($q)); } function dataHora($q){ return date("d/m/Y H:i", strtotime($q)); } function deleta($arquivo){ if(file_exists($arquivo)){ @unlink($arquivo); return TRUE; } return FALSE; } function decode($string){ return addslashes(utf8_decode(urldecode($string))); } function criaPasta($caminho, $nomedapasta = ""){ if(!empty($nomedapasta)) $pasta = $caminho."/".$nomedapasta; else $pasta = $caminho; if(!is_dir($pasta)){ mkdir($pasta, 0777, true); chmod($pasta, 0777); } } function apagaPasta($nomedapasta){ if($handle = opendir($nomedapasta)){ while(false !== ($file = readdir($handle))){ if($file != "." && $file != "..") deleta($nomedapasta."/".$file); } } if(is_dir($nomedapasta)) rmdir($nomedapasta); } function apagaPastaFull($caminho){ if($handle = opendir($caminho)){ while(false !== ($file = readdir($handle))){ if($file != "." && $file != ".."){ if(is_dir($caminho."/".$file)) rmdir($caminho."/".$file); else deleta($caminho."/".$file); apagaPastaFull($caminho."/".$file); } } } if(is_dir($caminho)) apagaPasta($caminho); } function renomeia($nome){ $v = html_entity_decode($nome, ENT_QUOTES, 'ISO-8859-1'); return preg_replace("/[^a-zA-Z0-9_-]/", "-", $v); } function titulo_url($titulo){ $titulo = preg_replace("/[--]+/", "-", strtolower(renomeia(acento(trim($titulo))))); $titulo = preg_replace("/(-_-)+/", "_", $titulo); return preg_replace("/(-+)$/", "", $titulo); } function url_query($string){ $string = str_replace(" ", "%", $string); $string = str_replace("-", "%", $string); return $string; } function tamanho($caminho){ $tamanhoarquivo = filesize($caminho); $bytes = array('bytes', 'KB', 'MB', 'GB', 'TB'); if($tamanhoarquivo <= 999) { $tamanhoarquivo = 1; } for($i = 0; $tamanhoarquivo > 999; $i++) { $tamanhoarquivo /= 1000; } $arquivo = filesize($caminho); $arquivo = number_format($arquivo, 2, '.', ''); return $arquivo <= 999 ? $arquivo." ".$bytes[$i] : number_format($tamanhoarquivo, 2, '.', '')." ".$bytes[$i]; } function contaCaracteres($string, $totalPermitido){ $string = strip_tags(h_decode($string)); $texto = substr($string, 0, $totalPermitido); if(strlen($string) > $totalPermitido) $texto .= "..."; return $texto; } function somenteNumeros($int){ return preg_replace("/[^0-9]/", "", $int); } function peso($array){ $ttlc = strlen($array); if($ttlc <= 3){ $retorno = $array."g"; }else{ $ret = number_format($array, 0, "", ","); $ret = explode(",", $ret); $a_ret = $ret[1]; if(substr($a_ret, 2, 1) == 0){ $retorno = $ret[0].",".substr($a_ret, 0, 2); if(substr($a_ret, 1, 1) == 0){ $retorno = $ret[0].",".substr($a_ret, 0, 1); if(substr($a_ret, 0, 1) == 0){ $retorno = $ret[0]; } } }else{ $retorno = $ret[0].",".substr($a_ret, 0, 3); } $retorno = $retorno." Kg"; } return $retorno; } function senha(){ $sConso = 'bcdfghjklmnpqrstvwxyzbcdfghjklmnpqrstvwxyz'; $sVogal = 'aeiou'; $sNum = '123456789'; $passwd = ' '; $y = strlen($sConso)-1; //conta o nº de caracteres da variável $sConso $z = strlen($sVogal)-1; //conta o nº de caracteres da variável $sVogal $r = strlen($sNum)-1; //conta o nº de caracteres da variável $sNum for($x=0; $x<=1; $x++){ $rand = rand(0,$y); //Funçao rand() - gera um valor randômico $rand1 = rand(0,$z); $rand2 = rand(0,$r); $str = substr($sConso,$rand,1); // substr() - retorna parte de uma string $str1 = substr($sVogal,$rand1,1); $str2 = substr($sNum,$rand2,1); $passwd .= $str.$str1.$str2; } $passwd = trim($passwd); return $passwd; } function codigo(){ $numbers = "1234567890"; $r = strlen($numbers)-1; //conta o nº de caracteres da variável $sNum $code = ""; for($x = 0; $x <= 5; $x++){ $rand = rand(0, $r); $str = substr($numbers, $rand, 1); $code .= $str; } $code = trim($code); return $code; } function d($string){ return date("d", strtotime($string)); } function m($string){ return date("m", strtotime($string)); } function a($string){ return date("Y", strtotime($string)); } function getTituloYoutube($url){ $arquivo = @file_get_contents($url); $arquivo = str_replace ("\n" , "", $arquivo);//retira novas linhas if (!$arquivo) { return "Incluir título"; } else { preg_match_all( "||U", $arquivo, $numero, PREG_PATTERN_ORDER); $retorno = $numero[1][0]; $retorno = str_replace(",", ".", $retorno); return addslashes(utf8_decode($retorno)); } } function url($url){ if(!preg_match("/http:\/\/|https:\/\//", $url)) $url = "http://{$url}"; return $url; } function linkar($url, $target = "_blank"){ $retorno = "{$url}"; if(!preg_match("/http:\/\/|https:\/\//", $url)) $retorno = "http://{$url}"; return $retorno; } function host($url){ global $secure; $parse = parse_url($url); $scheme = "http"; if($secure) $scheme = "https"; return $scheme."://".$parse['host'].separa($parse['path']).separa($parse['query'], "?"); } function hostEmail($string){ return preg_replace("/http:\/\/|https:\/\/|www./", "", $string); } function reload($page, $tempo = "1000"){ echo ""; } function maiusculo($string){ return strtoupper(acentoM($string)); } function validaCPF($cpf){ // Verifiva se o número digitado contém todos os digitos $cpf = str_pad(preg_replace('/[^0-9]/', '', $cpf), 11, '0', STR_PAD_LEFT); // Verifica se nenhuma das sequências abaixo foi digitada, caso seja, retorna falso if (strlen($cpf) != 11 || $cpf == '00000000000' || $cpf == '11111111111' || $cpf == '22222222222' || $cpf == '33333333333' || $cpf == '44444444444' || $cpf == '55555555555' || $cpf == '66666666666' || $cpf == '77777777777' || $cpf == '88888888888' || $cpf == '99999999999') { return false; }else{ // Calcula os números para verificar se o CPF é verdadeiro for ($t = 9; $t < 11; $t++) { for ($d = 0, $c = 0; $c < $t; $c++) { $d += $cpf{$c} * (($t + 1) - $c); } $d = ((10 * $d) % 11) % 10; if ($cpf{$c} != $d) { return false; } } return true; } } function validaCNPJ($cnpj){ if (strlen($cnpj) <> 18) return 0; $soma1 = ($cnpj[0] * 5) + ($cnpj[1] * 4) + ($cnpj[3] * 3) + ($cnpj[4] * 2) + ($cnpj[5] * 9) + ($cnpj[7] * 8) + ($cnpj[8] * 7) + ($cnpj[9] * 6) + ($cnpj[11] * 5) + ($cnpj[12] * 4) + ($cnpj[13] * 3) + ($cnpj[14] * 2); $resto = $soma1 % 11; $digito1 = $resto < 2 ? 0 : 11 - $resto; $soma2 = ($cnpj[0] * 6) + ($cnpj[1] * 5) + ($cnpj[3] * 4) + ($cnpj[4] * 3) + ($cnpj[5] * 2) + ($cnpj[7] * 9) + ($cnpj[8] * 8) + ($cnpj[9] * 7) + ($cnpj[11] * 6) + ($cnpj[12] * 5) + ($cnpj[13] * 4) + ($cnpj[14] * 3) + ($cnpj[16] * 2); $resto = $soma2 % 11; $digito2 = $resto < 2 ? 0 : 11 - $resto; return (($cnpj[16] == $digito1) && ($cnpj[17] == $digito2)); } function apagaForm($camada){ echo ""; } function jQuery($string){ echo ""; } function separa($string, $separator = null, $adicional = null){ $return = !empty($string) ? $separator.$string.$adicional : ""; return $return; } function separador($array, $joiner = ", "){ $out = array(); foreach($array as $i => $v){ if($v == "") continue; $out[] = $v; } return join($joiner, $out); } function saudacao(){ $horaAgora = date("H:i:s"); if($horaAgora >= "00:00:00" && $horaAgora < "12:00:00"){ $sauda = "Bom dia"; }elseif($horaAgora >= "12:00:00" && $horaAgora < "18:00:00"){ $sauda = "Boa tarde"; }elseif($horaAgora >= "18:00:00" && $horaAgora < "23:59:59"){ $sauda = "Boa noite"; } return $sauda; } function primeiro_nome($string){ $str = explode(" ", $string); return $str[0]; } function pesoTamanho($medida){ $medida = somenteNumeros($medida); $bytes = array('bytes', 'KB', 'MB', 'GB', 'TB'); if($medida <= 1023) $medida = 1; for($i = 0; $medida > 1023; $i++) { $medida /= 1024; } return $medida <= 1023 ? $medida." ".$bytes[$i] : number_format($medida, 2, '.', '')." ".$bytes[$i]; } function convertBytes( $value ) { if ( is_numeric( $value ) ) { return $value; } else { $value_length = strlen($value); $qty = substr( $value, 0, $value_length - 1 ); $unit = strtolower( substr( $value, $value_length - 1 ) ); switch ( $unit ) { case 'k': $qty *= 1024; break; case 'm': $qty *= 1048576; break; case 'g': $qty *= 1073741824; break; } return $qty; } } function getOperadoras(){ return array("TIM", "Claro", "CTBC Telecom", "Oi", "Vivo", "Sercomtel", "Nextel", "Outra"); } function audioHTML5($arquivo, $autoplay = false){ $formato = formato($arquivo); $atp = $autoplay ? " autoplay" : ""; return ""; } function isValidMd5($md5 =''){ return preg_match('/^[a-f0-9]{32}$/', $md5); } function getCURL($url, $header = array("Content-type: application/json")){ $header = !is_array($header) ? array($header) : $header; $tmp_fname = tempnam("tmp", "COOKIE"); $ch = curl_init($url); curl_setopt($ch, CURLOPT_COOKIEJAR, $tmp_fname); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); $result = curl_exec($ch); curl_close($ch); unlink($tmp_fname); return $result; } function postCURL($url, $post, $followlocation = false, $header = array("Content-type: multipart/form-data")){ $header = !is_array($header) ? array($header) : $header; $tmp_fname = tempnam("tmp", "COOKIE"); $ch = curl_init($url); curl_setopt($ch, CURLOPT_COOKIEFILE, $tmp_fname); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $followlocation); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $result = curl_exec($ch); if($result === false) return curl_error($ch); curl_close($ch); unlink($tmp_fname); return $result; } function fetchCURL($url, $params = array(), $method = "POST", $header = array("Content-type: multipart/form-data")){ $hdr = array( "Cache-Control: no-cache", ); $header = array_merge($hdr, $header); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CAINFO => dirname(__FILE__)."/cert/cacert.pem", CURLOPT_CUSTOMREQUEST => $method, CURLOPT_POSTFIELDS => $params, CURLOPT_HTTPHEADER => $header, )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); return array($response, $err); } function busca_cep($cep){ $url = "http://api.postmon.com.br/v1/cep/{$cep}"; return getCURL($url); } function getCorContraste($hexcolor){ $hexcolor = str_replace("#", "", $hexcolor); $r = hexdec(substr($hexcolor,0,2)); $g = hexdec(substr($hexcolor,2,2)); $b = hexdec(substr($hexcolor,4,2)); $yiq = (($r*299)+($g*587)+($b*114))/1000; return ($yiq >= 128) ? '#000' : '#FFF'; } function getPorcentagem($total, $qtd){ return (($qtd / $total) * 100); // ex.: 0.3 de 1 return 30% } function getPorcentagemDescontoFinal($total, $porcentagem){ return $total - (($total * $porcentagem) / 100); // ex.: 100.00 menos 60% return 40.00 } function zero($string){ return empty($string) ? "0" : $string; } function getLinkDownload($pasta, $arquivo, $nome){ return "download.php?dados=".base64_encode("pasta={$pasta}&arquivo={$arquivo}&nome={$nome}"); } function diasDaSemana(){ return array("Domingo", "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sábado"); } function diaSemana($data){ $dias = diasDaSemana(); $semana = date("w", strtotime($data)); return $dias[$semana]; } function getDiaDasemana($i){ $dias = diasDaSemana(); return $dias[$i]; } function newDate($data, $time = "+ 1 day", $retorno = "Y-m-d"){ return date($retorno, strtotime($data.$time)); } function contaDias($dataInicial, $dataFinal = false){ $dataFinal = !$dataFinal ? date("Y-m-d") : $dataFinal; $dias = abs(((strtotime($dataInicial) - strtotime($dataFinal)) / 86400)); return ceil($dias); } function contaDiasNegative($dataInicial, $dataFinal = false){ $dataFinal = !$dataFinal ? date("Y-m-d") : $dataFinal; $dias = ((strtotime($dataInicial) - strtotime($dataFinal)) / 86400); return ceil($dias); } function plural($num, $texto, $singular, $plural){ if($num <= 1) return $texto.$singular; return $texto.$plural; } function ckeditor($string){ global $host; $retorno = preg_replace("/\n\n/", "\n", h_decode($string)); $retorno = preg_replace("/(src=\")(.*)(\/arquivos)/", "$1{$host}$3", $retorno); return $retorno; } function _str_pad($str, $qtd = 0, $preenchimento = '0', $direcao = STR_PAD_LEFT){ return str_pad($str, $qtd, $preenchimento, $direcao); } function enc($string){ $encode = base64_encode($string); return preg_replace("/=/", "", $encode); } function getNextAutoIncrement($tabela){ global $con; $query = mysqli_query($con, "SHOW TABLE STATUS LIKE '{$tabela}'"); $dados = mysqli_fetch_assoc($query); return $dados['Auto_increment']; } function json_encode_array($array){ $out = array(); foreach($array as $i => $v){ $out[] = h($v); } return json_encode($out, JSON_UNESCAPED_UNICODE); } function setUsername($str){ return preg_replace("/[^a-zA-Z0-9\-_@\.]+/", "", acento($str)); } function visualizarArquivo($pasta, $arquivo, $class_btn = "btn-sm btn-info", $text = " Visualizar arquivo"){ if(empty($arquivo)) return; $url = $pasta."/".$arquivo; return "{$text}"; } function excluirArquivo($tabela, $id, $campo, $pasta, $arquivo, $class_btn = "btn-mini btn-danger", $text = " Excluir arquivo"){ if(empty($arquivo)) return; $url = "global.php?funcao=excluiArquivo&tabela={$tabela}&id={$id}&campo={$campo}&pasta={$pasta}&arquivo={$arquivo}"; return "{$text}"; } function chamada($str, $lenght = 250){ return contaCaracteres(strip_tags(h_decode($str)), $lenght); } function validaCampos($array = array()){ foreach($array as $v){ if((string) $v === "") return FALSE; } return TRUE; } function utf8_encode_array($array = array()){ $retorno = array(); foreach($array as $i => $dados){ if(is_array($dados)){ $retorno[$i] = utf8_encode_array($dados); }else{ $retorno[$i] = utf8_encode(h_decode($dados)); } } return $retorno; } function utf8_encode_array_simple($array = array()){ $retorno = array(); foreach($array as $i => $dados){ $retorno[$i] = addslashes(h(utf8_encode(h_decode($dados)))); } return $retorno; } function utf8_decode_array($array = array()){ $retorno = array(); foreach($array as $i => $dados){ if(is_array($dados)){ $retorno[$i] = utf8_decode_array($dados); }else{ $retorno[$i] = stripslashes(utf8_decode($dados)); } } return $retorno; } function cleanToJS($str){ return preg_replace("/\n|\r|\t/", "", $str); } function luhn($number, $iterations = 1){ while($iterations-- >= 1){ $stack = 0; $number = str_split(strrev($number), 1); foreach($number as $key => $value){ if($key % 2 == 0) $value = array_sum(str_split($value * 2, 1)); $stack += $value; } $stack %= 10; if($stack != 0) $stack -= 10; $number = implode('', array_reverse($number)) . abs($stack); } return $number; } function retornoJSON($code, $message = "", $itens = array()){ $retorno['code'] = $code; $retorno['message'] = utf8_encode($message); $retorno['itens'] = $itens; return json_encode($retorno); } function envioEmail($params = array()){ /* $params = array( "template" => "", "email_topo" => "", "dest" => "", "email_nome" => "", "email_from" => "", "email_reply" => "", "email_assunto" => "", "email_conteudo" => "", "nomeEmpresa" => "", "copia" => "", "style" => "", ); */ extract($params); if(empty($dest)) return FALSE; $email_nome = "=?UTF-8?B?".base64_encode(utf8_encode($email_nome))."?="; $email_assunto = "=?UTF-8?B?".base64_encode(utf8_encode($email_assunto))."?="; $template = empty($template) ? host($_SERVER['HTTP_HOST']).HOST."/wconfig/templates/" : $template; $email_reply = !empty($email_reply) ? $email_reply : $email_from; $headers = "From: {$email_nome} <{$email_from}>".PHP_EOL; if(!empty($copia)) $headers .= "Bcc: ".$copia.PHP_EOL; $headers .= "Return-Path: ".$email_from.PHP_EOL; $headers .= "Reply-To: ".$email_reply.PHP_EOL; $headers .= "Content-Type: text/html; charset=ISO-8859-1".PHP_EOL; $headers .= "X-Mailer: PHP/".phpversion().PHP_EOL; $headers .= "MIME-Version: 1.1".PHP_EOL; // template email $ano = date("Y"); $url_base = $template; $email_topo = $email_topo ? $email_topo : $url_base."bg_topo.jpg"; $email_rodape = "

Copyright © {$nomeEmpresa} {$ano} - Todos os Direitos Reservados.

"; $html = addslashes(file_get_contents("wconfig/templates/email.html")); eval("\$html = \"$html\";"); // template email $mensagem = <<"; }elseif(preg_match("/vimeo/", $url)){ $explode = explode(".com/", $url); $video_id = $explode[1]; return ""; }else{ return "Vídeo inválido"; } } function getDadosVimeo($url){ $explode = explode(".com/", $url); $video_id = $explode[1]; $url = "http://vimeo.com/api/v2/video/{$video_id}.xml"; $load = @simplexml_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA); if($load) foreach($load as $dados){ return $dados; } } function idade($data){ // Separa em dia, mês e ano list($ano, $mes, $dia) = explode('-', $data); // Descobre que dia é hoje e retorna a unix timestamp $hoje = mktime(0, 0, 0, date('m'), date('d'), date('Y')); // Descobre a unix timestamp da data de nascimento do fulano $nascimento = mktime( 0, 0, 0, $mes, $dia, $ano); // Depois apenas fazemos o cálculo já citado :) $idade = floor((((($hoje - $nascimento) / 60) / 60) / 24) / 365.25); return $idade; } function base64_to_jpeg($base64_string, $output_file){ $ifp = fopen($output_file, "wb"); $data = explode(',', $base64_string); fwrite($ifp, base64_decode($data[1])); fclose($ifp); return $output_file; } function base64_encode_json($str){ if(empty($str)) return; return base64_encode(json_encode(utf8_encode_array($str))); } function base64_decode_json($str, $decode = true){ if(empty($str)) return; $out = json_decode(base64_decode(h_decode($str)), true); $out = $decode ? utf8_decode_array($out) : $out; //$out = array_map("h", $out); return $out; } function utf8_decode_str($str){ return addslashes(h(utf8_decode(h_decode($str)))); } function _rtrim($str){ return rtrim(stripcslashes(stripcslashes($str))); } function novoDiaUtil($data, $dias){ $newdate = date("Y-m-d", strtotime($data." + {$dias} day")); if(date("w", strtotime($newdate)) == "6") return novoDiaUtil($data, $dias + 2); elseif(date("w", strtotime($newdate)) == "0") return novoDiaUtil($data, $dias + 1); return $newdate; } function optimizeJPG($input_path, $output_path, $quality = 60){ if(!extension_loaded('imagick')) return false; $filePath = $input_path; $im = new \Imagick($filePath); $im->setImageCompression(\Imagick::COMPRESSION_ZIP); $im->setImageCompressionQuality($quality); //$im->stripImage(); $im->setInterlaceScheme(\Imagick::INTERLACE_PLANE); //$im->gaussianBlurImage(0.05, 5); $im->setFormat("jpg"); $im->writeImage($output_path); return true; } function optimizePNG($input_path, $output_path, $quality = 90){ if(!file_exists($input_path)){ return false; // throw new Exception("File does not exist: $input_path"); } // guarantee that quality won't be worse than that. $min_quality = 60; // '-' makes it use stdout, required to save to $compressed_png_content variable // '<' makes it read from the given file path // escapeshellarg() makes this safe to use with any path $compressed_png_content = shell_exec("/usr/local/bin/pngquant --quality=$min_quality-$quality - < ".escapeshellarg($input_path)); if(!$compressed_png_content){ // throw new Exception("Conversion to compressed PNG failed. Is pngquant 1.8+ installed on the server?"); return false; } file_put_contents($output_path, $compressed_png_content); return true; } function trueDate($date){ list($ano, $mes, $dia) = explode("-", $date); return checkdate($mes * 1, $dia * 1, $ano); }