#!/usr/bin/perl

use DBI;
use locale;

use Mail::IMAPClient;		# a nice set of perl libs for imap 
use File::Path;				# create full file paths. (yummy!)
use File::Basename;			# find a nice basename for a folder.

if( $^O=~/linux/ ) {
    require "/usr/local/apache/cgi-bin/neomega/neomega.cfg";
    } else {
    require "/export/horde2/cgi-bin/neomega/neomega.cfg";
    } 

$database=$usercfgdatabase;
$hostname=$usercfghost;
$username=$usercfgname;
$password=$usercfgpass;

#$SERVER		= 'estart.imedia.ru';
$SERVER		= 'localhost';
$USER		= 'rux';
$PASSWORD	= 'pscript.drv';
$PORT		= '143';


%actions = ();
%stopped = ();
%folderd =();

%ffolder = ();
%fposition = ();
%fstring = ();
%fpresent = ();
%faction = ();
%fparams = ();
%fnext = ();
%fcheck = ();
%fsize = ();
%fxz = ();

%filterfolders = ();

%filterfolder = ();
%filteruid = ();
%filterfrom = ();
%filterto = ();
%filtercc = ();
%filtersubj = ();
%filtersize = ();
%filteraction = ();
%filterparams = ();
%filtercheck =();

#print @ARGV;
#exit;

$dbh1 = DBI->connect("DBI:mysql:$neomega::usercfgdatabase:$neomega::usercfghost", $neomega::usercfgname, $neomega::usercfgpass) || exit;

while (1==1)
{

$sth1 = $dbh1->prepare("select pref_filters as filters, user, pref_password as password from imp_pref where user like ?");
#$sth1->execute($ARGV[0].'@%');
$sth1->execute('rux'.'@%');

 while ($row1=$sth1->fetchrow_hashref)
        {
	($USER)=$row1->{user}=~/\A(.+)\@/;
	$PASSWORD=$row1->{password};

#	print "$USER - $PASSWORD\n\n";
	&connect_imap;
if ($imape!=0)
{

%ffolder = ();
%fposition = ();
%fstring = ();
%fpresent = ();
%faction = ();
%fparams = ();
%fnext = ();
%fcheck = ();
%fsize = ();
%fxz = ();

%filterfolders = ();
    
%filterfolder = ();
%filteruid = ();
%filterfrom = ();
%filterto = ();
%filtercc = ();
%filtersubj = ();
%filtersize = ();
%filteraction = ();
%filterparams = ();
%filtercheck =();

	$imap->Uid(1);
	&fetch_folders;
	&find_folders("n");
	#print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
#	for ($i=0; $i<$msgn; $i++)
#	    {
#	    $filteraction{$i}="";
#	    }


#%filterfolders = ();
#%filterfolder = ();
#%filteruid = ();
#%filterfrom = ();
#%filterto = ();
#%filtercc = ();
#%filtersubj = ();
#%filtersize = ();
%filteraction = ();
%filterparams = ();
%filtercheck =();

	&find_folders("p");
	$imap->Uid(0);
	$imap->disconnect();
}
	}

$sth->finish;
sleep 5;
}
$dbh->disconnect;

sub connect_imap { 
	$imape=1;
	$imap = Mail::IMAPClient->new(
		Server		=> "$SERVER", 
		User		=> "$USER",
		Password	=> "$PASSWORD",
		Port		=> "$PORT",
		Clear		=>	'1', 
	)
	|| ($imape=0);

#die ("Could not connect to $SERVER:$PORT with $USER: $! $?\n");
#	print $imap->list("*");
};

sub fetch_folders {
    my (@folders, $folder, $message_count, $new_folder, $path);


    $dbh = DBI->connect("DBI:mysql:$neomega::usercfgdatabase:$neomega::usercfghost", $neomega::usercfgname, $neomega::usercfgpass) ||
	die "Unable to connect to mysql database $neomega::usercfgdatabase at $neomega::usercfghost";

#    $dbh = DBI->connect("DBI:mysql:$database:$hostname", $username, $password);
#    if( !$dbh ) {
#        print "Unable to open database\n";
#        exit;
#    }

    $sth = $dbh->prepare("select pref_filters as filters from imp_pref where user like ?");
    $sth->execute($USER.'@%');


    $ftr=0;

    while ($row=$sth->fetchrow_hashref)
	{
	
	    @filters=split /\#/,$row->{filters};
	    foreach $filter (@filters)
	    {
	    @params = split /:/, $filter;
	    for ($i=0; $i<@params; $i++)
		{
		$params[$i]=~s/\x01/:/g;
		$params[$i]=~s/\x02/#/g;
		}

#	    print "Folder: $params[0], Position: $params[1], String: $params[2], Present: $params[3],  Action: $params[4], Params: $params[5], Next: $params[6], Checked: $params[7], Size: $params[8], X3: $params[9]\n";

	    if ($filterfolders{$params[0]}!=1) {$filterfolders{$params[0]}=1;}

    	    $ffolder{$ftr} =		$params[0];
	    $fposition{$ftr} =		$params[1];
    	    $fstring{$ftr} =		$params[2];
    	    $fpresent{$ftr} =		$params[3];
	    $faction{$ftr} =		$params[4];
    	    $fparams{$ftr} =		$params[5];
    	    $fnext{$ftr} =		$params[6];
	    $fcheck{$ftr} =		$params[7];
	    $fsize{$ftr} =		$params[8];
	    $fxz{$ftr} =		$params[9];
	    
	    $ftr++;
	    }
	}

    $sth->finish;
    $dbh->disconnect;

}



sub find_folders {

    $findme = shift;
    $msgn=0;

    foreach $folder (keys %filterfolders)
	{
#        print "$folder:$findme\n";
        $imap->select($folder);

	if ($findme eq "n")
	    {
    	    @uids = $imap->search("not flagged new not deleted");
	    } else
	    {
    	    @uids = $imap->search("not deleted");
	    }
#        @uids = $imap->search("not flagged not new not deleted");
        foreach $uid (@uids)
    	    { 
	    #print "fuck!\n";
    	    @zlo=($imap->fetch("$uid","(rfc822.header.lines (from to subject cc) rfc822.size)"));
	    foreach (@zlo)
	        {
	        $i++;
	        $z=$_;
	        if ($z=~m/from:/i)		{ ($from)=($z=~m/from:(.+)/i);}
	        if ($z=~m/to:/i)		{ ($to)=($z=~m/to:(.+)/i); }
	        if ($z=~m/cc:/i) 		{ ($cc)=($z=~m/cc:(.+)/i);}
	        if ($z=~m/subject:/i) 		{ ($subj)=($z=~m/subject:(.+)/i);}
	        if ($z=~m/rfc822\.size /i) 	{ ($size)=($z=~m/rfc822\.size (\d+)/i);}
	        }
	        $from=~s/\x0D|\x0A//sg;
	        $to=~s/\x0D|\x0A//sg;
	        $cc=~s/\x0D|\x0A//sg;
	        $subj=~s/\x0D|\x0A//sg;

    		$filterfolder{$msgn} = $folder;	    
	        $filteruid{$msgn} = $uid;
	        $filterfrom{$msgn} = $from;
	        $filterto{$msgn} = $to;
	        $filtercc{$msgn} = $cc;
	        $filtersubj{$msgn} = $subj;
	        $filtersize{$msgn} = $size;

		$msgn++;
	    }
    }

for ($i=0; $i<$msgn; $i++)
    {
    $z=-1;
    foreach (keys %ffolder)
	{
	$z++;
	if ($fcheck{$z} ne "$findme") { next;}
	if ($ffolder{$z} eq $filterfolder{$i})
	    {
	    if ($fposition{$z} eq "From")
		{
		if ($filterfrom{$i}=~m/$fstring{$z}/i)
		    {
		    if ($fpresent{$z} eq "p")
			{
			if ((($filtersize{$i} < $fsize{$z})&&($fxz{$z} eq "l"))||
			    (($filtersize{$i} >= $fsize{$z})&&($fxz{$z} eq "g")))
			    {
			    $filteraction{$i}=$faction{$z};
			    $filterparams{$i}=$fparams{$z};
			    if ($fnext{$z} ne "Next") {last;}
			    }
			}
		    } else
		    {
		    if ($fpresent{$z} eq "n")
			{
			if ((($filtersize{$i} < $fsize{$z})&&($fxz{$z} eq "l"))||
			    (($filtersize{$i} >= $fsize{$z})&&($fxz{$z} eq "g")))
			    {
			    $filteraction{$i}=$faction{$z};
			    $filterparams{$i}=$fparams{$z};
			    if ($fnext{$z} ne "Next") {last;}
			    }
			}
		    }
		} else
		{
		if ($fposition{$z} eq "To")
		    {
		    if ($filterto{$i}=~m/$fstring{$z}/i)
			{
			if ($fpresent{$z} eq "p")
			    {
			    if ((($filtersize{$i} < $fsize{$z})&&($fxz{$z} eq "l"))||
				(($filtersize{$i} >= $fsize{$z})&&($fxz{$z} eq "g")))
				{
				$filteraction{$i}=$faction{$z};
				$filterparams{$i}=$fparams{$z};
				if ($fnext{$z} ne "Next") {last;}
				}
			    }
			} else
			{
			if ($fpresent{$z} eq "n")
			    {
			    if ((($filtersize{$i} < $fsize{$z})&&($fxz{$z} eq "l"))||
				(($filtersize{$i} >= $fsize{$z})&&($fxz{$z} eq "g")))
				{
				$filteraction{$i}=$faction{$z};
				$filterparams{$i}=$fparams{$z};
				if ($fnext{$z} ne "Next") {last;}
				}
			    }
			}
		    } else
		    {
		    if ($fposition{$z} eq "CC")
			{
			if ($filtercc{$i}=~m/$fstring{$z}/i)
			    {
			    if ($fpresent{$z} eq "p")
			        {
				if ((($filtersize{$i} < $fsize{$z})&&($fxz{$z} eq "l"))||
				    (($filtersize{$i} >= $fsize{$z})&&($fxz{$z} eq "g")))
				    {
				    $filteraction{$i}=$faction{$z};
				    $filterparams{$i}=$fparams{$z};
				    if ($fnext{$z} ne "Next") {last;}
				    }
				}
			    } else
			    {
			    if ($fpresent{$z} eq "n")
				{
				if ((($filtersize{$i} < $fsize{$z})&&($fxz{$z} eq "l"))||
				    (($filtersize{$i} >= $fsize{$z})&&($fxz{$z} eq "g")))
				    {
				    $filteraction{$i}=$faction{$z};
				    $filterparams{$i}=$fparams{$z};
				    if ($fnext{$z} ne "Next") {last;}
				    }
				}
			    }
			} else
			{
			if ($fposition{$z} eq "Subj")
			    {
			    if ($filtersubj{$i}=~m/$fstring{$z}/i)
				{
				if ($fpresent{$z} eq "p")
			    	    {
				    if ((($filtersize{$i} < $fsize{$z})&&($fxz{$z} eq "l"))||
					(($filtersize{$i} >= $fsize{$z})&&($fxz{$z} eq "g")))
					{
					$filteraction{$i}=$faction{$z};
					$filterparams{$i}=$fparams{$z};
					if ($fnext{$z} ne "Next") {last;}
					}
				    }
				} else
				{
				if ($fpresent{$z} eq "n")
				    {
				    if ((($filtersize{$i} < $fsize{$z})&&($fxz{$z} eq "l"))||
					(($filtersize{$i} >= $fsize{$z})&&($fxz{$z} eq "g")))
					{
					$filteraction{$i}=$faction{$z};
					$filterparams{$i}=$fparams{$z};
					if ($fnext{$z} ne "Next") {last;}
					}
				    }
				}
			    }
			}
		    }
		}
	    }
	}
    }

    foreach $folder (keys %filterfolders)
	{
#        print "$folder\n";
        $imap->select($folder);

	for ($i=0; $i<$msgn; $i++)
	    {
	    if (($filteraction{$i} ne "")&&($filterfolder{$i} eq $folder))
		{
#		print	"folder=$filterfolder{$i} ";
#		print	"uid=$filteruid{$i} ";
#		print	"from=$filterfrom{$i} ";
#		print	"to=$filterto{$i} ";
#		print	"cc=$filtercc{$i} ";
#		print	"subj=$filtersubj{$i} ";
#		print	"action=$filteraction{$i} ";
#		print	"param=$filterparams{$i}\n";
		
		if ($filteraction{$i} eq "Forward")
		    {
		    ($message)=($imap->message_string("$filteruid{$i}"));
		    $message=~s/\x0D//g;
#		    open M, '|/var/qmail/bin/qmail-inject' or die "cannot pipe to sendmail: $!\n";
		    open M, '|/usr/sbin/sendmail -t' or die "cannot pipe to sendmail: $!\n";
#		    open M, ">&STDIN";
		    print M "From: $USER\@estart\.ru\n";
		    print M "To: $filterparams{$i}\n";
		    print M "Subject: Forward message\n\n";
		    print M "$message";
		    close(M);
		    $imap->store("$uid",'+FLAGS (\flagged)');
#		    print ("Flagged!\n");
		    } else 
		    {
		    if ($filteraction{$i} eq "Move")
			{
#			print "$filterparams{$i}<-$filteruid{$i}\n";
			$imap->move("$filterparams{$i}","$filteruid{$i}");
			$imap->store("$filteruid{$i}",'+FLAGS (\deleted)');
			} else
			{
			if ($filteraction{$i} eq "Reply")
			    {
    			    ($zlo)=($imap->fetch("$filteruid{$i}","(rfc822.header.lines (from))"));
	    		    ($zlo)=($zlo=~m/from:(.+)/i);
	    		    $zlo=~s/\x0D|\x0A//sg;
#			    open M, '|/var/qmail/bin/qmail-inject' or die "cannot pipe to sendmail: $!\n";
			    open M, '|/usr/sbin/sendmail -t' or die "cannot pipe to sendmail: $!\n";
#			    open M, ">&STDIN";
			    print M "From: $USER\@estart\.ru\n";
			    print M "To: $zlo\n";
			    print M "Subject: Auto reply message\n\n";
			    print M "$filterparams{$i}";
			    close(M);
			    #do something
    			    $imap->store("$filteruid{$i}",'+FLAGS (\flagged)');
#			    print ("\nFlagged!\n");
		    
			    } else
			    {
			    if ($filteraction{$i} eq "Noaddr")
				{
				($message)=($imap->message_string("$filteruid{$i}"));
				$message=~s/\x0D//g;
    				($zlo)=($imap->fetch("$filteruid{$i}","(rfc822.header.lines (from))"));
	    			($zlo)=($zlo=~m/from:(.+)/i);
	    			$zlo=~s/\x0D|\x0A//sg;
#				open M, '|/var/qmail/bin/qmail-inject' or die "cannot pipe to sendmail: $!\n";
				open M, '|/usr/sbin/sendmail -t' or die "cannot pipe to sendmail: $!\n";
#				open M, ">&STDIN";
				print M "From: MAILER-DAEMON\@estart\.ru\n";
				print M "To: $zlo\n";
				print M "Subject: Auto reply message\n\n";
				print M "Hi. This is the mail-send program at estart.ru.\n";
				print M "I'm afraid I wasn't able to deliver your message to the following addresses.\n";
				print M "This is a permanent error; I've given up. Sorry it didn't work out.\n\n";
				print M "Connected to 212.188.13.155 but sender was rejected.\n";
				print M "Remote host said: 550 5.0.0 Open spam relay - see http://www.mail-abuse.org/rss\n\n";
				print M "--- Below this line is a copy of the message.\n\n";
				print M "$message";
				close(M);
				$imap->store("$filteruid{$i}",'+FLAGS (\flagged)');
#				print ("Flagged!\n");
				} else
				{
				if ($filteraction{$i} eq "Delete")
				    {
				    $imap->store("$filteruid{$i}",'+FLAGS (\deleted)');
#				    print ("Flagged!\n");
				    }
				}
			    }
			}
		    }
		}
	    }
	}
}


