#!/usr/bin/perl -w
# 
# Script for collect all spam and generate a spamreport
#
# Author: Matthias Jansen
# Version: 0.2, 2007/01/05

use strict;
use Mail::Sendmail;
use HTML::Entities;
use Fcntl ':flock'; # import LOCK_* constants

# get all possible spam
my @files = `/usr/bin/find /var/vpopmail/domains/ -mtime -1 -a -type f -a \\( -wholename '*.maildir/.Spamverdacht/cur/*' -o -wholename '*.maildir/.Spamverdacht/new/*' \\) -a -not -name '*T' -print`;

my %spams = ();
my $lastuser = '';
my $count = 0;

# collect all the data
for (my $i=0;$i<@files;$i++) {

	my($domain, $user) = $files[$i] =~ /\/var\/vpopmail\/domains\/([^\/]+)\/([^\/]+)\//;
		
	my $currentuser = $user."@".$domain;

	if ($lastuser ne $currentuser) {
		my @temp = ();
		$spams{$currentuser} = \@temp;
		$count = 0;
	}

	$lastuser = $currentuser;
	if (open(SP,"<".$files[$i])) {
		# lock the mail before reading
		flock(SP,LOCK_EX);
		my $subject = '';
		my $from = '';

		while(defined(my $line = <SP>) && (length($subject) == 0 || ($from eq ''))) {
			if ($line =~ /^Subject:\s*(.*)$/i) { $subject = $1; }
			elsif ($line =~ /^From:\s*(.*)$/i) { $from = $1; }
		}
		# encode HTML codes
		encode_entities($subject);
		encode_entities($from);

		my %spam = ('subject' => $subject, 'from' => $from);
		$spams{$currentuser}[$count] = \%spam;
		$count++;
		
		flock(SP,LOCK_UN);
		close(SP);
	}
}


# generate the spamreport now

open(TPL,"</root/spamreport.tpl");
my @a_tpl = <TPL>;
close(TPL);
my $tpl = join("",@a_tpl);

while (my ($user,$data) = each(%spams)) {
	(my $text = $tpl) =~ s/###EMAIL###/$user/;
	my $spam_text = '';
	for (my $i=0;$i<scalar @$data;$i++) {
		$spam_text.= '<tr><td>'.@$data[$i]->{'from'}.'</td><td>'.@$data[$i]->{'subject'}.'</td></tr>';
	}
	$text =~ s/###SPAMTEXT###/$spam_text/;

	my %mail = ( To    => $user,
                From    => 'Spamreporter <spamreport@jansen-systems.de>',
                Message => $text,
		Subject => 'Spamreport',
		'Content-Type' => 'text/html; charset="utf8"'
        );

	sendmail(%mail);
}
