<?php
/*********************************************
Description: Functions do deliver and format strings
File: /gestao/includes/funcoes.formatacao.php
Project: Demo
Developers: João Vieira
Start Date: 2007/06/01
*********************************************/
function trd($texto, $tag){
    $inicio = "[$tag]";
    $fim = "[/$tag]";
    $iniciopos = strpos($texto, $inicio) + strlen($inicio);
    $fimpos = strpos($texto, $fim) + 1;
    $temp = substr($texto, $iniciopos, $fimpos);
    $temp = substr($temp, 0, strpos($temp, $fim));
    return $temp;
}

function ft($txtp) {
    $txtp = strip_tags($txtp, "<a>");
    $txtp = nl2br($txtp);
    //$txtp = ereg_replace("\[a","<a style=\"text-decoration:none;\" ",$txtp);
    //$txtp = ereg_replace("\"\]","\">",$txtp);
    //$txtp = ereg_replace("\[/a\]","</a>",$txtp); 
    //$txtp = ereg_replace("\n","<br>",$txtp);
    $txtp = ereg_replace(chr(13).chr(10),"<br/>",$txtp); 
    $txtp = ereg_replace(chr(13),"&nbsp;",$txtp);
    $txtp = ereg_replace(chr(10),"&nbsp;",$txtp);
 return $txtp;
}

function EscapeString($str)
{
    $str = str_replace("\"","", $str);
    $str = str_replace(array('\\', "'"), array("\\\\", "\\'"), $str);
    $str = preg_replace('#([\x00-\x1F])#e', '"\x" . sprintf("%02x", ord("\1"))', $str);

    return $str;
}


function formata_urllink($texto) {function ImageResize ($fileRaw, $imageWidthNew, $fullLink) {
        
        list($imageWidth, $imageHeight, $imageType, $imageAttr) = getimagesize($fileRaw['tmp_name']);
        $imageSource = "";
        
        $imageHeightNew = round( $imageHeight * ($imageWidthNew/$imageWidth) );
        $imageFinal=imagecreatetruecolor($imageWidthNew, $imageHeightNew)
        or die('Problems creating new image');
        
        $imageSource=ImageCreateFromJPEG($fileRaw['tmp_name'])
        or die('Problems openning JPG file');
        
        imagecopyresampled($imageFinal, $imageSource, 0, 0, 0, 0, $imageWidthNew, $imageHeightNew, $imageWidth, $imageHeight);
        
        if ( file_exists($fullLink) ) unlink($fullLink); 
        
        imagejpeg($imageFinal, $fullLink, 100);
        
        imagedestroy($imageSource);
        imagedestroy($imageFinal);
        
}
    $from = array("Ã", "ã", "À", "à", "Á", "á", "Â", "â", "É", "é", "È", "è", "ê", "í", "Í", "Ì", "ì", "î", "Ó", "ó", "Ò", "ò", "Õ", "õ", "Ô", "ô", "Ú", "ú", "Ù", "ù", "Ũ", "ũ", "Ç", "ç", "Ẽ", "ẽ");
    $to   = array("a", "a", "a", "a", "a", "a", "a", "a", "e", "e", "e", "e", "e", "i", "i", "i", "i", "i", "o", "o", "o", "o", "o", "o", "o", "o", "u", "u", "u", "u", "u", "u", "c", "c", "e", "e");
    //$texto = str_replace("%", "_", $texto);
    return urlencode(str_replace(" ", "_", strtolower(str_replace($from, $to, $texto))));
}

function formata_min2horas($minTime)
{
       $secs = ($minTime*60);
       $horas = intval($secs/3600);
       $secs = $secs - ($horas*3600);
       $minutos = intval($secs/60);
       $secs = $secs -($minutos*60);
       $segundos = $secs;
       if (intval($horas)>0)
            {$real = str_pad($horas, 2, "0", STR_PAD_LEFT) . "h" . str_pad($minutos, 2, "0", STR_PAD_LEFT) . "m&nbsp;&nbsp;";}
       else {$real = str_pad($minutos, 2, "0", STR_PAD_LEFT)."m&nbsp;&nbsp;";}

 return $real;
}

function hiperlink($text) {
    // match protocol://address/path/file.extension?some=variable&another=asf%
    $text = preg_replace("/([a-zA-Z]+:\/\/[a-z0-9\_\.\-]+".
    "[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%\=\,\.]+)/",
    " <a href=\"$1\" target=\"_blank\">$1</a>", $text);
    // match www.something.domain/path/file.extension?some=variable&another=asf%
    $text = preg_replace("/[^a-z]+[^:\/\/](www\.".
    "[^\.]+[\w][\.|\/][a-zA-Z0-9\/\*\-\?\&\%\=\,\.]+)/",
    " <a href=\"http://$1\" target=\"_blank\">$1</a>", $text);
    // match name@address + ?subject etc...
    $text = preg_replace(
    "/([\s|\,\>])([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-z" .
    "A-Z]*\@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})" .
    "([A-Za-z0-9\!\?\@\#\$\%\^\&\*\(\)\_\-\=\+]*)" .
    "([\s|\.|\,\<])/i",
    "$1<a href=\"mailto:$2$3\">$2</a>$4",
    $text);
    return $text;
}

function safe($unsafestring, $html=false) {
    $unsafestring = trim($unsafestring);
    $unsafestring = str_replace("'", "\'", $unsafestring);
    $unsafestring = str_replace("<?", "??", $unsafestring);
    $unsafestring = str_replace("?>", "??", $unsafestring);
    if (!get_magic_quotes_gpc()) {
        $unsafestring = addslashes($unsafestring);
    }
    /*
    if ( !$html ) return htmlentities($unsafestring);
    else return $unsafestring;
    */
    return $unsafestring;
} 

function imagemCaminho($id, $pass='') {
    $retorna = substr(md5($id.$pass), 0, 2);
    return $retorna;
}

function imagemCaminhoCompleto($id, $ficheiro, $pwd = "", $como = "HTTP") {
    $imagePathInfo  = pathinfo($ficheiro);
    if ( stripos($ficheiro, ".jpg") === false ) $imagePathInfo['extension'] = 'jpg';
    if( !is_dir( $_SERVER['DOCUMENT_ROOT'] . "/img/" . substr(md5($id.$pwd), 0, 2) . "/" ) ) {
        mkdir( $_SERVER['DOCUMENT_ROOT'] . "/img/" . substr(md5($id.$pwd), 0, 2),  0777);
    }
    $retorna = "/img/" . substr(md5($id.$pwd), 0, 2) . "/" . str_pad($id, 10, "0", STR_PAD_LEFT) . "-" . Date("YmdHis") . "." . $imagePathInfo['extension'];
    if ( $como != "HTTP" ) {
        return $_SERVER['DOCUMENT_ROOT'] . $retorna;
    }else {
        return "http://" . $_SERVER['HTTP_HOST'] . $retorna;
    }
}


/*********************************************
Description: Functions do deliver and format strings
File: /gestao/includes/funcoes.accao.php
Project: Demo
Developers: João Vieira
Start Date: 2007/06/01
*********************************************/

function js_alert($alertMessage = "Ok") {
    print "<script language=\"Javascript\">\n
<!--\n
    alert(\"" . $alertMessage . "\")\n
//-->\n
</script>\n";
}


function emailenvia($fromaddress, $toaddress, $subject, $body, $headers) {
    if (mail($toaddress, $subject, $body, "From: \"".$fromaddress."\" <$fromaddress>\n")) return true;
    else return false;
}

function create_password($length=8,$use_upper=1,$use_lower=1,$use_number=1,$use_custom=""){
    $upper          = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $lower          = "abcdefghijklmnopqrstuvwxyz";
    $number         = "0123456789";
    $seed_length    = 0;
    $seed           = '';
    $password       = '';
    if($use_upper){
        $seed_length += 26;
        $seed .= $upper;
    }
    if($use_lower){
        $seed_length += 26;
        $seed .= $lower;
    }
    if($use_number){
        $seed_length += 10;
        $seed .= $number;
    }
    if($use_custom){
        $seed_length +=strlen($use_custom);
        $seed .= $use_custom;
    }
    for($x=1;$x<=$length;$x++){
        $password .= $seed{rand(0,$seed_length-1)};
    }
    return($password);
}

function formAntiInjection($authHosts) {
	$fromArray = parse_url(strtolower($_SERVER['HTTP_REFERER']));
	$wwwUsed = strpos($fromArray['host'], "www.");
        if(!in_array(($wwwUsed === false ? $fromArray['host'] : substr(stristr($fromArray['host'], '.'), 1)), $authHosts)){ header("HTTP/1.0 403 Forbidden"); exit; }
        $badStrings = array("Content-Type:", "MIME-Version:", "Content-Transfer-Encoding:", "bcc:", "cc:");
	foreach($_POST as $k => $v)
	{ 
		foreach($badStrings as $v2)
		{ 
			if(strpos($v, $v2) !== false)
			{ 
				header("HTTP/1.0 403 Forbidden"); 
				print " * No cookie for Injection :) *";
				exit; 
			}
		}
	}
        unset($k, $v, $v2, $badStrings, $authHosts, $fromArray, $wwwUsed);        
}

function ImageResize ($fileRaw, $imageWidthNew, $fullLink) {
        
        list($imageWidth, $imageHeight, $imageType, $imageAttr) = getimagesize($fileRaw);
        $imageSource = "";
        
        $imageHeightNew = round( $imageHeight * ($imageWidthNew/$imageWidth) );
        $imageFinal=imagecreatetruecolor($imageWidthNew, $imageHeightNew)
        or die('Problems creating new image');
        
        $imageSource=ImageCreateFromJPEG($fileRaw)
        or die('Problems openning JPG file');
        
        imagecopyresampled($imageFinal, $imageSource, 0, 0, 0, 0, $imageWidthNew, $imageHeightNew, $imageWidth, $imageHeight);
        
        if ( file_exists($fullLink) ) unlink($fullLink); 
        
        imagejpeg($imageFinal, $fullLink, 100);
        
        imagedestroy($imageSource);
        imagedestroy($imageFinal);
        
}

/*********************************************
Desciption: Functions do deliver and format strings
File: /gestao/includes/funcoes.calculo.php
Project: Demo
Developers: João Vieira
Start Date: 2007/06/01
*********************************************/

function regra3s ($a, $b, $c) {
    return round((float) (($b*$c)/$a), 2);
}

function obterIdade ($ano, $mes, $dia) {
    /*
    $ageTime = mktime(0, 0, 0, $dia, $mes, $ano); // Get the person's birthday timestamp
    $t = time(); // Store current time for consistency
    $age = ($ageTime < 0) ? ( $t + ($ageTime * -1) ) : $t - $ageTime;
    $year = 60 * 60 * 24 * 365;
    $ageYears = $age / $year;
    return floor($ageYears);
    */
    return floor((time() - strtotime($ano."-".$mes."-".$dia))/(60*60*24*365.2425));
}

/*********************************************
Desciption: Functions do deliver and format strings
File: /gestao/includes/funcoes.strings.php
Project: Demo
Developers: Jo�o Vieira
Start Date: 2007/06/01
*********************************************/

function valida_email($email) {
    if( (preg_match('/(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/', $email)) || 
	    (preg_match('/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/',$email)) ) { 
	    return true;
    }
    return false;
}

function valida_url($url) {
    if (preg_match ("|^http(s)?://[a-z0-9-]+(\.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i", $url)) {
	return true;
    } else {
	return false;
    }
}

function val_str($text, $size, $name) {
    if ( strlen($text) <= $size )
        return "<br/>* Tem de preencher " . $name . " com m�nimo de " . $size . " car�cteres.";
    else
        return "";
}

function val_num($value, $size, $name) {
    if ( $value <= $size )
        return "<br/>* Tem de preencher " . $name . ".";
    else
        return "";
}

function val_day($date, $name) {
    $date_array = explode("-", $date);
    if (count($date_array)==3) {
        if ( !checkdate((int)$date_array[1], (int)$date_array[0], (int)$date_array[2]) ) { 
            return "<br/>* Tem de escolher " . $name . "";
            $date = "";
        }
    }else return "<br/>* Tem de escolher " . $name . "";
    return "";
}



?>