#!/usr/bin/perl -w
# vim: set sw=4 ts=4 si et:
# Written by: Guido Socher, Copyright: GPL
#
no locale;
# this is the directory where lfwmC.pm is found:
use lib '/home/webmail/lfwmail';
use strict;
use lfwmC;
use CGI;
use MIME::Words;
# note: you need also MD5 for POP3Client.
use Mail::POP3Client;
sub printmsglist($$$);
sub msglist($$$);
#
# config data pointer:
my $cf=lfwmC::getconfig();
my $secretsdir=$cf->{'secretsdir'};
my $q;
$q=new CGI;
#
# user data pointer:
my $ud;
$ud=lfwmC::getACU($q);
# 

if(! $ud->{'cookie'} || $q->param('new')){
    unless($q->param('pw')){
        # generate login page
        print $q->header(-Pragma=> 'no-cache');
        print $q->start_html(-title=>"lfwmail web mail, version".$cf->{'ver'},
                             'BGCOLOR="#3b5987"');
        print $q->startform(-method=>'POST',
                            -action=>$cf->{'url'});
        print '
<CENTER>
<h2>lfwmail web mail login</h2>
<TABLE BORDER="1" CELLSPACING="2" CELLPADDING="2">
  <TR bgcolor="#cbdaea">
    <TD ALIGN="RIGHT">Login name:</TD>
    <TD><INPUT NAME="uid" SIZE="20" TYPE="text"></TD>
  </TR>
  <TR bgcolor="#cbdaea">
    <TD ALIGN="RIGHT">Password:</TD>
    <TD><INPUT NAME="pw" TYPE="password" SIZE="20"></TD>
  </TR>
</TABLE>
<br>
';
        print $q->submit();
        print $q->endform;
        print "<br><hr><br>\n";
        print $q->end_html;
        print "\n";
        exit 0;
    }else{
        # we have a password. Store it together with the
        # cookie.
        my $cookie;
        my $uid;
        $uid=$ud->{'uid'};
        $cookie=sprintf("%x%x%x%x",rand(254),rand(254),rand(254),rand(254));
        $ud->{'cookie'}=$cookie;
        my $pw;
        # check pw:
        $pw=$q->param('pw');
        lfwmC::htmldie_std($q,"Error no uid/pw received.") unless($uid && $pw);

        # authenticate by checking pop3 connection
        my $mpop=new Mail::POP3Client(USER =>"$uid",PASSWORD=>"$pw",HOST=>$cf->{'pophost'});
        # Count returns -1 on Authentication Error:
        lfwmC::htmldie_std($q,"Authentication error.") unless($mpop->Count() >=0);
        $mpop->Close();
        
        # pw is ok set it in user data:
        $ud->{'pw'}=$pw;
        # write password:
        lfwmC::writesessionfile($q,$ud,$cf);
        # clean up old decoded messages if any:
        if (-d $cf->{'mimetmpdir'}."/$uid"){
            system("/bin/rm -rf \"".$cf->{'mimetmpdir'}."/$uid\"");
        }
        # generate frameset first, pass cookie and do not use
        # anymore the real password
        print $q->header(-Pragma=> 'no-cache');
        print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
<HTML><HEAD><TITLE>lfwmail web mail, version '.$cf->{'ver'}.'</TITLE>
 <FRAMESET ROWS="40%,60%">
  <FRAME SRC="'.$cf->{'url'}.'?c='.$cookie.'&amp;a=msglist&amp;uid='.$uid.'" NAME="tf">
  <FRAME SRC="'.$cf->{'url'}.'?c='.$cookie.'&amp;a=empty&amp;uid='.$uid.'" NAME="bf">
 </FRAMESET>
</HEAD>
<body>
  <p>This page works only with frames</p>
</body>
</HTML>
';
        exit 0;
        }
}

lfwmC::htmldie_std($q,"Error no uid given.") unless($ud->{'uid'});
# add password to $ud or terminate execution here:
$ud=lfwmC::cookie2pw($q,$ud,$cf);
%ENV=();
$ENV{'PATH'}="/bin:/usr/bin";
$ENV{'IFS'}=" ";

if ($ud->{'action'} eq "msglist"){
    printmsglist($q,$ud,$cf);
}elsif($ud->{'action'} eq "del"){
    my @names=$q->param;
    my $delnum;
    my $pop=new Mail::POP3Client(USER =>$ud->{'uid'},PASSWORD=>$ud->{'pw'},HOST=>$cf->{'pophost'});
    for my $i (@names){
        # the name must match di[0-9]
        if($i=~/^di\d/){
            $delnum=$q->param($i)|| next;
            $pop->Delete($delnum);
        }
    }
    $pop->Close();
    printmsglist($q,$ud,$cf);
}elsif($ud->{'action'} eq "logout"){
    # logout
    # clean up old decoded messages if any:
    if (-d $cf->{'mimetmpdir'}."/".$ud->{'uid'}){
        system("rm -rf \"".$cf->{'mimetmpdir'}."/".$ud->{'uid'}."\" > /dev/null 2>&1");
    }
    unlink($secretsdir."/".$ud->{'uid'}.".session")||die "ERROR: could not delete session file ".$secretsdir."/".$ud->{'uid'}.".session, effective uid is $>\n";
    lfwmC::appendlog("$secretsdir/lfwmail.log","logout;".$ud->{'uid'});
    #
    lfwmC::htmldie($q,"Bye, bye... <a href=\"".$cf->{'url'}."\">Click here to login again</a>");
    #
}elsif($ud->{'action'} eq "empty"){
    print $q->header(-Pragma=> 'no-cache');
	print $q->start_html(-title=>"lfwmail web mail", 'BGCOLOR=#FFFFFF');
    print '<p>Please select a message from the inbox.</p>
';
    print $q->end_html;
    print "\n";
}else{
    lfwmC::htmldie_std($q,"Error no action found.");
}
# ------------   end of main program

sub printbuttonbar($$$){
    my $uid=shift;
    my $cookie=shift;
    my $url=shift;
    print '<small><table border="1" align="right" bgcolor="#BABABA"><tr>';
    print "<td bgcolor=\"#DDDDDD\"><a href=\"${url}_send?c=$cookie&amp;a=n0&amp;uid=$uid\" target=\"bf\">Compose New</a></td>\n";
    print "<td bgcolor=\"#DDDDDD\"><a href=\"${url}?c=$cookie&amp;a=logout&amp;uid=$uid\" target=\"_top\">Logout</a></td>\n";
    print "</tr></table></small>\n";
}

sub printmsglist($$$){
    my $q=shift;
    my $ud=shift;
    my $cf=shift;
    print $q->header(-Pragma=> 'no-cache');
    # we must clean the bottom window if the top list is refreshed
    print q?<html><head><title>lfwmail web mail</title>
<script LANGUAGE="JavaScript">
<!--  to hide script contents from old browsers
function cbg(Obj) {
    Obj.style.backgroundColor="#AAAAFF";
}

function refresh_bf() {
    top.bf.document.open();
    top.bf.document.clear();
    top.bf.document.writeln('<HTML><BODY BGCOLOR="#3b5987">');
    top.bf.document.writeln('<p><font color="#ffffff">Please select a message from the inbox.</font></p>');
    top.bf.document.write('</BODY></HTML>');
    top.bf.document.close();
}
// end hiding contents from old browsers  -->
</SCRIPT>
</head><body bgcolor="#ffffff" onLoad="refresh_bf()">
?;
    printbuttonbar($ud->{'uid'},$ud->{'cookie'},$cf->{'url'});
    print "<center><b>lfwmail, Inbox message list</b></center>\n";
    print "<br clear=\"all\">\n";
    msglist($q,$ud,$cf);
    print $q->end_html;
    print "\n";
}

sub msglist($$$){
    my $q=shift;
    my $ud=shift;
    my $cf=shift;
    my $cookie=shift;
    my $pop=new Mail::POP3Client(USER =>$ud->{'uid'},PASSWORD=>$ud->{'pw'},HOST=>$cf->{'pophost'});
    my $messagecount = $pop->Count();
    if ($messagecount<1){
        lfwmC::htmldie_noheader($q,"No message in mailbox");
        $pop->Close();
        exit 0;
    }
    print "<font size=1>$messagecount messages</font><br>\n";
    my @messagesize = $pop->ListArray();
    my $i=1;
    my ($from,$subject,$size,$date);
    print $q->startform(-method=>'POST',
                        -action=>$cf->{'url'});
    print '<input type="hidden" name="c" value="'.$ud->{'cookie'}."\">\n";
    print '<input type="hidden" name="uid" value="'.$ud->{'uid'}."\">\n";
    print "<table border=\"2\" width=\"98%\">\n";
    print '<tr bgcolor="#BABABA"><th width="50">Msg.<br>Nr.</th><th>From, Date,
    Subject</th><th width="50">Del</th><th width="80">Message<br>Size</th></tr>'."\n";
    while($i<=$messagecount){
        $from='(unknown)';
        $date='(missing date)';
        $subject='(No subject)';
        foreach my $l ( $pop->Head($i) ) {
            if ($l=~/^From:\s*(.+)/){
                $from=(lfwmC::htmlescape($1));
                $from=MIME::Words::decode_mimewords($from);
                next;
            }
            if ($l=~/^Date:\s*(..+)/){
                $date=(lfwmC::htmlescape($1));
                next;
            }
            if ($l=~/^Subject:\s*(..+)/){
                $subject=(lfwmC::htmlescape($1));
                $subject=MIME::Words::decode_mimewords($subject);
                next;
            }
        }
        if (($i % 2) == 0){
            print "<tr bgcolor=\"#cbdaea\">\n";
        }else{
            print "<tr>\n";
        }
        $size=$messagesize[$i]; # element 0 is not used
        $size=0 unless($size); # no undef
        $size=$size / 1024;
        print "<td>$i</td><td><small><b>$from</b><br>$date</small><br> &nbsp;<a href=\"".$cf->{'url'}."_display?c=".$ud->{'cookie'}."&amp;a=s$i&amp;uid=".$ud->{'uid'}."\" onclick=\"cbg(this)\" target=\"bf\">$subject</a></td><td> <input type=\"checkbox\" value=\"$i\" name=\"di$i\"></td><td>".sprintf("%5.1fKb",$size)."</td>
</tr>\n";
        $i++;
    }
    print "</table><br>\n";
    print '<input type="hidden" name="a" value="del">'."\n";
    print '<input type="hidden" name="imax" value="'. ($i-1) . "\">\n";
    print $q->submit(-value=>'Refresh list and DELETE Msgs');
    print $q->endform;
    print "<table width=\"95%\" border=\"0\">\n";
    print "<tr><td>";
    print $q->startform(-method=>'POST',
                        -action=>$cf->{'url'});
    print '<input type="hidden" name="c" value="'.$ud->{'cookie'}."\">\n";
    print '<input type="hidden" name="uid" value="'.$ud->{'uid'}."\">\n";
    print '<input type="hidden" name="a" value="msglist"'."\">\n";
    print $q->submit(-value=>'Refresh list, keep all');
    print $q->endform;
    print "</td><td>";
    printbuttonbar($ud->{'uid'},$ud->{'cookie'},$cf->{'url'});
    print "</td></tr>";
    print "</table>\n";
    print "<br>\n";
    $pop->Close();
}
# end of lfwmail
