#!/usr/bin/perl

use Time::localtime;

BEGIN {
  # Configuraciones Iniciales :

  $NT_SERVER = 0;
  $SAVE_DIRECTORY = "/cybertesis/www/rbe/";
  $URL_SALIDA = "http://bibliotecadigital.ucn.cl/rbe/";
  $PATH_IMAGENES = "http://bibliotecadigital.ucn.cl/rbe";
  $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
}

sub envia_email {
  open(SENDMAIL, "|/usr/sbin/sendmail -t -i") or die "Cannot open $sendmail: $!";

  $sendToAddress  = $_[0];
  $myEmailAddress = $_[1];
  $subject        = $_[2];
  $mensaje        = $_[3];
  
  print SENDMAIL "To: $sendToAddress\n";
  print SENDMAIL "From: $myEmailAddress\n";
  print SENDMAIL "Subject: $subject\n";
  print SENDMAIL "$mensaje.\n";
  close (SENDMAIL);
  
  #$cabecera = 'From:'. $myEmailAddress ." \r\n";
  #$cabecera .= 'MIME-Version: 1.0' . "\r\n";
  #$cabecera .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
  #mail($sendToAddress, $subject, $mensaje, $cabecera);
}

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

  @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."/".$Filename;
    $body ="<table width='96%' cellspacing='0' cellpadding='0'>";
    $body =$body."<tr>";
    $body =$body."<td valign='top'>"; 
    $body =$body."<p align='left'>Ingreso de Archivo al servidor</p>";
    $body =$body."<p align='left'>El archivo se recibi&oacute; correctamente. La direcci&oacute;n "; 
    $body =$body."para enlazar el campo 856 es:</p>";
    $body =$body."<p align='center'>&nbsp;</p>";
    $body =$body."<p align='left'>$url_final</p>";
    $body =$body."<p>&nbsp;</p>";
    $body =$body."<p>&nbsp;</p>";
    $body =$body."<p>&nbsp;</p>";
    $body =$body."</td>";
    $body =$body."</tr>";
    $body =$body."</table>";
    $content = "Ingreso de Archivo al servidor de bibliotecadigital\n";
    $content .= "El archivo se recibio correctamente y la direccion para enlazar el campo 856 es: \n";
    $content .= $url_final;
    

    &envia_email($email,"bidocweb\@ucn.cl","Se agrego nuevo documento a Biblioteca Digital",$content);
    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>Biblioteca Digital de la Universidad Cat&oacute;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('http://bibliotecadigital.ucn.cl/archivos_historicos/images/boton_doctos2.gif','http://bibliotecadigital.ucn.cl/archivos_historicos/images/bot_map2.gif','http://bibliotecadigital.ucn.cl/archivos_historicos/images/bot_home2.gif','http://bibliotecadigital.ucn.cl/archivos_historicos/images/boton_aroba2.gif')">
<div align="center">
<!-- BANNER SUPERIOR -->
 <table border="0" width="792" id="table1" cellspacing="0" cellpadding="0" style="border: 1px solid #C0C0C0">
		
		<tr>
			<td bgcolor="#FFFFFF" width="102" height="107">
			<map name="FPMap4">
			<area href="http://www.ucn.cl" shape="circle" coords="50, 46, 46">
			</map>
			<img border="0" src="http://www.ucn.cl/imagenUCN/logo_ucn.jpg" width="100" height="95" usemap="#FPMap4"></td>
			<td bgcolor="#FFFFFF" width="296" height="107">
			<img border="0" src="http://www.ucn.cl/imagenUCN/ver_mas.jpg" width="296" height="49"><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;<img border="0" src="http://www.ucn.cl/bidoc_new/images/sist1.jpg" width="144" height="17"></td>
			<td bgcolor="#FFFFFF" height="107" width="394">
			<img border="0" src="http://www.ucn.cl/bidoc_new/images/banner2.jpg" width="394" height="110"></td>
		</tr>
		<tr>
			<td bgcolor="#FFFFFF" height="13" colspan="3" class="fondo3">
			<img border="0" src="http://www.ucn.cl/bidoc_new/images/barra1.jpg" width="792" height="13"></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 WEB BIDOC -->
			<table border="0" width="100%" id="table2" cellspacing="0" cellpadding="0">
				<tr>
					<td width="159" bgcolor="#4882B0" valign="top">
					<div align="center">
						<table border="0" width="94%" id="table3" cellspacing="7">
							<tr>
								<td>&nbsp;</td>
							</tr>
							<tr>
								<td><b> 
								<a href="http://www.ucn.cl/bidoc_new/inf_general.asp" class="blanco">Informaci&oacute;n 
								General</a></b></td>
							</tr>
							<tr>
								<td>
								<font class="blanco"><b><a href="http://www.ucn.cl/bidoc_new/servicios.asp" class="blanco">Servicios</a></b></font></td>
							</tr>
							<tr>
								<td>
								<font class="blanco"><b><a href="http://aleph.bidoc.ucn.cl/ALEPH" class="blanco">
								Cat&aacute;logo de Bibliotecas</a></b></font></td>
							</tr>
							<tr>
								<td><b><a href="http://www.ucn.cl/bidoc_new/coleccionElectronica.asp" class="blanco">Colecci&oacute;n 
								Electr&oacute;nica</a></b></td>
							</tr>
							<tr>
								<td><b><a href="http://www.ucn.cl/bidoc_new/areasTematicas.asp" class="blanco">
								&Aacute;reas Tem&aacute;ticas</a></b></td>
							</tr>
							<tr>
								<td><b><a href="http://www.ucn.cl/bidoc_new/revistas_suscritas.asp?desdePag=servicios" class="blanco">Revistas Suscritas Año 2008</a></b></td>
							</tr>
							<tr>
								<td><b><a href="http://www.ucn.cl/bidoc_new/PEI.asp" class="blanco">Programa 
								de Educaci&oacute;n en Informaci&oacute;n (PEI)</a></b></td>
							</tr>
							<tr>
								<td><b><a href="http://www.ucn.cl/bidoc_new/cybertesis.asp" class="blanco">Cybertesis</a></b></td>
							</tr>
							<tr>
								<td><b><a href="http://bibliotecadigital.ucn.cl/archivos_historicos/" class="blanco">Archivos Hist&oacute;ricos</a></b></td>
							</tr>
							<tr>
								<td><b><a href="http://www.ucn.cl/bidoc_new/sitiosRecomendados.asp" class="blanco">Sitios 
								Recomendados</a></b></td>
							</tr>
							<tr>
								<td><b><a href="http://www.ucn.cl/bidoc_new/manuales.asp" class="blanco">Manuales</a></b></td>
							</tr>
							<tr>
								<td>&nbsp;</td>
							</tr>
						</table>
						<p>
					<map name="sitios">
					<area target="_blank" href="http://www.alerta.cl/" shape="polygon" coords="96, 117, 77, 117, 74, 113, 71, 112, 68, 112, 69, 107, 53, 107, 53, 144, 63, 144, 67, 137, 92, 137, 92, 124, 98, 125">
					<area target="_blank" href="http://isiknowledge.com" shape="rect" coords="38, 52, 105, 86">
					</map>
					<img border="0" src="http://www.ucn.cl/bidoc_new/images/logos.jpg" width="158" height="156" usemap="#sitios"></div>
<!-- FIN DE MENU WEB BIDOC --> </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&aacute;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; <span class="isHere">Informaci&oacute;n de URL para campo 856</span></td>
      </tr>
    </table>
    <br>
        $body

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