#!/usr/bin/perl

use Socket;
use Time::Local;
use MIME::QuotedPrint;
use MIME::Base64;

###### getting form data

%formdata=();
%filenames=();

if( $ENV{'CONTENT_TYPE'}=~/multipart/ )
{
    binmode STDIN;
    read(STDIN, $query, $ENV{'CONTENT_LENGTH'});

    $query=~/\A(.+?)(\015|\012)/;
    $boundary = $1;

    (@allkeys) = split/$boundary/,$query;

    foreach $mykey (@allkeys) {

        if($mykey=~/name="(.+?)"/) {
            $keyname=$1;
            $mykey=~s/\A(.+?)\015{0,1}\012\015{0,1}\012//s;
            $keyinfo=$1;

            if( $keyinfo=~/filename="(.+?)"/ ) {
                $filename = $1;
            } else { $filename=""; }

            $mykey=~s/\015{0,1}\012\Z//;

            $formdata{$keyname}=$mykey;
            $filenames{$keyname}=$filename;
        }
    }
} else {
if( $ENV{'REQUEST_METHOD'} eq 'POST' )
{
    read(STDIN, $query, $ENV{'CONTENT_LENGTH'});

    @params=split(/&/, $query);
    foreach $keyvalueparam (@params) {
        ($keyparam, $valueparam) = split(/=/, $keyvalueparam);
        $valueparam=~tr/+/ /;
        $valueparam=~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
        $formdata{$keyparam}=$valueparam;
    }
} else
{
    $query = $ENV{'QUERY_STRING'};

    @params=split(/&/, $query);
    foreach $keyvalueparam (@params) {
        ($keyparam, $valueparam) = split(/=/, $keyvalueparam);
        $valueparam=~tr/+/ /;
        $valueparam=~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
        $formdata{$keyparam}=$valueparam;
    }
}
}


$main::cgi_bin      = '/usr/local/apache/cgi-bin';
$main::mailbot_path = "$main::cgi_bin/mailbot";
#$main::data_path   = "$main::mailbot_path/data";

$main::from_addr    = 'Ãàçåòà.Ru <mailbot@gazeta.ru>';
$main::smtp_addr    = 'mail.gazeta.ru';
$main::subj         = 'Ãàçåòà.Ru: ';

my $message_template="";
my ($idx,$dbh,$sth,$sthupdate, $hour,$href,%cfg);

sub make_message_template {
    my ($dbhreklama, $sthreklama, $rowreklama, $reklamabanner, $reklamaurl);

    $from = "$formdata{satanfrom}";
    $to = "jager\@gazeta.ru";
    $subj = "î÷åðåäíîé êëîóí ïûòàëñÿ ñòàòü çíàìåíèòûì";


    $message_template = 
	"From: $from\015\012".
	"To: $to\015\012".
	"Subject: $subj\015\012".
	"Date:".time_to_date()."\015\012".
	"Mime-version: 1.0\015\012".
	"Content-Type: multipart/related;\015\012".
	"\tboundary=\"----=_NextPart_000_0007_01C0092B.3FC93040\"\015\012".
	"X-Mailer=Gazeta.RU MailBot v0.25jager=\"\015\012".
	"X-Mailer: Microsoft Outlook Express 5.00.2615.200\015\012".
	"X-MimeOLE: Produced By Microsoft MimeOLE V5.00.2615.200\015\012".
	"\015\012";

    $message_template.="This is a multi-part message in MIME format.\015\012\015\012";

    $message_template.="------=_NextPart_000_0007_01C0092B.3FC93040\015\012";
    $message_template.="Content-Type: multipart/alternative;\015\012";
    $message_template.="\tboundary=\"----=_NextPart_001_001D_01C00A01.3241EC00\"\015\012\015\012";


    $message_template.="------=_NextPart_001_001D_01C00A01.3241EC00\015\012";
    $message_template.="Content-Type: text/plain;\015\012\tcharset=\"Windows-1251\"\015\012";
    $message_template.="Content-transfer-encoding: 8bit\015\012\015\012";
    $message_template.="::textmessagehere::\015\012\015\012";

    $message_template.="------=_NextPart_001_001D_01C00A01.3241EC00--\015\012\015\012";

    $message_template.="------=_NextPart_000_0007_01C0092B.3FC93040\015\012";
    $message_template.="Content-Type: image/jpeg;\015\012\tname=\"mashka.jpg\"\015\012";
    $message_template.="Content-transfer-encoding: base64\015\012";
    $message_template.="\015\012";


#    local $/=undef;
#    open(TPL, "/usr/local/apache/htdocs/images/0putinok.jpg");
#    my $filedata = <TPL>;
#    close(TPL);
#    $/="\n";
	
    $message_template.=encode_base64($formdata{satanpicture}); 
    $message_template.="\015\012";	
    $message_template.="------=_NextPart_000_0007_01C0092B.3FC93040--\015\012";

    $message_template=~s/::textmessagehere::/$formdata{satantext}/;

    

    my %message_destiny = ( from => $from,  to => $to, subj => $subj, message => $message_template );
    sendmail2(\%message_destiny); # || print "zasada!\n"; 
}


# ----------------------------------------------------------------------------
# sendmail stufff
# ----------------------------------------------------------------------------

sub win2koi {
    my (@win)=@_;
    
    foreach (@win) {
	tr/àáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß/ÁÂ×ÇÄÅÖÚÉÊËÌÍÎÏÐÒÓÔÕÆÈÃÞÛÝßÙØÜÀÑáâ÷çäåöúéêëìíîïðòóôõæèãþûýÿùøüàñ/;
	s/«/"/g; s/»/"/g;
    }
    return wantarray ? @win : $win[0];
}
    

sub sendmail_error {
	my $msg=shift;
	warn "$msg\n";
	close(S);
	return 0;
}

sub time_to_date {
    # convert a time() value to a date-time string according to RFC 822
    my $time = $_[0] || time(); # default to now if no argument
    my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
    my @wdays  = qw(Sun Mon Tue Wed Thu Fri Sat);
    my $TZ;
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
        = localtime($time);

    # offset in hours
    my $offset  = sprintf "%.1f", (timegm(localtime) - time) / 3600;
    my $minutes = sprintf "%02d", ( $offset - int($offset) ) * 60;
    $TZ  = sprintf("%+03d", int($offset)) . $minutes;
    
    return join(" ",
                    ($wdays[$wday] . ','),
                     $mday,
                     $months[$mon],
                     $year+1900,
                     sprintf("%02d", $hour) . ":" . sprintf("%02d", $min),
                     $TZ
               );
} # end sub time_to_date


sub sendmail_connect {
	my ($mailcfg)=shift;
	my ($localhost,$smtpaddr,$connected,$oldfh,$retr,$max_retr);
	
	$localhost = (gethostbyname('localhost'))[0] || 'localhost';

	unless(socket(S, AF_INET, SOCK_STREAM, (getprotobyname 'tcp')[2])) {
	    warn "Cannot create socket\n";
	    return 0;
	}

	$smtpaddr = inet_aton($mailcfg->{'smtp'}||'estart.imedia.ru');
	$retr    = 0;
	$max_retr= $mailcfg->{'retries'} || 3;

	1 while( !($connected=connect(S, pack_sockaddr_in($mailcfg->{'port'}||25, $smtpaddr))) && $retr++ < $max_retr );
	print "1: $connected\n";

	unless($connected) {
	    warn "Cannot connect to server\n";
	    return 0;
	}

	$oldfh=select(S); $|=1; select($oldfh);
	return 1;
}

sub sendmail2 {
	my ($mailcfg)=shift;
	my ($from, $to, $subj, $message);

	$from = $mailcfg->{from} || "jager\@gazeta.ru";
	$to = $mailcfg->{to} || "jager\@gazeta.ru";
	$subj = $mailcfg->{subj} || "eStart!";
	my $resp;
	my $date;
	
	print S "RSET\015\012";
	$resp = <S> || "";
	if(!$resp || $resp=~/^(221|[45])/) {
		return sendmail_error("RST error: $resp");
	}

	print S "MAIL FROM:<$from>\015\012";
	$resp = <S> || "";
	
	if(!$resp || $resp=~/^(221|[45])/) {
		return sendmail_error("Invalid sender");
	}
	
	print S "RCPT TO:<$to>\015\012";
	$resp = <S> || "";
    
	if(!$resp || $resp=~/^(221|[45])/) {
		return sendmail_error("Invalid recipient");
	}

	print S "DATA\015\012";
	$resp = <S> || "";
	
	if(!$resp || $resp=~/^(221|[45])/) {
		return sendmail_error("DATA error");
	}
	
	
	$message = $mailcfg->{'message'};
	$message =~s/^\./\.\./gom; 
	$message =~s/\r\n/\n/go;
	$message =~s/\n/\015\012/go;
	$date = $mailcfg->{'date'} || time_to_date();
    
#	print S "From: $from\015\012";
#	print S "To: $to\015\012";
#	print S "Subject: $subj\015\012";
#	print S "Date: $date\015\012";
	print S "$message\015\012.\015\012";
        $resp = <S> || "";
	
	if(!$resp || $resp=~/^(221|[45])/) {
			return sendmail_error("Error sending");
	}
	
	return 1;
}


sub sendmail {
	my ($mailcfg)=shift;

	my $from      = $mailcfg->{'from'}    || 'mailbot@gazeta.ru';
	my $subj      = $mailcfg->{'subject'} || "";
	my $to	      = $mailcfg->{'to'}      || 'dl@gazeta.ru';
	my $resp;
	my $date;
	my $message;
	return;

	print S "RSET\015\012";
	$resp = <S> || "";
	if(!$resp || $resp=~/^(221|[45])/) {
		return sendmail_error("RST error: $resp");
	}

	print S "MAIL FROM:<$from>\015\012";
	$resp = <S> || "";
	
	if(!$resp || $resp=~/^(221|[45])/) {
		return sendmail_error("Invalid sender");
	}
	
	print S "RCPT TO:<$to>\015\012";
	$resp = <S> || "";
    
	if(!$resp || $resp=~/^(221|[45])/) {
		return sendmail_error("Invalid recipient");
	}

	print S "DATA\015\012";
	$resp = <S> || "";
	
	if(!$resp || $resp=~/^(221|[45])/) {
		return sendmail_error("DATA error");
	}
	
	
	$message = $mailcfg->{'message'};
	$message =~ s/^\./\.\./gom; 
	$message =~ s/\r\n/\n/go;
#	$message =  encode_qp($message);
	$message =~ s/\n/\012/go;
    
	$date = $mailcfg->{'date'} || time_to_date();
    
#	print S "From: $from\015\012";
#	print S "To: $to\015\012";
#	print S "Subject: $subj\015\012";
#	print S "Date:$date\015\012";
#	print S "Mime-version: 1.0\015\012";
#	print S "Content-type: text/html; charset=\"Windows-1251\"\015\012";
#	print S "Content-transfer-encoding: quoted-printable\015\012";
#	print S "Content-transfer-encoding: 8bit\015\012";
#	print S "X-Mailer=Gazeta.RU MailBot v 0.24\015\012";
	print S "\015\012$message\015\012.\015\012";
    
        $resp = <S> || "";
	
	if(!$resp || $resp=~/^(221|[45])/) {
			return sendmail_error("Error sending");
	}
	
	return 1;
}


sub sendmail_shutdown {
    print S "quit\015\012";
    <S>;
    close(S);
}

# -----------------------------------------------------------------------------
# end of sendmail
# -----------------------------------------------------------------------------


    $|=1;

    my %mailserver =(   smtp => 'localhost',
			port    => 25 );
			
    sendmail_connect(\%mailserver) || die "satan borogoth";

    make_message_template();
	

    sendmail_shutdown();

    print "Location: http://www.gazeta.ru\n\n";
    exit; 


