<?

# Get a remote file size
function cut_str($msg,$cut_size) {
                if($cut_size<=0) return $msg;
                if(ereg("\[re\]",$msg)) $cut_size=$cut_size+4;
                for($i=0;$i<$cut_size;$i++) if(ord($msg[$i])>127) $han++; else $eng++;
                $cut_size=$cut_size+(int)$han*0.6;
                $point=1;
                for ($i=0;$i<strlen($msg);$i++) {
                        if ($point>$cut_size) return $pointtmp."¡¦";
                        if (ord($msg[$i])<=127) {
                                $pointtmp.= $msg[$i];
                                if ($point%$cut_size==0) return $pointtmp."¡¦"; 
                        } else {
                                if ($point%$cut_size==0) return $pointtmp."¡¦";
                                $pointtmp.=$msg[$i].$msg[++$i];
                                $point++;
                        }
                        $point++;
                }
                return $pointtmp;
        }

function get_remote_size($u){
	$ourhead = "";
	$url=parse_url($u); 
	$host=$url["host"]; 
	$path=$url["path"]; 

	$fp = fsockopen($host, 80, &$errno, &$errstr, 20); 
	if(!$fp) { 
	    echo("error"); 
	    exit (); 
	} else { 
	    fputs($fp,"HEAD $u HTTP/1.1\r\n"); 
	    fputs($fp,"HOST: dummy\r\n"); 
	    fputs($fp,"Connection: close\r\n\r\n"); 

	    while (!feof($fp)) { 
	        $ourhead = sprintf("%s%s", $ourhead, fgets ($fp,128)); 
	    }
	} 
	fclose ($fp);

	$split_head = explode("Content-Length: ",$ourhead);
	$size = abs($split_head[1]);
	return $size;
}

# Grava Log

function grava_log($arq,$x,$path = "/var/log"){
     
       $agora = date("d/m/Y H:i:s");
       $x= "$agora # ".$x."\n";

       $fp = fopen("$path/$arq","a");
       fwrite($fp,$x);
       fclose($fp);
}

# Inicia as preferencias do usuario
# linguagem, etc.

function init_prefs(){
    GLOBAL $language,$TEXT;
    include "languages/$language.txt";
}


# Gera semente aleat?ria

function make_seed() {
    list($usec, $sec) = explode(" ", microtime());
    return (float) $sec + ((float) $usec * 100000);
}


# Gera numero aleat?rio

function gera_rand(){
    $chave = "";
    for ($x=0;$x<16;$x++){
        $letra = rand(65,90);
        $chave=$chave.chr($letra);
    }
    return $chave;
}


# Exclui recursivamente um diretorio
# currentDir: Diretorio atual
# connection: handle da Conexao FTP
# file: diretorio a ser excluido

function del_recursive($currentDir,$connection,$file){
    //echo "entering $currentDir/$file<BR>";
    if ($lista = @ftp_nlist($connection, "$file")){
        for ($x=0;$x<count($lista);$x++){
            //echo "tryng to delete $lista[$x]<BR>";
            if (!@ftp_delete($connection, "$lista[$x]"))
                del_recursive($currentDir,$connection,$lista[$x]);
        }
        @ftp_rmdir($connection, "$file");
    }
}


# Verifica se um arquivo/diretorio pode ser eliminado
# file: arquivo
# retorna: TRUE,FALSE

function CanDel($file){
    GLOBAL $dont_delete;
    $dont = $dont_delete;

    while(list($a,$b) = each($dont)){
        if ($b == $file)
            return FALSE;
    }
    return TRUE;
}


# Verifica se um arquivo/diretorio pode ser mostrado
# file: arquivo
# retorna: TRUE,False

function CanShow($file){
    GLOBAL $hide_files;
    $hide = $hide_files;

    while(list($a,$b) = each($hide)){
        if ($b == $file)
            return FALSE;
        if (strpos($b,"*"))
            if (substr($file,0,strlen($b)-1) == str_replace("*","",$b) )
                return FALSE;

    }
    return TRUE;
}


# Verifica se um arquivo ? texto pode ser editado
# ext: Extensao
# server: servidor de conexao
# currentDir: diretorio atual
# file: Arquivo
# retorna: true,false

function CanEdit($ext,$server,$currentDir,$file){
    GLOBAL $ascii_array, $enable_localhost_commands, $statCommand, $root_dir, $user;
    $asc = $ascii_array;

    //Escolher se: 1)deve fazer a verifica?ao por comando, ou 2) por extensao conhecida
    if ($server == "localhost" && $enable_localhost_commands){
        //Verificar se est? usando chroot no ftp.
        if ($root_dir <> "" && substr($currentDir,0,strlen($root_dir)) <> $root_dir)
            $true_path = $root_dir."/".$user.$currentDir."/".$file;
        else
            $true_path = $currentDir."/".$file;

        if (exec("$statCommand $true_path|grep text") != "")
            return TRUE;
    }
    else{
        while(list($a,$b) = each($asc)){
            if ($b == $ext)
                return TRUE;
        }
    }
    return FALSE;
}


# Modifica as permissoes de um arquivo no ftp
# connection: handle da conexao de ftp
# permissions: novas permissoes do arquivo
# file: arquivo
# retorna: TRUE,FALSE.

function f_chmod($connection,$permissions,$file){
    if(@ftp_site($connection, "chmod $permissions $file"))
    {
        return TRUE;
    } else {
        return FALSE;
    }

}


# Muda de diretorio no ftp
# connection: handle da conexao de ftp
# currentDir: diretorio atual
# file: novo diretorio
# return: Diretorio Atual

function f_chdir($connection,$currentDir,$file){

    //se for diretorio normal
    if(@ftp_chdir($connection, $currentDir . "/" . $file))
	{
        $currentDir = @ftp_pwd($connection);
		return $currentDir;
	}
	
    //Se for link par aum diretorio
	elseif(@ftp_chdir($connection, $file))
    {
        $currentDir = @ftp_pwd($connection);
		return $currentDir;
	}
	
    //Se for link para um arquivo, fazer download
    else
    {
        header("Content-disposition: attachment; filename=\"$file\"");
		header("Content-type: application/octetstream");
		header("Pragma: ");
		header("Cache-Control: cache");
		header("Expires: 0");

		//Determine original filename
		$filearray = explode("/",$file);
		$file = $filearray[sizeof($filearray)-1];

		$fp = fopen($downloadDir . $file, "w");
		if(!@ftp_fget($connection,$fp,"$file",$mode))
		{
            fclose($fp);
		    exit;
		}
		fclose($fp);
		$data = readfile($downloadDir . $file);
		$i=0;
		while ($data[$i] != ""){
            echo $data[$i];
		    $i++;
		}
		unlink($downloadDir . $file);
		exit;
    }

    return $currentDir;
}


# Faz o download direto de uma url para o FTP.
# file: url a ser recuperada
# connection: handle da conexao de ftp
# currentDir: Diretorio atual
# mode: modo de transferencia: 0 ASC,1 Binary
# retorna: mensagem

function f_directDownload($file,$currentDir,$connection,$mode){
	GLOBAL $size_restriction,$TEXT;

	if(substr($file,0,7) != "http://" && substr($file,0,6) != "ftp://"){
		$msg = $TEXT['invalidprotocol'];
		return $msg;
	}

	$f = explode("/",str_replace("http://","",$file));
	$filename = $f[count($f)-1];

	//$filename = str_replace("..",".",$filename);
	$filename = urlencode($filename);

	if ($filename == "")
		$filename = "download_".date("YmdHis").".fil";

	$size = get_remote_size($file);
	$rsize = round(abs($size)/1024);

	if ($size >= $size_restriction){
		$msg = $TEXT['toobig']." :($rsize KB)";
		return $msg;
	}
	
        $fp = @fopen($file, "r");

        if (ftp_fput($connection, $currentDir."/".$filename, $fp, $mode))
		$msg = $filename." ".$TEXT['downloaded']." :($rsize KB)";
	else
		$msg = $filename." ".$TEXT['error']."!";
        fclose($fp);

	return $msg;
}


# Donwload de um arquivo via ftp
# connection: handle de conexao ftp
# donwloadDir: Diretorio temporario
# file: arquivo
# Modo: 0 ASC, 1 BIN

function f_down($connection,$downloadDir,$file,$mode){
    GLOBAL $TEXT;
    header("Content-disposition: attachment; filename=\"$file\"");
	header("Content-type: application/octetstream");
	header("Pragma: ");
	header("Cache-Control: cache");
	header("Expires: 0");

	$fp = fopen($downloadDir . $file, "w");
	ftp_fget($connection,$fp,"$file",$mode) OR DIE($TEXT['errordownloading']);
	fclose($fp);
	$data = readfile($downloadDir . $file);
	$i=0;
	while ($data[$i] != ""){
	      echo $data[$i];
	      $i++;
	}
	unlink($downloadDir . $file);
	exit;
}


# Upload de arquivo via ftp

function f_upl($connection,$currentDir,$file_size,$MAX_FILE_SIZE,$mode,$HTTP_POST_FILES){
    GLOBAL $TEXT;
    
    if($file_size > $MAX_FILE_SIZE){
        $msg = "<B>".$TEXT['toobig']."</B> (max. " . $MAX_FILE_SIZE . "bytes)<P>";
    }
	else{
        if(file_exists($HTTP_POST_FILES['file']['tmp_name'])){
            if ($mode==1){
                ftp_put($connection, $currentDir . "/" . $HTTP_POST_FILES['file']['name'], $HTTP_POST_FILES['file']['tmp_name'], 1);
            }
			else{
		        ftp_put($connection, $currentDir . "/" . $HTTP_POST_FILES['file']['name'], $HTTP_POST_FILES['file']['tmp_name'], 0);
		        
            }
			unlink($HTTP_POST_FILES['file']['tmp_name']);
			$file = $HTTP_POST_FILES['file']['name'];
			ftp_site($connection,"chmod 755 $file");
        }
		else{
            $msg = $TEXT['cantupload'];
		}
	}

    return $msg;
}


# Remover um diretorio no FTP

function f_deldir($connection,$file,$currentDir){
  GLOBAL $TEXT;
  
  if (CanDel($file)){
    if(@ftp_rmdir($connection, "$file")){
        $msg = $file." ".$TEXT['deleted'];
    }
    else
    {
        //Verify if has files inside and if so, call recursive del
	if ($lista = @ftp_nlist($connection, "$currentDir/$file")){
        	del_recursive($currentDir,$connection,$file);
		$msg = $currentDir."/".$file." ".$TEXT['deleted'];
	}
	else $msg = $TEXT['cantdelete'].": ".$file;
    }
  }else $msg = $TEXT['notalloweddelete'].": ".$file;
  return $msg;
}


# Remover um arquivo no ftp

function f_delfile($connection,$file){
    GLOBAL $TEXT;

    if (CanDel($file)){
        if(@ftp_delete($connection, "$file"))
        {
            $msg = $file." ".$TEXT['deleted'];
        }
	    else
        {
            $msg = $TEXT['cantdelete'].": ".$file;
        }
     }
     return $msg;
}	


# renomear um arquivo ou diretorio no ftp

function f_rename($connection,$file,$file2){
    GLOBAL $TEXT;
    
    if(@ftp_rename($connection, "$file", "$file2"))
	{
        $msg = $file." ".$TEXT['renamedto']." ".$file2;
	}
	else
	{
        $msg = $TEXT['cantrenameto']." ".$file2;
	}
	return $msg;
}


# Criar um diretorio no ftp

function f_createdir($connection,$file){
    GLOBAL $TEXT;
    
    $file = str_replace("'", "", $file);
    $file = str_replace("\\", "", $file);
    if(@ftp_mkdir($connection, "$file"))
	{
        $msg = $file." ".$TEXT['created'];
        ftp_site($connection,"chmod 755 $file");
	}
	else
	{
        $msg = $TEXT['cantcreate'].": ".$file;
	}
	return $msg;

}


# Descompactar um arquivo zip no ftp

function f_unzipfile($file,$currentDir){
    GLOBAL $unzipCommand,$user,$root_dir,$TEXT;

    $filens = str_replace(" ","\\ ",$file);
	$filens = str_replace("&","",$filens);
	$filens = str_replace("|","",$filens);
	$filens = str_replace("`","",$filens);


    //if we are chrooted
    if ($root_dir <> "" && substr($currentDir,0,strlen($root_dir)) <> $root_dir)
       $true_path = $root_dir."/".$user.$currentDir;
    else
        $true_path = $currentDir;

    if (exec("$unzipCommand $true_path/$filens -d $true_path/"))
        $msg = $file." ".$TEXT['unziped'];
    else
        $msg = $TEXT['cantunzip'].": $file";

    //chmod??
    return $msg;
}

?>
