<?php
/*********************************************
Description: Functions do deliver and format strings
File: /gestao/includes/funcoes.formatacao.php
Project: Basikus
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 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) {
    $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 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 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 uri_in($uQ){
    if ( strpos($_SERVER['REQUEST_URI'], $uQ) !== false ) return true;
    else return false;
}

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 false;
    else
        return true;
}

function val_num($value, $size, $name) {
    if ( $value <= $size )
        return false;
    else
        return true;
}

function val_dia($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 "";
}

?>