#!/usr/bin/perl
 
########## Confixx(R) 3.0 Professional ############
####### Copyright SWsoft, Inc. 2004-2005 ##########
#### http://www.sw-soft.com - info@sw-soft.com ####


#############################
#         POP3              #
#    MailtrafficAnalyzer    #
#  Measures Confixx Traffik #
#  from POP3 Logfile        #
#   (qpopper)               #
#############################

$LogFile = '/var/log/mail';  # change this to the path to your logfile!
$STDOUT = '0'; # print results to stdout
$CONFIXX = '1'; # insert results into confixx database


## einige feste Variablen
%Monate = ('Jan' => '01',
           'Feb' => '02',
           'Mar' => '03',
           'Apr' => '04',
           'May' => '05',
           'Jun' => '06',
           'Jul' => '07',
           'Aug' => '08',
           'Sep' => '09',
           'Oct' => '10',
           'Nov' => '11',
           'Dec' => '12');


$cMonth = (localtime)[4] + 1;
$cYear = (localtime)[5] + 1900;
## /einige feste Variablen

if(!$STDOUT && !$CONFIXX){
  die("You need to set at least one type of output.\n");
}

&loadConfFile;
use DBI;
$dbh = DBI->connect($db_address, $dbUser, $dbPw)
  or die( &ltext('db_connect', '#2001', "$DBI::errstr") );
$GrepAusgabe = &GrepLastLine;
#$GrepAusgabe = 0;
$LastLine = &ParseLogFile;

if ( $LastLine ne "" ) {
  &Mysql_Anbieter;
  ## choose which output to use
  $STDOUT && &Ausgabe_STDOUT;
  $CONFIXX && &Ausgabe_CONFIXX;
  ##// choose which output to use
  &WriteLastLine($LastLine);
}

$dbh->disconnect;

## SUBS
sub ParseLogFile{
  my ($count, $nextLine, $Month, $Day, $User, $NoMails, $SizeMails, $LastLine);
  unless (open(LINIE, "$LogFile")) {
   if(!(-e "$LogFile")){
     die("File $LogFile  does not exist.\n");
   }
   elsif(!(-r "$LogFile")){
     die ("You are not allowed to read $LogFile.\n");
   }
   else{
     die ("$LogFile cannot be opened\n");
   }
  }
  if($GrepAusgabe != 0){
   for($count=0; $count <= $GrepAusgabe; $count++) {
     $Line = <LINIE>;
   }
  }
  $nextLine = <LINIE>;
  if( $nextLine ne ""){
    while($nextLine ne ""){
      if($nextLine =~ /^(\w\w\w)\s+(\d\d?)\s+(\d\d:\d\d:\d\d).+Stats: ($user_prefix\d+)(p\d+)? (\d+) (\d+).+/){
        if( $7 != 0 ) {
          $Month = $1;
          $Day = $2;
          $User = $4;
          $NoMails = $6;
          $SizeMails = $7;
          $POP3{$Month}{$Day}{$User} += $SizeMails;
          $Users{$User} = 1;
          $LastLine = "$Month.*$Day.*$3.*$User.*$NoMails.*$SizeMails";
        }
#     }
#     elsif ( $nextLine =~ /popper/ ) {
#       print "$nextLine\n";
      }
      $nextLine = <LINIE>;
    }
  }
  close ("LINIE");
  return ($LastLine);
}


sub Mysql_Anbieter {
  my $sth = $dbh->prepare("SELECT kunde,anbieter FROM kunden");
  $sth->execute;
  while(@row = $sth->fetchrow_array){
    $Anbieter{$row[0]} = $row[1];
  }
}


sub Ausgabe_CONFIXX {
  my ($User, $TraffikKB, $nMonth, $nDay, $nYear);
  foreach $Month (keys(%POP3)) {
    $nMonth = $Monate{$Month};
    if(($cMonth < 6) && ($nMonth > 6)){
      $nYear = $cYear - 1;
    }
    else{
      $nYear = $cYear;
    }
    foreach $nDay (keys (%{$POP3{$Month}})){
      foreach $User (keys (%{$POP3{$Month}{$nDay}})){
        $TraffikKB = (int ( ( $POP3{$Month}{$nDay}{$User} / 1024 ) * 100 ) ) / 100;
        &Update_MySQL ($User, $Anbieter{$User}, $nDay, $nMonth, $nYear, $TraffikKB);
      }
    }
  }
}


sub Ausgabe_STDOUT {
  my ($User, $TraffikKB, $nMonth, $nDay, $nYear, %total);
  print"\n###### POP3 TRAFFIK ####### \n";
  print "\nDetails \n";
  print "------- \n";
  foreach $Month (keys(%POP3)) {
    $nMonth = $Monate{$Month};
    if(($cMonth < 6) && ($nMonth > 6)){
      $nYear = $cYear - 1;
    }
    else{
      $nYear = $cYear;
    }
    foreach $nDay (keys (%{$POP3{$Month}})){
      print "\n$nDay.$nMonth.$nYear\n";
      foreach $User (keys (%{$POP3{$Month}{$nDay}})){
        $TraffikKB = (int ( ( $POP3{$Month}{$nDay}{$User} / 1024 ) * 100 ) ) / 100;
        print "$User () ($Anbieter{$User}) : $TraffikKB KB : $nDay.$nMonth.$nYear\n";
        $total{$User} += $TraffikKB;
      }
    }
  }
  print "\nTotal \n";
  print "----- \n";
  my @users = sort { $total{$a} <=> $total{$b} } keys %total;
  foreach $user (@users){
    print "$user: $total{$user} KB\n";
  }
}


sub Update_MySQL {
  my ($kunde, $anbieter, $tag, $monat,  $jahr, $traffik) = @_;
  my $sth = $dbh->prepare("SELECT email FROM transfer WHERE kunde='$kunde' AND tag=$tag AND monat=$monat AND jahr=$jahr");
  $sth->execute;
  my $exists = $sth->rows;
  if($exists){
    $dbh->do("UPDATE transfer SET email=email+$traffik WHERE kunde='$kunde' AND tag=$tag AND monat=$monat AND jahr=$jahr");
  }
  else{
    $dbh->do("INSERT INTO transfer (kunde, anbieter, tag, monat, jahr, email) VALUES ('$kunde', '$anbieter', $tag, $monat, $jahr, $traffik)");
  }
}


sub WriteLastLine {
  my ($writeline) = @_;
  $dbh->do("UPDATE grep SET pattern='$writeline' WHERE type='pop3'");
}


sub loadConfFile{
  my ($file, $base);
  if(-T "/root/confixx/confixx_main.conf"){
    $file = "/root/confixx/confixx_main.conf";
  }
  else{
   $0 = $^X unless ($^X =~ m%(^|[/\\])(perl)|(perl.exe)$%i);
   ($base) = $0 =~ m%^(.*)[/\\]%;
   $base ||= ".";
   $file = "$base/confixx_main.conf";
   unless(-T $file){
     die("Couldn't find confixx_main.conf");
   }
 }
 do $file;
}


sub ltext {
  my $text_name = shift;
  if (!%lang_text) {
    my $langFile = "$confixx_htmlDir/languages/$language/scripts.local";
    do $langFile;
  }
  if (!defined($lang_text{$text_name})) {
    return "Sorry, text $text_name not found!";
  }
  else {
    my @VAR = @_;
    my $text = $lang_text{$text_name};
    $text =~ s/\$VAR\[(\d+)\]/$VAR[$1]/g;
    if ($text) {
      return $text;
    }
    else {
      return "Sorry, localizing text $text_name failed!";
    }
  }
}


sub GrepLastLine {
  my $sth = $dbh->prepare("SELECT pattern FROM grep WHERE type='pop3'");
  $sth->execute;
  my $rows = $sth->rows;
  my $pattern = '###NEW###';
  if($rows){
    $pattern = $sth->fetchrow;
    chop($pattern);
  }
  else{
    $dbh->do("INSERT INTO grep (pattern,type) VALUES ('###NEW###','pop3')");
  }
  $sth->finish;
  $pattern =~ s/\[/\\\[/g;
  $pattern =~ s/\]/\\\]/g;
  my $grepAusgabe = `$bin_grep -na '$pattern' $LogFile`;
  if($grepAusgabe =~ /^(\d+):/){
    $grepAusgabe = $1 -1;
  }
  else{
    $grepAusgabe = '0';
  }
  return($grepAusgabe);
}
## /SUBS
