#!/usr/bin/perl

use Time::localtime;

BEGIN {
	# Configuraciones Iniciales :

	$NT_SERVER = 0;
	$SAVE_DIRECTORY = "/cybertesis/www/archivos_historicos/documentos/";
	$URL_SALIDA = "http://bibliotecadigital.ucn.cl/archivos_historicos/documentos/";
	$PATH_IMAGENES = "http://bibliotecadigital.ucn.cl/archivos_historicos";
	$MAXIMUM_UPLOAD = 0;
	$ALLOW_INDEX = 0;
	$SUCCESS_LOCATION = "";

$ano=localtime->year(); 	# Año menos 1900
$ano=$ano+1900;			# Año corregido
$mes=localtime->mon();		# Mes menos 1
#$mes++;				# Mes corregido
$fecha=localtime->mday();	# Dia del mes
#$diasem=localtime->wday();	# Dia de la semana (Viernes = 5)
$hora=localtime->hour();	# Hora de 0 - 23
$minutos=localtime->min();	# Minutos 0 - 59

}

	$| = 1;
	chop $SAVE_DIRECTORY if ($SAVE_DIRECTORY =~ /\/$/);
	use CGI qw(:standard);
	$query = new CGI;
	$subcarpeta = $query->param("coleccion");
	$SAVE_DIRECTORY = $SAVE_DIRECTORY."/".$subcarpeta."/archivos";

@finales = (31,28,31,30,31,30,31,31,30,31,30,31);
if ($year%4 == 0){
	$finales[1]++;
}
$fecha += 7;
if ($finales[$mes] < $fecha){
	$fecha -= $finales[$mes];
	$mes++;
	if ($mes > 11){
		$ano++;
		$mes = 0;
	}
}
$prefijo = $ano.$mes.$fecha;
$prefijo .="-".$hora.$minutos;
$nombrearchivo="";
$thumbail="";
$detalle="";

	if ( (!(-e $SAVE_DIRECTORY)) ||
		 (!(-W $SAVE_DIRECTORY)) ||
		 (!(-d $SAVE_DIRECTORY)) ) {
		print header;
		print <<__END_OF_HTML_CODE__;
		
		<HTML>
		<HEAD>
			<TITLE>Error: Bad Directory</TITLE>
		</HEAD>
		<BODY BGCOLOR="#FFFFFF">
		<H1>Bad Directory</H1>
		<P>
		The directory you specified:
		<BR>
		<BLOCKQUOTE>
			<TT>\$SAVE_DIRECTORY = "<B>$SAVE_DIRECTORY</B>";</TT>
		</BLOCKQUOTE>
		<BR> is invalid.  This problem is caused by one of the three following reasons:
		<OL>
			<LI>The directory doesn't exist.  Make sure that this directory is a complete path name, not a URL or something similar.  It should look similar to <TT>/home/username/public_html/uploads</TT>
			<P>
			<LI>The directory isn't writable.  Make sure that this directory is writable by all users.  At your UNIX command prompt, type <TT>chmod 777 $SAVE_DIRECTORY</TT>
			<P>
			<LI>The directory you specified isn't really a directory.  Make sure that this is indeed a directory and not a file.
		</OL>
		<HR SIZE=1>
		</BODY>
		</HTML>
		
__END_OF_HTML_CODE__
		exit;
	}
	
	foreach $key (sort {$a <=> $b} $query->param()) {
               
		next if ($key =~ /^\s*$/);
		next if ($query->param($key) =~ /^\s*$/);
		if ($key !~ /^file-to-upload-(\d+)$/){
			$aux = '$'.$key;
			$aux2 = $query->param($key);
			eval "$aux = '$aux2';";
		}
		else{
		$Number = $1;
		
		if ($query->param($key) =~ /([^\/\\]+)$/) {
			$Filename = $1;
			$Filename =~ s/^\.+//;
			$Filename = $prefijo.$Filename;

			$Filename =~ tr/\n, ¿?¡!\@\;\:\"\'\`\|\\\/\+\*\~\^\[\]\{\}\(\)\=\&\%\$\#//d;
			$Filename =~ tr/áéíóúñÑäëïöüàèìòùâêîôû/aeiounNaeiouaeiouaeiou/;
			$Filename =~ tr/ÁÉÍÓÚÄËÏÖÜÀÈÌÒÙÂÊÎÔÛ/AEIOUAEIOUAEIOUAEIOU/;
			$Filename =~ tr/A-Z/a-z/;


			$File_Handle = $query->param($key);
			
			if (!$ALLOW_INDEX && $Filename =~ /^index/i) {
				print header;
				print <<__END_OF_HTML_CODE__;
				
				<HTML>
				<HEAD>
					<TITLE>Error: Filename Problem</TITLE>
				</HEAD>
				<BODY BGCOLOR="#FFFFFF">
				<H1>Filename Problem</H1>
				<P>
				You attempted to upload a file that isn't properly formatted.  The system administrator has decided that you can't upload files that begin with the word '<B>index</B>'. Please rename the file on your computer, and try uploading it again.
				<P>
				</BODY>
				</HTML>
	
__END_OF_HTML_CODE__
				exit;
			}
		} else {
			$FILENAME_IN_QUESTION = $query->param($key);
		
			print header;
			print <<__END_OF_HTML_CODE__;
			
			<HTML>
			<HEAD>
				<TITLE>Error: Filename Problem</TITLE>
			</HEAD>
			<BODY BGCOLOR="#FFFFFF">
			<H1>Filename Problem</H1>
			<P>
			You attempted to upload a file that isn't properly formatted.  The file in question is <TT><B>$FILENAME_IN_QUESTION</B></TT>  Please rename the file on your computer, and attempt to upload it again.  Files may not have forward or backward slashes in their names.  Also, they may not be prefixed with one (or more) periods.
			<P>
			<HR SIZE=1>
			</BODY>
			</HTML>

__END_OF_HTML_CODE__
			exit;
		}
		
        if (!open(OUTFILE, ">$SAVE_DIRECTORY\/$Filename")) {
            print "Content-type: text/plain\n\n";
            print "-------------------------\n";
            print "Error:\n";
            print "-------------------------\n";
            print "File: $SAVE_DIRECTORY\/$Filename\n";
            print "-------------------------\n";
	        print "There was an error opening the Output File\n";
    	    print "for Writing.\n\n";
        	print "Make sure that the directory:\n";
	        print "$SAVE_DIRECTORY\n";
    	    print "has been chmodded with the permissions '777'.\n\n";
        	print "Also, make sure that if your attempting\n";
	        print "to overwrite an existing file, that the\n";
    	    print "existing file is chmodded '666' or better.\n\n";
	        print "The Error message below should help you diagnose\n";
    	    print "the problem.\n\n";
        	print "Error: $!\n";
            exit;
        }
		
if ($NT_SERVER) {
	 binmode(OUTFILE); }
	    {   next;

}
		undef $BytesRead;
		undef $Buffer;
		
        while ($Bytes = read($File_Handle,$Buffer,1024)) {
			$BytesRead += $Bytes;
            print OUTFILE $Buffer;
        }
		
		push(@Files_Written, "$SAVE_DIRECTORY\/$Filename");
		$TOTAL_BYTES += $BytesRead;
		$Confirmation{$File_Handle} = $BytesRead;

        close($File_Handle);
		close(OUTFILE);

        chmod (0666, "$SAVE_DIRECTORY\/$Filename");
    }
	}

	$FILES_UPLOADED = scalar(keys(%Confirmation));

	
	if ($TOTAL_BYTES > $MAXIMUM_UPLOAD && $MAXIMUM_UPLOAD > 0) {
		foreach $File (@Files_Written) {
			unlink $File;
		}
		
		print header;
		print <<__END_OF_HTML_CODE__;
		
		<HTML>
		<HEAD>
			<TITLE>Error: Limit Reached</TITLE>
		</HEAD>
		<BODY BGCOLOR="#FFFFFF">
		<H1>Limit Reached</H1>
		<P>
		You have reached your upload limit.  You attempted to upload <B>$FILES_UPLOADED</B> files, totalling <B>$TOTAL_BYTES</B>.  This exceeds the maximum limit of <B>$MAXIMUM_UPLOAD</B> bytes, set by the system administrator.  <B>None</B> of your files were successfully saved.  Please try again.
		<P>
		<HR SIZE=1>
		</BODY>
		</HTML>
				
__END_OF_HTML_CODE__
		exit;
	}
	
	if ($SUCCESS_LOCATION !~ /^\s*$/) {
		print $query->redirect($SUCCESS_LOCATION);
	} else {
		$url_final = $URL_SALIDA.$subcarpeta."/archivos/".$Filename;
		print header;
		print <<__END_OF_HTML_CODE__;
<html>
<head>
<link href="http://www.ucn.cl/sec/estilo_wwwtmp.css" rel="stylesheet" type="text/css">
<link href="http://www.ucn.cl/bidoc_new/include/estilo.css" rel="stylesheet" type="text/css">
<title>Archivos Históricos de la Universidad Católica el Norte</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language="JavaScript">
<!--
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//-->
</script>
</head>

<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onLoad="MM_preloadImages('../images/boton_doctos2.gif','../images/bot_map2.gif','../images/bot_home2.gif','../images/boton_aroba2.gif')">
<div align="center">
<!-- BANNER SUPERIOR -->
<table width="792" id="table1" cellspacing=" 0" cellpadding="0" style="border: 1px solid #C0C0C0">                                                                                                                                                                                                                            
  <tr>                                                                                                                                                                                                                                                                           
    <td colspan="2" valign="top">                                                                                                                                                                                                                                                
      <table border="0" cellpadding="0" cellspacing="0" width="100%">                                                                                                                                                  
        <tbody>                                                                                                                                                                                                                                                                  
        <tr>                                                                                                                                                                                                                                                                     
          <td bgcolor="#FFFFFF" height="3" width="90" valign="top">                                                                                                                                                                                                              
            <div align="left"><a href="http://www.ucn.cl/" target="_blank">
				<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/logo_ucn.jpg" usemap="#FPMap4" border="0" height="85" width="89" alt="Universidad Cat&oacute;lica del Norte"></a></div>                                                              
          </td>                                                                                                                                                                                                                                                                  
          <td height="3" width="912" bgcolor="#FFFFFF" align="center">                                                                                                                                                                                                                                            
            <img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/ver_mas.jpg" width="327" height="73"><a href="http://www.ucn.cl/" target="_blank"><br></a>
          </td>                                                                                                                                                                                                                                                                  
          <td bgcolor="#FFFFFF" height="3" valign="top" width="320">                                                                                                                                                                                                             
            <div align="right">
				<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/banner2.jpg" border="0" height="85" width="319"></div>                                                                                                                                                                           
          </td>                                                                                                                                                                                                                                                                  
        </tr>                                                                                                                                                                                                                                                                    
        <tr bgcolor="#5089B6">                                                                                                                                                                                                                                                   
          <td colspan="3" height="2">                                                                                                                                                                                                                                            
            <div align="left">
				<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/barra1.jpg" border="0" height="13" width="760"></div>                                                                                                                                                                             
          </td>                                                                                                                                                                                                                                                                  
        </tr>                                                                                                                                                                                                                                                                    
        <tr bgcolor="#E7E7B6">                                                                                                                                                                                                                                                   
          <td colspan="3" height="2">                                                                                                                                                                                                                                            
            <table width="100%" border="0" cellspacing="0" cellpadding="0">                                                                                                                                                                                                      
              <tr>                                                                                                                                                                                                                                                               
                <td>                                                                                                                                                                                                                                                             
                  <div align="right"><b>
					<a href="http://bibliotecadigital.ucn.cl/archivos_historicos/documentos/default.asp" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image1','','/archivos_historicos/images/boton_doctos2.gif',1)">
					<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/boton_doctos1.gif" width="181" height="16" border="0" name="Image1"></a></b></div>
                </td>                                                                                                                                                                                                                                                            
                <td>                                                                                                                                                                                                                                                             
                  <table width="97" border="0" cellspacing="0" cellpadding="0" align="right">                                                                                                                                                                                    
                    <tr>                                                                                                                                                                                                                                                         
                      <td>                                                                                                                                                                                                                                                       
                        <div align="center"><a href="javascript:;" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image2','','/archivos_historicos/images/bot_map2.gif',1)">
							<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bot_map1.gif" width="42" height="14" border="0" name="Image2"></a></div>                    
                      </td>                                                                                                                                                                                                                                                      
                      <td>                                                                                                                                                                                                                                                       
                        <div align="center">
							<a href="http://bibliotecadigital.ucn.cl/archivos_historicos/default.asp" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image3','','/archivos_historicos/images/bot_home2.gif',1)">
							<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bot_home1.gif" width="27" height="14" border="0" name="Image3"></a></div>                     
                      </td>                                                                                                                                                                                                                                                      
                      <td>                                                                                                                                                                                                                                                       
                        <div align="center"><a href="javascript:;" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image4','','/archivos_historicos/images/boton_aroba2.gif',1)">
							<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/boton_aroba1.gif" width="28" height="14" border="0" name="Image4"></a></div>            
                      </td>                                                                                                                                                                                                                                                      
                    </tr>                                                                                                                                                                                                                                                        
                  </table>                                                                                                                                                                                                                                                       
                </td>                                                                                                                                                                                                                                                            
              </tr>                                                                                                                                                                                                                                                              
            </table>                                                                                                                                                                                                                                                             
          </td>                                                                                                                                                                                                                                                                  
        </tr>                                                                                                                                                                                                                                                                    
        </tbody>                                                                                                                                                                                                                                                                 
      </table>                                                                                                                                                                                                                                                                   
    </td>                                                                                                                                                                                                                                                                        
  </tr>                                                                                                                                                                                                                                                                          
</table>
<!-- FIN BANNER SUPERIOR -->
<table width="792" id="table1" cellspacing=" 0" cellpadding="0" style="border: 1px solid #C0C0C0">
  <tr>                                                             
    <td width="10%" valign="top" bgcolor="6087CF">     
<!-- MENU DE ARCHIVOS HISTORICOS -->
      <table width="150" cellspacing="5" cellpadding="2" id="table3">                                                                                                                                                             
        <tr>                                                                                                                                                                                                          
          <td width="144">
			<a href="http://bibliotecadigital.ucn.cl/archivos_historicos/acerca.asp" class="blanco">
          	<b>Acerca</b> 
            <img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bulet.gif" width="2" height="5" border="0">                                                                                                         
            </a>
          </td>                                                                                                                                                                                                
        </tr>                                                                                                                                                                                                         
        <tr>                                                                                                                                                                                                          
          <td width="144">
          <a href="http://bibliotecadigital.ucn.cl/archivos_historicos/Chacabuco/default.asp" class="blanco">
          <b>Oficina Salitrera Chacabuco</b> 
          <img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bulet.gif" width="2" height="5" border="0"></a>
          </td>                                                                                                                                               
        </tr>                                                                                                                                                                                                         
        <tr>                                                                                                                                                                                                          
          <td width="144">
            <a href="http://bibliotecadigital.ucn.cl/archivos_historicos/flor_de_chile/flordechile.asp" class="blanco">
            <b>Oficina Salitrera Flor de Chile</b>
            <img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bulet.gif" width="2" height="5" border="0">
            </a>
          </td>                                                                                                                                                                                                 
        </tr>                                                                                                                                                                                                         
        <tr>                                                                                                                                                                                                          
          <td width="144">
          	<a href="http://bibliotecadigital.ucn.cl/archivos_historicos/capitania_mejillones/mejillones-capitania-pto.asp" class="blanco">
          	<b>Capitanía de Puerto de Mejillones</b> 
          	<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bulet.gif" width="2" height="5" border="0">
            </a>
           </td>
        </tr>                                                                                                                                                                                                         
        <tr>                                                                                                                                                                                                          
          <td width="144">
          	<a href="http://bibliotecadigital.ucn.cl/archivos_historicos/aduana_mejillones/mejillones-aduana.asp" class="blanco">
          	<b>Aduana de Mejillones</b> 
          	<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bulet.gif" width="2" height="5" border="0"></a>
          </td>
        </tr>                                                                                                                                                                                                         
        <tr>                                                                                                                                                                                                          
          <td width="144">
          	<a href="http://bibliotecadigital.ucn.cl/archivos_historicos/subdelegacion_mejillones/mejillones-subdel-civil.asp" class="blanco">
          	<b>Subdelegación Civil de Mejillones</b> 
          	<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bulet.gif" width="2" height="5" border="0"></a>
          </td>                                                                                                                                               
        </tr>                                                                                                                                                                                                         
        <tr>                                                                                                                                                                                                          
          <td width="144">
          	<a href="http://bibliotecadigital.ucn.cl/archivos_historicos/juzgado_mejillones/mejillones-juzgadocivil.asp" class="blanco">
          	<b>Juzgado Civil de Mejillones</b> 
          	<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bulet.gif" width="2" height="5" border="0"></a>
          </td>                                                                                                                                               
        </tr>                                                                                                                                                                                                         
        <tr>                                                                                                                                                                                                          
          <td width="144" valign="top">
          	<a href="http://bibliotecadigital.ucn.cl/archivos_historicos/aduana_antofagasta/antofagasta-aduana.asp" class="blanco">
          	<b>Aduana de<br>Antofagasta</b> 
            <img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bulet.gif" width="2" height="5" border="0"></a>
          </td>                                                                                                                                                                                                       
        </tr>                                                                                                                                                                                                         
        <tr>                                                                                                                                                                                                          
          <td width="144">
          	<a href="http://bibliotecadigital.ucn.cl/archivos_historicos/antogagasta_extranjeria/antofagasta-extranjeria.asp" class="blanco">
          	<b>Extranjería del Registro Civil e Identificación de Antofagasta</b> 
          	<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bulet.gif" width="2" height="5" border="0"></a>
          </td>
        </tr>                                                                                                                                                                                                         
        <tr>                                                                                                                                                                                                          
          <td width="144">
          	<a href="http://bibliotecadigital.ucn.cl/archivos_historicos/prosperidad/prosperidad.asp" class="blanco">
          	<b>Oficina Salitrera Prosperidad</b> 
          	<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bulet.gif" width="2" height="5" border="0"></a>
          </td>
        </tr>                                                                                                                                                                                                         
        <tr>                                                                                                                                                                                                          
          <td width="144">
          	<a href="http://bibliotecadigital.ucn.cl/archivos_historicos/antofagasta_intendencia/antofagasta-intendencia.asp" class="blanco">
          	<b>Intendencia de Antofagasta</b> 
          	<img src="http://bibliotecadigital.ucn.cl/archivos_historicos/images/bulet.gif" width="2" height="5" border="0"></a>
          </td>                                                                                                                                                                                                 
        </tr>                                                                                                                                                                                                         
      </table>
<!-- FIN DE MENU DE ARCHIVOS HISTORICOS -->	</td>
    <td width="90%" valign="top" bgcolor="#FFFFFF"> <br>
		<table border="0" cellpadding="0" width="100%" id="table4" cellspacing="0">
			<tr>
				<td height="20" colspan="3" class="roadmapCell">
				&nbsp;<b>Estás en:</b>&nbsp;&nbsp;&nbsp;&nbsp;<a class="roadmap" href="http://www.ucn.cl">UCN</a> 
				&gt; <a class="roadmap" href="http://www.ucn.cl/bidoc_new/default.asp">
				Sistema de Bibliotecas</a> &gt; <a class="roadmap" href="../default.asp">
				Archivos Históricos</a> &gt; <span class="isHere">Información de URL para campo 856</span></td>
			</tr>
		</table>
		<br>
      <table width="96%" cellspacing="0" cellpadding="0">
        <tr> 
          <td valign="top"> 
            <p class="tituloPag" align="center">Ingreso de im&aacute;genes al 
              servidor</p>
            <p align="center">El archivo se recibi&oacute; correctamente. La direcci&oacute;n 
              para enlazar el campo 856 es:</p>
            <p align="center">&nbsp;</p>
            <p align="left">$url_final</p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
            <p>&nbsp;</p>
          </td>
        </tr>
      </table>


      </td>
  </tr>
</table>
</div>
</body>
</html>
__END_OF_HTML_CODE__
	#	exit;	
	}
	
# ---------------------------------------------------------------------
# EOF
