#!/usr/bin/perl

require 'common.pl';
use strict;
use CGI;

sub main($)
{
  my ($dbh) = @_;
  my $q = new CGI;
  my $buf = undef;

  if( $ENV{'REQUEST_METHOD'} ne 'POST' )
  {
    mysql_log($dbh, $q, 'Wrong request method');
    print('Location: '.$::base_url."\n\n");
    return( 0 );
  }

  if( !$q->param('f') )
  {
    mysql_log($dbh, $q, 'No File');
    print('Location: '.$::base_url."\n\n");
    return( 0 );
  }

  my $filename = $q->param('f');
  if( $filename !~ /^[\d\w][\d\w\_\.\,-]+[\d\w]$/ )
  {
    mysql_log($dbh, $q, 'Illegal File');
    print('Location: '.$::base_url."\n\n");
    return( 0 );
  }
  $filename = $::file_pool.'/'.$filename;
  if( !-f($filename) || !-r($filename) )
  {
    mysql_log($dbh, $q, 'File not found');
    print('Location: '.$::base_url."\n\n");
    return( 0 );
  }

  if( !allowDownload($dbh, $q) )
  {
    mysql_log($dbh, $q, 'Authentication failed');
    print('Location: '.$::base_url."\n\n");
    return( 0 );
  }

  my $filesize = -s($filename);
  if( !open(FILE, $filename) )
  {
    mysql_log($dbh, $q, 'File read error');
    print('Location: '.$::base_url."\n\n");
    return( 0 );
  }
  print($q->header(-type => 'application/octet-stream',
                   -attachment => $q->param('f')));
  my $fpos = 0;
  my $read_bytes = undef;
  do
  {
    $read_bytes = read(FILE, $buf, 65536, $fpos);
#    $fpos += $read_bytes;
    if( $read_bytes )
    {
      print($buf);
    }
  }
  while( $read_bytes );
  close(FILE);

  mysql_log($dbh, $q, 'File download complete');

  # Stats
  my ($old_user) = mysql_hashrows('SELECT stats WHERE File = ? AND User = ?', $filesize, $q->param('f'), decode_base64($q->param('u')));
  if( $old_user )
  {
    $dbh->do('UPDATE stats SET Count = Count + 1, Size = Size + ?, LastAccess = NOW() WHERE File = ? AND User = ?', undef, $filesize, $q->param('f'), decode_base64($q->param('u')));
  }
  else
  {
    $dbh->do('INSERT INTO stats (File, User, Count, Size, FirstAccess, LastAccess) VALUES (?, ?, 1, ?, NOW(), NOW())', undef, $q->param('f'), decode_base64($q->param('u')), $filesize);
  }

  # Fertig
  return( 0 );
}

# Logging

my $dbh;
if( $dbh = mysql_connect() )
{
  main($dbh);
  mysql_disconnect($dbh);
}

exit( 0 );
