#use strict 'refs';
use FileHandle;
use IPC::Open2;
use lib '..';
use CGI qw(:standard);
use CGI::Carp qw/fatalsToBrowser/;
use MIME::Base64;
use Time::Local;
use Time::DaysInMonth;

#############
if($credentials{'home'} =~ /(.*)/){$credentials{'home'} = $1;}
&loadaddressbook();

@alias;
&loadalias();

%settings;
&loadsettings();

$action = param('action');
$folder = param('folder') or $folder = "INBOX";
if($folder =~ /^([^\.][^\/]*)/){ $folder = $1; }
&move2cur($folder);

if($action ne "down")
{
  print "Content-type: text/html\n".
        "Cache-Control: no-cache\n\n";
}

@wday = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
@month = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
my %monthsh = 
   (
     "Jan" => 0,
     "Feb" => 1,
     "Mar" => 2,
     "Apr" => 3,
     "May" => 4,
     "Jun" => 5,
     "Jul" => 6,
     "Aug" => 7,
     "Sep" => 8,
     "Oct" => 9,
     "Nov" => 10,
     "Dec" => 11
   );

if($action eq "")
{
  print &draw_frames();
  exit;
}

if($action eq "folders")
{
  print &draw_folders();
  exit;
}

if($action eq "Delete" && param('screen') eq "addressbook") {
  open TMP, "$credentials{'home'}/.web/addressbook";
  my @addresses = <TMP>;
  close TMP;

  my %list;
  grep {
    if($_ =~ /"(.*)" <(.*)>/){ $list{$1} = $2; }
  } @addresses;

  my @dellist = split ";", param('list');

  grep {
    if($_ =~ /"([^"]*)"/) { $_ = $1; }
    delete $list{$_};
  } @dellist;

  undef @addresses;
  while ((my $name, my $addr) = each %list) {
    my $tmp = "\"$name\" <$addr>";
    push @addresses, $tmp;
  }

  my $temp = join "\n", @addresses;
  open TMP, ">$credentials{'home'}/.web/addressbook";
  print TMP $temp;
  close TMP;

  &loadaddressbook();
  $action = "addressbook";
  $oldaction = "Delete";
}

if($action eq "Save" && param('screen') eq "addressbook") {
  open TMP, "$credentials{'home'}/.web/addressbook";
  my @addresses = <TMP>;
  close TMP;

  my %list;
  grep {
    if($_ =~ /"(.*)" <(.*)>/){ $list{$1} = $2; }
  } @addresses;

  if((my $name = param('displayname')) && (my $address = param('address'))) {
    $list{$name} = $address;
  }

  undef @addresses;
  while ((my $name, my $addr) = each %list) {
    my $tmp = "\"$name\" <$addr>";
    push @addresses, $tmp;
  }

  my $temp = join "\n", @addresses;
  open TMP, ">$credentials{'home'}/.web/addressbook";
  print TMP $temp;
  close TMP;

  &loadaddressbook();
  $action = "addressbook";
}

if($action eq "checkaddressbook") {
  my $field = param('field');
  my $list = param('list');

  print
  "<head><title>Checking Names</title></head>\n".
  "<body text=#ffffff bgcolor=#000080 link=#FFFF00 vlink=#C0C000 alink=#FFFF88 onLoad='parent.folders.location = \"?action=folders\"'>\n\n".
  "<noscript>This won't work without javascript.  Period.</noscript>\n".
  "<font face='verdana' size=2><b>Checking names";
  if($field eq "to"){print "..."; }
  if($field eq "cc"){print "......"; }
  if($field eq "bcc"){print "........."; }
 
  print
  "</b></font>\n".
  "<script language='javascript'>\n".
  "  function submitaddresses (check, list) {\n".
  "    opener.document.forms.compose.$field.value = list;\n".
  "    field = '$field';\n".
  "    if(check == 'yes'){\n".
  "      if(field == 'to'){field = 'cc';}\n".
  "      else if(field == 'cc'){field = 'bcc';}\n".
  "    }\n".
  "    if(check == 'maybe' || '$field' != 'bcc') {\n".
  "      opener.openAddressBook(field, check);\n".
  "    }\n".
  "    if(check == 'maybe' || '$field' == 'bcc') {\n".
  "      window.close();\n".
  "    }\n".
  "  }\n".
  "</script>\n";

  my $line;
  my @newaddresses;
  for (my $x=0;$x < length($list);$x++)
  {
    if($list =~ /^("[^"]*")/)
    {
      $line .= $1;
      $list =~ s/^("[^"]*")//;
    }
    elsif($list =~ /^[,;]/)
    {
      push @newaddresses, $line;
      $line = "";
      $list =~ s/^[,;]//;
    }
    elsif($list =~ /^([^";,]+)/)
    {
      $line .= $1;
      $list =~ s/^([^";,]+)//;
    }
  }
  push @newaddresses, $line;

#  $list =~ s/,/;/g;
#  $list =~ s/ *; */;/g;
#  my @newaddresses = split ";", $list;

  for (my $x = 0; $x < @newaddresses; $x++)
  {
    $newaddresses[$x] =~ s/^[ ;\t\r\n]//g;
    $newaddresses[$x] =~ s/[ ;\t\r\n]$//g;
    $newaddresses[$x] = &findaddress($newaddresses[$x]);
  }

  @newaddresses = sort {uc($a) cmp uc($b)} @newaddresses;
  grep {
   if($_) {
    my $name; my $addr;
    if($_ =~ /"(.*)" <(.*)>/){$name = $1; $addr = $2; }
    if($addr !~ /^[^@]+@[^.]+\..+/) {
      print "<script>\n".
      "  submitaddresses('maybe', '".join("; ", @newaddresses)."');\n".
      "</script>\n";
      exit;
    }
   }
  } @newaddresses;

  print
  "<script>\n".
  "  submitaddresses('yes', '".join("; ", @newaddresses)."');\n".
  "</script>\n".
  "</body>\n".
  "</html>\n";

}

if($action eq "addressbook") {
  my $field = param('field');
  my $list = param('list');
  my $quick = param('quick');
  if($oldaction eq "Delete") {
    $list = "";
  }

  my $line;
  my @newaddresses;
  for (my $x=0;$x < length($list);$x++)
  {
    if($list =~ /^("[^"]*")/)
    {
      $line .= $1;
      $list =~ s/^("[^"]*")//;
    }
    elsif($list =~ /^[,;]/)
    {
      push @newaddresses, $line;
      $line = "";
      $list =~ s/^[,;]//;
    }
    elsif($list =~ /^([^";,]+)/)
    {
      $line .= $1;
      $list =~ s/^([^";,]+)//;
    }
  }
  push @newaddresses, $line;

#  $list =~ s/,/;/g;
#  $list =~ s/ *; */;/g;

#  my @newaddresses = split ";", $list;
  my %checked;
  my %addr;

  for (my $x = 0; $x < @newaddresses; $x++) {
    $newaddresses[$x] =~ s/^[ ;\t\r\n]//g;
    $newaddresses[$x] =~ s/[ ;\t\r\n]$//g;
    $newaddresses[$x] = &findaddress($newaddresses[$x]);
    $checked{$newaddresses[$x]} = ($x + 1);
  }

  grep {
    my $y = $_; $y =~ s/BUILTIN$//g;
    if(my $x = $checked{$y}) {
      delete $newaddresses[$x - 1];
    }
  } @addresses;

  while((my $key, my $value) = each %checked) {
    $checked{$key} = "checked";
  }

  @newaddresses = sort {uc($a) cmp uc($b)} @newaddresses;
  @addresses = sort {uc($a) cmp uc($b)} @addresses;

  my $controls = "<table width=100% cellpadding=0><tr><td width=200>\n".
  "<input type='button' value='Ok' onClick='submitaddresses();'>\n";
  if($field) { $controls = $controls.
    "<font size=1>Choose addresses for the </font>'$field'<font size=1> field.";
  }
  $controls = $controls.
  "</td><td align='right'>\n".
  "<input type='submit' name='action' value='Delete'></td></tr>\n".
  "<tr><td colspan=2 align='right'><font size=1>\nName ".
  "</font><font size=2><input type='text' size=9 name='displayname' onChange='update(this.name, this.value);'>\n".
  "<font size=1>Address </font><input type='text' size=16 name='address' onChange='update(this.name, this.value);'>\n".
  "<input type='submit' name='action' value='Save'>\n".
  "</td></tr></table>\n";

  print
  "<head><title>Address Book</title></head>\n".
  "<body text=#ffffff bgcolor=#000080 link=#FFFF00 vlink=#C0C000 alink=#FFFF88 onMouseUp='mouseup();' onLoad='parent.folders.location = \"?action=folders\"'>\n\n".
  "<noscript>This won't work without javascript.  Period.</noscript>\n".
  "<script language='javascript'>\n".
  "  starty = 0;\n".
  "  startx = 0;\n".
  "  function mousedown(evnt) {\n".
  "    if (document.layers) { // Netscape\n".
  "      document.captureEvents(Event.MOUSEMOVE);\n".
  "      document.onmousemove = captureMousePosition;\n".
  "    } else if (document.all) { // Internet Explorer\n".
  "      document.onmousemove = captureMousePosition;\n".
  "    } else if (document.getElementById) { // Netcsape 6\n".
  "      document.onmousemove = captureMousePosition;\n".
  "    }\n".
  "  }\n".
  "  xMousePos = 0; // Horizontal position of the mouse on the screen\n".
  "  yMousePos = 0; // Vertical position of the mouse on the screen\n".
  "  xMousePosMax = 0; // Width of the page\n".
  "  yMousePosMax = 0; // Height of the page\n".
  "  function captureMousePosition(e) {\n".
  "    if (document.layers) {\n".
  "        xMousePos = e.pageX;\n".
  "        yMousePos = e.pageY;\n".
  "        xMousePosMax = window.innerWidth+window.pageXOffset;\n".
  "        yMousePosMax = window.innerHeight+window.pageYOffset;\n".
  "    } else if (document.all) {\n".
  "        xMousePos = window.event.x+document.body.scrollLeft;\n".
  "        yMousePos = window.event.y+document.body.scrollTop;\n".
  "        xMousePosMax = document.body.clientWidth+document.body.scrollLeft;\n".
  "        yMousePosMax = document.body.clientHeight+document.body.scrollTop;\n".
  "    } else if (document.getElementById) {\n".
  "        xMousePos = e.pageX;\n".
  "        yMousePos = e.pageY;\n".
  "        xMousePosMax = window.innerWidth+window.pageXOffset;\n".
  "        yMousePosMax = window.innerHeight+window.pageYOffset;\n".
  "    }\n".
  "    if (startx == 0) {\n".
  "      starty = (yMousePos - parseInt(document.getElementById('temp').style.top));\n".
  "      startx = (xMousePos - parseInt(document.getElementById('temp').style.left));\n".
  "    }\n".
  "    moveWindow(xMousePos,yMousePos);\n".
  "  }\n".
  "  function mouseup() {\n".
  "    if (document.layers) { // Netscape\n".
  "      document.releaseEvents(Event.MOUSEMOVE);\n".
  "    }\n".
  "    document.onmousemove = '';\n".
  "    startx = starty = 0;\n".
  "  }\n".
  "  function moveWindow(x,y) {\n".
  "    document.getElementById('temp').style.top = (y - starty);\n".
  "    document.getElementById('temp').style.left = (x - startx);\n".
  "  }\n".
  "  function closetempedit() {\n".
  "    if(document.layers) {\n".
  "      object = document.layers[0].document.forms.tempwindow;\n".
  "      document.temp.top = -100;\n".
  "      document.left = 11;\n".
  "    }\n".
  "    else {\n".
  "      object = document.forms.tempwindow;\n".
  "      document.getElementById('temp').style.top = -100;\n".
  "      document.getElementById('temp').style.left = 11;\n".
  "    }\n".
  "    for(x=0; x < object.elements.length; x++) {\n".
  "      if(object.elements[x].name == 'tempold') {\n".
  "        tempold = object.elements[x].value;\n".
  "      }\n".
  "    }\n".
  "    for(x=0; x < document.forms.addressbook.elements.length; x++) {\n".
  "      if(document.forms.addressbook.elements[x].value == tempold && document.forms.addressbook.elements[x].name == 'addresscheck') {\n".
  "        document.forms.addressbook.elements[x].checked = 1;\n".
  "      }\n".
  "    }\n".
  "    gatherlist();\n".
  "  }\n".
  "  function update (myname, myvalue) {\n".
  "    for(x=0; x < document.forms.addressbook.elements.length; x++) {\n".
  "      if(document.forms.addressbook.elements[x].name == myname) {\n".
  "        document.forms.addressbook.elements[x].value = myvalue;\n".
  "      }\n".
  "    }\n".
  "  }\n".
  "  function tempedit (name, address) {\n".
  "    if(document.layers) {\n".
  "      object = document.layers[0].document.forms.tempwindow;\n".
  "    }\n".
  "    else {\n".
  "      object = document.forms.tempwindow;\n".
  "    }\n".
  "    for(x=0; x < object.elements.length; x++) {\n".
  "      if(object.elements[x].name == 'tempname') {\n".
  "        object.elements[x].value = name;\n".
  "      }\n".
  "      if(object.elements[x].name == 'tempaddr') {\n".
  "        object.elements[x].value = address;\n".
  "      }\n".
  "      if(object.elements[x].name == 'tempold') {\n".
  "        object.elements[x].value = '\"' + name + '\" <' + address + '>';\n".
  "      }\n".
  "    }\n".
  "    for(x=0; x < document.forms.addressbook.elements.length; x++) {\n".
  "      if(document.forms.addressbook.elements[x].value == '\"' + name + '\" <' + address + '>' && document.forms.addressbook.elements[x].name == 'addresscheck') {\n".
  "        document.forms.addressbook.elements[x].checked = 0;\n".
  "      }\n".
  "    }\n".
  "    gatherlist();\n".
  "    if(document.layers){\n".
  "      document.temp.top = window.pageYOffset + 100;\n".
  "    }\n".
  "    else if(document.all){\n".
  "      document.getElementById('temp').style.top = document.body.scrollTop + 100;\n".
  "    }\n".
  "    else {\n".
  "      document.getElementById('temp').style.top = window.pageYOffset + 100;\n".
  "    }\n".
  "  }\n".
  "  function edit (name, address) {\n".
  "    for(x=0; x < document.forms.addressbook.elements.length; x++) {\n".
  "      if(document.forms.addressbook.elements[x].name == 'displayname') {\n".
  "        document.forms.addressbook.elements[x].value = name;\n".
  "      }\n".
  "      if(document.forms.addressbook.elements[x].name == 'address') {\n".
  "        document.forms.addressbook.elements[x].value = address;\n".
  "      }\n".
  "    }\n".
  "  }\n".
  "  function addtempname () {\n".
  "    if(document.layers) {\n".
  "      name = document.layers[0].document.forms.tempwindow.tempname.value;\n".
  "      address = document.layers[0].document.forms.tempwindow.tempaddr.value;\n".
  "    }\n".
  "    else {\n".
  "      name = document.getElementById('tempname').value;\n".
  "      address = document.getElementById('tempaddr').value;\n".
  "    }\n".
  "    window.location = 'mail.pl?action=addressbook&quick=$quick&field=$field&list=' + escape(document.forms.addressbook.list.value + '\"' + name + '\" <' + address + '>; ');\n".
  "  }\n".
  "  function gatherlist () {\n".
  "    document.forms.addressbook.list.value = '';\n".
  "    for(x = document.forms.addressbook.elements.length - 1;x > -1; x--) {\n".
  "      if(document.forms.addressbook.elements[x].name == 'addresscheck'".
  " && document.forms.addressbook.elements[x].checked) {\n".
  "        document.forms.addressbook.list.value =".
  " document.forms.addressbook.elements[x].value + '; '".
  " + document.forms.addressbook.list.value;\n".
  "      }\n".
  "    }\n".
  "  }\n".
  "  function tempadd(name, addr) {\n".
  "    window.location=('mail.pl?action=Save&screen=addressbook&field=$field&list=' + escape('$list') + '&displayname=' + name + '&address=' + addr);\n".
  "  }\n".
  "  function submitaddresses () {\n";
  if($field) {
    print
    "    opener.document.forms.compose.$field.value = document.forms.addressbook.list.value;\n";
  }
  if($quick eq "maybe") {
    print
    "    opener.openAddressBook('$field', 'yes');\n";
  }
  print
  "    window.close();\n".
  "  }\n".
  "</script>\n".


  " <div id='temp' style='position: absolute;top: -100;left: 30' name='temp' onMouseUp='mouseup();'>\n".
  "  <form id='tempwindow' name='tempwindow' action=''>\n".
  "  <table border=1 bgcolor=#888888>\n".
  "   <tr><td onMouseDown='mousedown();' bgcolor=#0066AA><b>Edit Temporary Address</b></td></tr>\n".
  "   <tr><td bgcolor=#0022FF height=30 align='right'>\n".
  "    <font size=1>Name </font><input type='text' id='tempname' name='tempname' size=9>\n".
  "    <font size=1>Address </font><input type='text' id='tempaddr' name='tempaddr' size=16><br>".
  "    <input type='hidden' name='tempold'>\n".
  "    <input type='button' onClick='closetempedit();' value='Cancel'>\n".
  "    <input type='button' onClick='addtempname();' value='Ok'>\n".
  "  </font></td></tr></table>\n".
  " </form>\n".
  " </div>\n".


  "<form name='addressbook' action='mail.pl' method='post'>\n".
  "<input type='hidden' name='list'>\n".
  "<input type='hidden' name='quick' value='$quick'>\n".
  "<input type='hidden' name='field' value='$field'>\n".
  "<input type='hidden' name='screen' value='addressbook'>\n".
  "<table border=1><tr><td colspan=10>\n".
  "$controls\n".
  "</td></tr>";

  grep {
   if($_) {
    my $name; my $addr;
    if($_ =~ /"(.*)" <(.*)>/){$name = &text2html($1); $addr = &text2html($2); }
    my $bgcolor;
    if($addr =~ /^[^@]+@[^.]+\..+/) {$bgcolor = "bgcolor=#888888"; }
    else {$bgcolor = "bgcolor=#FF0000";}
    print
    "<tr><td $bgcolor><input type='checkbox' name='addresscheck'".
    " value='\"$name\" <$addr>' onClick='gatherlist();' $checked{$_}></td>\n".
    "<td align='center' $bgcolor><font color=#000000>$name<img src='/img/web/dot.gif'></td><td align='center' $bgcolor><font color=#000000>$addr<img src='/img/web/dot.gif'></td>\n";
    if($bgcolor =~ /#FF0000/) {
      print
      "<td $bgcolor><a href='javascript:tempedit(\"$name\", \"$addr\");'>Edit</a></td>";
    }
    else {
      print
      "<td $bgcolor><font size=1><a href='javascript:tempedit(\"$name\", \"$addr\");'>Edit</a><br>\n".
      "<a href='javascript:tempadd(\"$name\", \"$addr\");'>Add</a></td>";
    }
    print "</tr>\n";
   }
  } @newaddresses;

  grep {
    my $name; my $addr;
    if($_ =~ /"(.*)" <(.*)>/){$name = &text2html($1); $addr = &text2html($2); }
    print
    "<tr><td><input type='checkbox' name='addresscheck'".
    " value='\"$name\" <$addr>' onClick='gatherlist();' ".$checked{"\"$name\" <$addr>"}."></td>\n".
    "<td align='center'>$name</td><td align='center'>$addr</td>\n";
    if($_ !~ /BUILTIN$/) {
      print
      "<td><a href='javascript:edit(\"$name\", \"$addr\");'>Edit</a></td>";
    }
    print "</tr>\n";
  } @addresses;

  print
  "<tr><td colspan=10>\n".
  "$controls\n".
  "</td></tr></table>".
  "<script> gatherlist(); </script>\n";

  print
  "</body>\n".
  "</html>\n";

}

if($action eq "Send") {
  $mimefile = param('message');

  &splitmail ("$credentials{'home'}/.Maildir/.web/$mimefile");

  my $body = param('body');
  $body =~ s/\r//g;
  $body =~ s/\n$//;
  unlink "$credentials{'home'}/.Maildir/.web/tmp/0.mime";
  open TMP, ">$credentials{'home'}/.Maildir/.web/tmp/1.mime";
  print TMP "Content-type: text/plain\n\n".$body;
  close TMP;

  my @dates = split("\n", `/usr/bin/date -R`);
  my $date_2822 = @dates[0];

  my $effing_real_name = $alias[param('from')];
  $effing_real_name =~ s/@.*//;
  my $header = "To: ".param('to')."\nCc: ".param('cc')."\n".
    "From: $effing_real_name <".$alias[param('from')].">\n".
    "Reply-to: ".$alias[param('from')]."\n".
    "Date: $date_2822\n".
    "Subject: ".param('subject')."\n".
    "MIME-Version: 1.0\n".
    "X-FromLocal: teralon\n";
  $header =~ s/;/,/g;

  $mimefile = &joinmail($header);

  my $sendto = fixaddresses(param('to')."; ".param('cc')."; ".param('bcc'));
  my @list = split "; ", $sendto;
  @list = grep($_ =~ /<.+\@.+\..+>/, @list);

  open TMP, "<$credentials{'home'}/.Maildir/.web/$mimefile";
  my $blob = join "", <TMP>;
  close TMP;
#  my $cr = chr(13).chr(10);
  $blob =~ s/\r//gms;
#  $blob =~ s/\n/$cr/gms;

#  $ENV{'RELAYCLIENT'} = "";
  my $recip;
  grep
  {
    if($_ =~ /<(.*)>/){ $recip .= "$1 "; }
  } @list;
  if($credentials{'username'} =~ /(.*)/){ $credentials{'username'} = $1; }

  open my $fh, "| /var/qmail/bin/qmail-inject -f$credentials{'username'} $recip";
  
#  print $fh
#  "ehlo splitreflection.com\n".
#  "mail from: ".$alias[param('from')]."\@splitreflection.com\n";
#  grep {
#    my $address;
#    if($_ =~ /"[^"]*" <([^>]*)>/) { $address = $1; }
#    print SMTP "rcpt to: $address\n";
#  } @list;
#  print SMTP "data\n".$blob."\r\n.\r\nquit\n";
  print $fh $blob;

  close $fh;

  link("$credentials{'home'}/.Maildir/.web/$mimefile","$credentials{'home'}/.Maildir/Sent Items/cur/".time.".".$$.".Penguin:2,S");

  print "<b>Message sent to the following recipients:<br>";
  grep {
    print " &nbsp; &nbsp; &nbsp; &nbsp; ".&text2html($_)."<br>";
  } @list;
  print "</b><br><br>";


  $action = "inbox";
}

if($action eq "Move")
{
  my @move = split " ", param('message');
  my $tofolder = param('tofolder');
  if($tofolder =~ /^([^\.][^\/]*)/) { $tofolder = $1; }

  grep
  {
    if($_ =~ /(.*)/)
    {
      rename "$credentials{'home'}/.Maildir/$folder/cur/$1", "$credentials{'home'}/.Maildir/$tofolder/cur/$1";
    }
  } @move;

  $settings{"moveto.".$folder} = $tofolder;
  &savesettings;
  $action = "inbox";
}

if($action eq "New Folder")
{
  my $newfolder = param('newfolder');
  my $infolder = param('infolder');
  if($newfolder =~ /^([^\.][^\/]*)/) { $newfolder = $1; }
  if($infolder =~ /^([^\.][^\/]*)/) { $newfolder = "$1.$newfolder"; }

  mkdir "$credentials{'home'}/.Maildir/$newfolder";
  mkdir "$credentials{'home'}/.Maildir/$newfolder/new";
  mkdir "$credentials{'home'}/.Maildir/$newfolder/cur";
  mkdir "$credentials{'home'}/.Maildir/$newfolder/tmp";

  $action = "inbox";
}


if($action eq "inbox") {
  print
  "<body text=#ffffff bgcolor=#000080 link=#FFFF00 vlink=#C0C000 alink=#FFFF88 onUnload='newcount=0;notify();' onLoad='parent.folders.location = \"?action=folders\"'>\n\n".
  "<noscript>Hobbits without Javascript enabled will be logged off in 4 hours.</noscript>\n";

  opendir CUR, "$credentials{'home'}/.Maildir/$folder/cur" or die "Unable to open current mail directory";
  @cur = readdir CUR;
  close CUR;

  @cur = grep(/^[^.]/, @cur);
  grep
  {
    $_ = "$credentials{'home'}/.Maildir/$folder/cur/$_";
  } @cur;
  @cur = sort {uc($b) cmp uc($a)} @cur;
 
  my $buttons = 
  "<tr><td colspan=10><table width=100%><tr><td>\n".
  " <input type='submit' name='action' value='Compose'>\n".
  " <input type='submit' name='action' value='Move'>".
  " checked items to ".
  " <select name='tofolder' onChange='to_folder(this.value);'>\n";

  opendir my $dh, "$credentials{'home'}/.Maildir";
  my @dirs = readdir $dh;
  closedir $dh;

  @dirs = grep(/^[^.]/ && -d "$credentials{'home'}/.Maildir/$_/cur", @dirs);
  @dirs = sort{$a cmp $b} @dirs;
  grep
  {
    if($_ ne $folder)
    {
      $buttons .= "<option value='$_'";
      if($settings{"moveto.".$folder})
      {
        if($settings{"moveto.".$folder} eq $_){ $buttons .= " selected='yes'"; }
      }
      elsif($_ eq "Deleted Items" || ($folder eq "Deleted Items" && $_ eq "INBOX")){$buttons .= " selected='yes'";}
      $buttons .= ">$_</option>\n";
    }
  } @dirs;
  $buttons .=
  " </select><br />\n".
  " <input type='submit' name='action' value='New Folder'>".
  " named <input type='text' name='newfolder' onChange='new_folder(this.value);'/> in ".
  " <select name='infolder' onChange='in_folder(this.value);'>\n";

  opendir my $dh, "$credentials{'home'}/.Maildir";
  my @dirs = readdir $dh;
  closedir $dh;

  @dirs = grep(/^[^.]/ && -d "$credentials{'home'}/.Maildir/$_/cur", @dirs);
  @dirs = sort{$a cmp $b} @dirs;
  unshift @dirs, "";
  grep
  {
    $buttons .= "<option value='$_'>$_</option>\n";
  } @dirs;
  $buttons .=
  " </select>\n".
  "</td><td align='right'>\n".
  "</td></tr></table></td></tr>\n";
  my $linecount = @cur;

  print
  "<script language='javascript'>\n".
  "  newcount = 0;\n".
  "  function notify () {\n".
  "    if(newcount){ parent.document.title = newcount + ' new messages - Split|Reflection';}\n".
  "    else { parent.document.title = 'Split|Reflection';}\n".
  "  }\n".
  "  function to_folder (myvalue) {\n".
  "    for(x=0; x < document.forms.inbox.elements.length; x++) {\n".
  "      if(document.forms.inbox.elements[x].name == 'tofolder') {\n".
  "        document.forms.inbox.elements[x].value = myvalue;\n".
  "      }\n".
  "    }\n".
  "  }\n".
  "  function in_folder (myvalue) {\n".
  "    for(x=0; x < document.forms.inbox.elements.length; x++) {\n".
  "      if(document.forms.inbox.elements[x].name == 'infolder') {\n".
  "        document.forms.inbox.elements[x].value = myvalue;\n".
  "      }\n".
  "    }\n".
  "  }\n".
  "  function new_folder (myvalue) {\n".
  "    for(x=0; x < document.forms.inbox.elements.length; x++) {\n".
  "      if(document.forms.inbox.elements[x].name == 'newfolder') {\n".
  "        document.forms.inbox.elements[x].value = myvalue;\n".
  "      }\n".
  "    }\n".
  "  }\n".
  "  function checkdelete (checked) {\n".
  "    for(x=0; x < document.forms.inbox.elements.length; x++) {\n".
  "      if(document.forms.inbox.elements[x].name == 'delete') {\n".
  "        document.forms.inbox.elements[x].checked = checked;\n".
  "      }\n".
  "    }\n".
  "    gatherdelete ();\n".
  "  }\n".
  "  function gatherdelete () {\n".
  "    document.forms.inbox.message.value = '';\n".
  "    for(x=0; x < document.forms.inbox.elements.length; x++) {\n".
  "      if(document.forms.inbox.elements[x].name == 'delete' && ".
  "document.forms.inbox.elements[x].checked) {\n".
  "        document.forms.inbox.message.value = ".
  "document.forms.inbox.elements[x].value + ' ' + ".
  "document.forms.inbox.message.value;\n".
  "      }\n".
  "    }\n".
  "  }\n".
  "  setTimeout('window.location = \"?action=inbox&folder=$folder\"',300000);\n".
  "</script>\n".
  "<form name='inbox' method='post' action='mail.pl'>\n".
  "<input type='hidden' name='message'>\n".
  "<input type='hidden' name='folder' value='$folder'>\n".
  "<table border=1><tr><td colspan=10 align='center'>\n".
  "<font face='verdana' size=2><font size=4>$folder folder for $credentials{'username'}</font><br>\n";

  &headerfolder();

  print
  "</td><tr>\n".
  $buttons.
  "<tr><td bgcolor=#2222FF><font face='verdana'><b>N</b></td>\n".
  "<td bgcolor=#2222FF><b>@</b></td>\n".
  "<td bgcolor=#2222FF><input type='checkbox' name='deleteall' ".
  "onClick='checkdelete(document.forms.inbox.deleteall.checked);'></td>\n";
#if ($folder == 1) {
  print "<td bgcolor=#2222FF><font face='verdana'><b>Sent To</b></td>\n";
#}
#else {
  print "<td bgcolor=#2222FF><font face='verdana'><b>Sender</b></td>\n";
#}
  print
  "<td bgcolor=#2222FF><font face='verdana'><b>Subject</b></td>\n".
  "<td bgcolor=#2222FF><font face='verdana'><b>Date Received</b></td>\n".
  "<td bgcolor=#2222FF><font face='verdana'><b>Size</b></td></tr>\n";

  $linecount = 0;

  grep
  {
    if($_ =~ /(.+)/){$_ = $1;}
    my $filename = $_;
#    my @stats = stat $filename;
#    open tmp, "<$filename";
#    my $sender = my $sentto = my $subject = my $content = "";
#    header: while(my $file = <tmp>)
#    {
#      if($file =~ /^$/) {last header;}
#      if($file =~ /^From: +(.*)/)
#      {
#	my $len;
#	if($folder == 1) { $len = 15; }
#	else { $len = 35; }
#        $sender = substr $1, 0, $len;
#	if(length($sender) == $len) { $sender =~ s/...$/.../; }
#      }
#      if($file =~ /^To: +(.*)/)
#      {
#	my $len;
#	if($folder == 1) { $len = 35; }
#	else { $len = 15; }
#	$sentto = substr $1, 0, $len;
#	if(length($sentto) == $len) { $sentto =~ s/...$/.../; }
#      }
#      if($file =~ /^Subject: +(.*)/) {$subject = $1;}
#      if($file =~ /^Content-[Tt]ype: +(.*)/) {$content = $1;}
#    }
#    if(!$subject) {$subject = "none";}
#    if(!$sender) {$sender = "unknown";}
#    if(!$sentto) {$sentto = "unknown";}
#    if($sender =~ /"(.+)"/) {$sender = $1;}
#    if($sentto =~ /"(.+)"/) {$sentto = $1;}
#    if($sender =~ /(.+) <.+>/) {$sender = $1;}
#    if($sentto =~ /(.+) <.+>/) {$sentto = $1;}
#    if($sender =~ /\((.+)\)/) {$sender = $1;}
#    if($sentto =~ /\((.+)\)/) {$sentto = $1;}
#    $sender = &text2html($sender);
#    $sentto = &text2html($sentto);
#    $subject = &text2html($subject);

#    close tmp;

#    my $size = $stats[7];
#    my $date = $_;
#    $date =~ s/([^.]*).*/$1/;
#    my @ltime = localtime $date;
#    if($ltime[2] > 11) {
#      $ltime[2] = $ltime[2] - 12;
#      $ltime[10] = 'PM';
#    }
#    else { $ltime[10] = 'AM';}
#    if($ltime[2] == 0){$ltime[2] = 12;}
#    if($ltime[1] < 10){$ltime[1] = "0".$ltime[1];}

#    $date = ($ltime[4] + 1)."/".$ltime[3]."/".($ltime[5] + 1900).
#     " ".$ltime[2].":".$ltime[1]." ".$ltime[10];

    my $msg = &msg_stats($filename);
    my $basename;
    if($filename =~ /([^\/]*)$/){ $basename = $1; }
    my $subj = $$msg{'subject'};
    if(!$subj){$subj = "&lt;No Subject&gt;"; }

    print
    "<tr><td>";
    my $newstatus = "N";
    if($$msg{'status'} =~ /S/){ $newstatus = ""; }
    print $newstatus.
    "</td><td>";
    if($$msg{'content-type'} =~ /multipart\/mixed/i){print "@";}
    print
    "</td><td><input type='checkbox' name='delete' value='$basename' ".
    "onClick='gatherdelete();'></td>\n".
    "<td><font face='verdana' size=2><a href='mail.pl?action=read\&folder=$folder\&message=$basename'>".&text2html(&shorten($$msg{'to'},15))."</a>".
    "</td><td><font face='verdana' size=2><a href='mail.pl?action=read\&folder=$folder\&message=$basename'>".&text2html(&shorten($$msg{'from'},15))."</a>".
    "</td><td><font face='verdana' size=2><a href='mail.pl?action=read\&folder=$folder\&message=$basename'>".&text2html(&shorten($subj,50))."</a></td>\n".
    "<td><font face='verdana' size=2>".&time2text($$msg{'rcvtime'})."</td>".
    "<td><font face='verdana' size=2>$$msg{'size'}</td></tr>\n";
    $linecount += 1;
  } @cur;

  print
  $buttons.
  "<script>notify();</script>\n".
  "</table></form>";
  print
  "</body>\n".
  "</html>\n";
}

if($action eq "plain") {
  open TMP, $credentials{'home'}."/.Maildir/$folder/cur/".param('message');
  print text2html(join "",<TMP>);
  close TMP;
}

if($action eq "read") {

  my $filename = param('message');
  if($filename =~ /^([^\.][^\/]*)/){ $filename = $1; }
  my $path;
  if($filename =~ /:2,(.*)$/)
  {
    if($1 !~ /S/)
    {
      rename "$credentials{'home'}/.Maildir/$folder/cur/$filename", "$credentials{'home'}/.Maildir/$folder/cur/".$filename."S";
      $filename = $filename."S";
    }
  }

  my @cur;
  my $previous;
  my $next;

  opendir CUR, "$credentials{'home'}/.Maildir/$folder/cur" or die "Unable to open current mail directory";
  @cur = readdir CUR;
  close CUR;

  @cur = grep(/^[^.]/, @cur);
  @cur = sort {uc($b) cmp uc($a)} @cur;

  $path = "$credentials{'home'}/.Maildir/$folder/cur/$filename";

  open FILE, "<$path" or die "Message not found";
 
  print
  "<html><body bgcolor=#000080 onLoad='parent.folders.location = \"?action=folders\";'>\n\n".
  "<script language='javascript'>\n".
  "  function to_folder (myvalue) {\n".
  "    for(x=0; x < document.forms.read.elements.length; x++) {\n".
  "      if(document.forms.read.elements[x].name == 'tofolder') {\n".
  "        document.forms.read.elements[x].value = myvalue;\n".
  "      }\n".
  "    }\n".
  "  }\n".
  "</script>\n\n";

  my @data = <FILE>;
  close FILE;
  my $file = join "", @data;
  $hashcounter = 0;
  $hashdepth = 0;
  undef @hasharray;
  %{@hasharray};

  &parsemime($file);

  my $controls =
  "<tr><td colspan=2><table border=1 cellpadding=0 cellspacing=0>\n".
  "<tr><td width='90%'><font face='verdana' size=2>\n".
  "<input type='submit' name='action' value='Reply'>\n".
  "<input type='submit' name='action' value='Reply All'>\n".
  "<input type='submit' name='action' value='Forward'>\n".
  "<input type='checkbox' name='inline'><font face='verdana' color=#FFFFFF>Forward inline\n".
#  " <input type='hidden' name='message' value='".param('message')." />\n".
  "<input type='submit' name='action' value='Move'> to ".
  "<select name='tofolder' onChange='to_folder(this.value);'>\n";

  opendir my $dh, "$credentials{'home'}/.Maildir";
  my @dirs = readdir $dh;
  closedir $dh;

  @dirs = grep(/^[^.]/ && -d "$credentials{'home'}/.Maildir/$_/cur", @dirs);
  @dirs = sort{$a cmp $b} @dirs;
  grep
  {
    if($_ ne $folder)
    {
      $controls .= "<option value='$_'";
      if($settings{"moveto.".$folder})
      {
        if($settings{"moveto.".$folder} eq $_){ $controls .= " selected='yes'"; }
      }
      elsif($_ eq "Deleted Items" || ($folder eq "Deleted Items" && $_ eq "INBOX")){$controls .= " selected='yes'";}
      $controls .= ">$_</option>\n";
    }
  } @dirs;
  $controls .=
  " </select><br />\n".
  " <input type='submit' name='action' value='Compose'>".
  " <a href='mail.pl?action=plain&folder=$folder&message=$filename'><font color=#FFFF00>Full text</font></a>".
  "</td><td align='left'><font face='verdana' size=2 color=#FFFFFF>\n".
  "<a href='mail.pl?folder=$folder&action=";

  if($previous) {
    $controls = $controls.
    "read&message=$previous";
  }
  else {
    $controls = $controls.
    "inbox";
  }

  $controls = $controls.
  "'><font color=#FFFF00>Previous</font></a>\n".
  " | <a href='mail.pl?folder=$folder&action=";

  if($next) {
    $controls = $controls.
    "read&message=$next";
  }
  else {
    $controls = $controls.
    "inbox";
  }

  $controls = $controls.
  "'><font color=#FFFF00>Next</font></a></td>\n".
  "</tr></table></td></tr>\n";

  $width = "style='width: 10%;'";
  $width2 = "";

  print "<table border=1 width='100%'><tr><td align='left'>\n";

  &headerfolder();

  print
  "<form name='read' method='post' action='mail.pl'>\n".
  "<input type='hidden' name='message' value='$filename'>\n".
  "<input type='hidden' name='folder' value='$folder'>\n".
  "</td></tr>\n".
  $controls.
  "<tr><td align='right' $width><a href='javascript:abopener(\"".&text2href(&text2href($hasharray[0]{'from'}))."\");'><font face='verdana' size=2 color=#FFFFFF><b>From:</b></font></a></td>\n".
  "<td bgcolor=#DDDDDD $width2><font face='verdana' size=2><b>".&text2html($hasharray[0]{'from'})."</b></td></tr>\n".
  "<tr><td align='right' $width><font face='verdana' size=2 color=#FFFFFF><b>Date:</b></td>\n".
  "<td bgcolor=#DDDDDD $width2><font face='verdana' size=2><b>".&text2html($hasharray[0]{'date'})."</b></td></tr>\n".
  "<tr><td align='right' $width><a href='javascript:abopener(\"".&text2href(&text2href($hasharray[0]{'to'}))."\");'><font face='verdana' size=2 color=#FFFFFF><b>To:</b></font></a></td>\n".
  "<td bgcolor=#DDDDDD $width2><font face='verdana' size=2><b>".&text2html($hasharray[0]{'to'})."</b></td></tr>\n".
  "<tr><td align='right' $width><a href='javascript:abopener(\"".&text2href(&text2href($hasharray[0]{'cc'}))."\");'><font face='verdana' size=2 color=#FFFFFF><b>Cc:</b></font></a></td>\n".
  "<td bgcolor=#DDDDDD $width2><font face='verdana' size=2><b>".&text2html($hasharray[0]{'cc'})."</b></td></tr>\n".
  "<tr><td align='right' $width><font face='verdana' size=2 color=#FFFFFF><b>Subject:</b></td>\n".
  "<td bgcolor=#DDDDDD $width2><font face='verdana' size=2><b>".&text2html($hasharray[0]{'subject'})."</b></td></tr>\n";

  my $count = 0;
  mime:  while($count <= $hashcounter) {
    if(lc ($hasharray[$count]{'content-type'}) =~ /^\W*multipart\/alternative/) {
      if(lc ($hasharray[$count+1]{'content-type'}) =~ /^\W*text\/html/) {
        $hasharray[$count+2] = $hasharray[$count+1];
      }
      $count += 2;
      next mime;
    }
    if(lc ($hasharray[$count]{'content-type'}) =~ /^\W*multipart\//i) {
      $count += 1;
      next mime;
    }
    if($hasharray[$count]{'content-type'} =~ /^$/) {
      $hasharray[$count]{'content-type'} = "text/plain";
    }
    if(lc ($hasharray[$count]{'content-disposition'}) =~ /attachment/) {
      $attachment = $hasharray[$count]{'content-disposition'};
      if($attachment =~ /[Ff][Ii][Ll][Ee][Nn][Aa][Mm][Ee]="(.*)"/) {
        $attachment = $1;
      }

      print
      "<tr><td colspan=2><font face='verdana' size=2 color=#FFFFFF>Attachment: &nbsp;\n".
      "<a href='mail.pl?action=down&folder=$folder&message=$filename&file=".
      &text2href($attachment)."'>\n".
      "<font color=#FFFF00>$attachment</font></a></td></tr>\n";
    }
    if(lc ($hasharray[$count]{'content-type'}) =~ /text\//) {
      if(lc ($hasharray[$count]{'content-type'}) =~ /text\/plain/) {
        $hasharray[$count]{'blob'} = &text2html($hasharray[$count]{'blob'});
      }
      else {
        $hasharray[$count]{'blob'} =~ s/<base /<XXbase /gi;
        $hasharray[$count]{'blob'} =~ s/<object/<XXobject/gi;
        $hasharray[$count]{'blob'} =~ s/<applet/<XXapplet/gi;
        $hasharray[$count]{'blob'} =~ s/<script/<XXscript/gi;
      }
      print
      "<tr><td colspan=2 bgcolor=#D0E2FF><font face='verdana' size=2>\n".
      $hasharray[$count]{'blob'}.
      "\n</td></tr>\n";
    }
    if(lc ($hasharray[$count]{'content-type'}) =~ /image\/jpeg/ ||
        lc ($hasharray[$count]{'content-type'}) =~ /image\/gif/ ||
        lc ($hasharray[$count]{'content-type'}) =~ /image\/png/) {
      print
      "<tr><td colspan=2><img src='mail.pl?action=down&disposition=inline&folder=$folder&message=$filename&file=".
      &text2href($attachment)."'></td></tr>\n";
    }
    $count += 1;
  }

  print
  $controls."</form></table>\n";

#  grep {
#while((my $key, my $value) = each %{$_}) {
#  print $key." = ".$value."<br>\n";}

#print "<br><br><br><br>Next Part<br><br>\n";
#  } @hasharray;
  print
  "</body>\n".
  "</html>";

}


if($action eq "Attach File") {
  $mimefile = param('message');

  &splitmail ("$credentials{'home'}/.Maildir/.web/$mimefile");

  my $body = param('body');
  $body =~ s/\r//g;
  $body =~ s/\n$//;
  unlink "$credentials{'home'}/.Maildir/.web/tmp/0.mime";
  open TMP, ">$credentials{'home'}/.Maildir/.web/tmp/1.mime";
  print TMP "Content-type: text/plain\n\n".$body;
  close TMP;

  
  if ((param('attach') eq "") xor (param('attach2') eq "")) {
    my $file;
    if(param('attach') eq "") {
      $file = param('attach2');
    }
    else {
      $file = param('attach');
    }
    my $attach = $file; $attach =~ s/^.*[\\\/]//g;
    my @blob = <$file>;
    close $file;

    my $type = &mimetype($attach);
    my $stamp = "z".time.".".$$;

    my $temp = encode_base64(join "",@blob);

    unlink "/tmp/$stamp.mime";
    open TMP, ">$credentials{'home'}/.Maildir/.web/tmp/$stamp.mime";
    print TMP "Content-type: $type;\n\tname=\"$attach\"\n".
       "Content-Transfer-Encoding: base64\n".
       "Content-Disposition: attachment;\n\tfilename=\"$attach\"\n\n".
       $temp;
    close TMP;
  }

  my $header = "To: ".param('to')."\nCc: ".param('cc')."\nBcc: ".param('bcc').
    "\nSubject: ".param('subject')."\n";

  $mimefile = &joinmail($header);
  $action = "Compose";
}

if($action eq "Forward") {
  my $file = param('message');
  if($file =~ /(.*)/){ $file = $1; }
  my $textyet = "";

  if(!param('inline')) {
   &splitmail ("$credentials{'home'}/.Maildir/$folder/cur/$file");

   my $count = 0;
   while($count <= $hashcounter) {
     if($textyet eq "" && $hasharray[$count]{'depth'} < 2) {
       if(lc($hasharray[$count]{'content-type'}) =~ /^\W*text\/plain/ ||
          $hasharray[$count]{'content-type'} eq "") {
         $textyet = $count;
       }
       if(lc($hasharray[$count]{'content-type'}) =~ /^\W*multipart\/alternative/i) {
         my $tmpcount;
         if(lc ($hasharray[$count+1]{'content-type'}) =~ /^\W*text\/plain/) {
           $tmpcount = $count+1;
         }
         else {
           $tmpcount = $count+2;
         }
         open TMP, ">$credentials{'home'}/.Maildir/.web/tmp/$count.mime";
         while(my ($key, $value) = each %{$hasharray[$tmpcount]}) {
           if($key ne "depth" &&
             $key ne "blob" && $key ne "" && $key ne "rawblob") {
             print TMP $key.":$value\n";
           }
         }
         print TMP "\n".$hasharray[$tmpcount]{'rawblob'};
         close TMP;
         $textyet = $count;
       }
     }
     $count += 1;
   }
  }
  else {
    &rm ("$credentials{'home'}/.Maildir/.web/tmp/", ".*mime");
    link("$credentials{'home'}/.Maildir/$folder/cur/$file","$credentials{'home'}/.Maildir/.web/tmp/5.mime");

    open ORIG, "<$credentials{'home'}/.Maildir/.web/tmp/5.mime";
    my $filedata = join "", <ORIG>;
    close ORIG;

    $hashcounter = 0;
    $hashdepth = 0;
    undef @hasharray;
    %{@hasharray};

    &parsemime($filedata);
  }
  if($textyet eq "") {
    open TMP, ">$credentials{'home'}/.Maildir/.web/tmp/0.mime";
    print TMP "Content-type: text/plain\n\n";
    close TMP;
    $textyet = 0;
  }

  open TMP, "<$credentials{'home'}/.Maildir/.web/tmp/$textyet.mime";
  my $data = join "", <TMP>;
  close TMP;

  my $header = $data;
  $header =~ s/\n\n[^\0]*$//;
  $data =~ s/\n\n/\0\0/;
  $data =~ s/^[^\0]*\0\0//;
  $data = $header."\n\n".&restamp($data);

  open TMP, ">$credentials{'home'}/.Maildir/.web/tmp/$textyet.mime";
  print TMP $data;
  close TMP;

  $hasharray[0]{'subject'} =~ s/^ *//g;
  if(lc($hasharray[0]{'subject'}) !~ /^fw: /) {
    $hasharray[0]{'subject'} = "Fw: $hasharray[0]{'subject'}";
  }

  $mimefile = &joinmail("Subject: $hasharray[0]{'subject'}");
  $action = "Compose";
}

if($action eq "Reply" || $action eq "Reply All") {
  $stamp = time;
  &rm ("$credentials{'home'}/.Maildir/.web/", ".*mime");
  my $file = param('message');
  if($file =~ /(.*)/) {$file = $1;}
  $mimefile = "$stamp.$$.mime";

  open ORIG, "<$credentials{'home'}/.Maildir/$folder/cur/$file";
  my $filedata = join "", <ORIG>;
  close ORIG;

  $hashcounter = 0;
  $hashdepth = 0;
  undef @hasharray;
  %{@hasharray};

  &parsemime($filedata);

  open NEW, ">$credentials{'home'}/.Maildir/.web/$mimefile";
  my $to;
  my $cc;
  if($hasharray[0]{'reply-to'}){
    $hasharray[0]{'from'} = $hasharray[0]{'reply-to'};
  }
  if($action eq "Reply") {
    $to = $hasharray[0]{'from'}; $to =~ s/^\w*//g;
  }
  else {
    $to = $hasharray[0]{'from'}.",  ".$hasharray[0]{'to'};
    $cc = $hasharray[0]{'cc'};
  }
  my $from;
  grep
  {
    if($hasharray[0]{'to'} =~ /(?<![a-z\.\-_])$_/)
    {$from = $_;}
  } @alias;
  my $subject = $hasharray[0]{'subject'}; $subject =~ s/^ *//g;
  if(lc($subject) !~ /^re: /) {$subject = "Re: $subject";}
  my $count = 0;
  my $blob = "";
  findmsg: while (1) {
    if (lc ($hasharray[$count]{'content-type'}) =~ /text\/plain/ ||
        lc ($hasharray[$count]{'content-type'}) =~ /^$/) {
      $blob = $hasharray[$count]{'blob'};
      last findmsg;
    }
    $count += 1;
  }

  $blob = &restamp($blob);

  print NEW "From: $from\nTo: $to\nCc: $cc\nSubject: $subject\nContent-type: text/plain\n\n".
    $blob;
  close NEW;

  $action = "Compose";
}

if($action eq "Compose") {
  my $edityet = 0;
  print
  "<body bgcolor=#000080 onLoad='parent.folders.location = \"?action=folders\";'>\n\n".
  "<script language='javascript'>\n".
  "  function openAddressBook(field, quickcheck) {\n".
  "    if(field == 'to') {\n".
  "      value = document.forms.compose.to.value;\n".
  "    }\n".
  "    else if(field == 'cc') {\n".
  "      value = document.forms.compose.cc.value;\n".
  "    }\n".
  "    else if(field == 'bcc') {\n".
  "      value = document.forms.compose.bcc.value;\n".
  "    }\n".
  "    value = escape(value);\n".
#  "    re = /;/gi;\n".
#  "    value = value.replace(re,\"%3B\");\n".
  "    if(quickcheck == 'yes') {\n".
  "      window.open('mail.pl?action=checkaddressbook&field=' + field + '&quick=' + quickcheck + '&list=' + value, 'CheckNames', 'dependent=yes,menubar=no,scrollbars=yes,resizable=yes,height=25,width=180');\n".
  "    }\n".
  "    else {\n".
  "      window.open('mail.pl?action=addressbook&field=' + field + '&quick=' + quickcheck + '&list=' + value, 'AddressBook', 'dependent=yes,menubar=no,scrollbars=yes,resizable=yes,height=350,width=365');\n".
  "    }\n".
  "  }\n".
  "</script>\n";

  $stamp = time;
  if(!$mimefile) {
    if($mimefile = param('message')) {
    }
    else {
      $mimefile = "$stamp.$$.mime";
      &rm ("$credentials{'home'}/.Maildir/.web/", ".*mime");
    }
  }
  $path = "$credentials{'home'}/.Maildir/.web/$mimefile";

  my @cur;

  opendir CUR, "$credentials{'home'}/.Maildir/$folder/cur" or die "Unable to open current mail directory";
  @cur = readdir CUR;
  close CUR;

  @cur = grep(/^[^.]/, @cur);
  @cur = sort {uc($b) cmp uc($a)} @cur;

  open FILE, "<$path";
  my @data = <FILE>;
  close FILE;
  my $file = join "", @data;
  $hashcounter = 0;
  $hashdepth = 0;
  undef @hasharray;
  %{@hasharray};

  &parsemime($file);

  my $controls =
  "<tr><td colspan=2><table width=100% cellpadding=0 cellspacing=0>\n".
  "<tr><td><font face='verdana' size=2>\n".
  "<input type='submit' name='action' value='Send' onclick='if(document.getElementById(\"msgbody\").value == \"\" || document.getElementById(\"msgto\").value == \"\") return(confirm(\"Some fields are blank.  Really send?\"))'>\n".
  "&nbsp; <input type='button' value='Check' onClick='javascript:openAddressBook(\"to\", \"yes\");'>\n".
#  "<input type='checkbox' name='autocheck' checked><font size=1 color=#FFFFFF>auto\n".
  "</td><td align='right'><input type='file' name='attach'>\n".
  "<input type='submit' name='action' value='Attach File'>\n".
  "</td></tr></table></td></tr>\n";

  $width = "width='70'";
  $width2 = "width=99%";

  my $from;
  if(param('from'))
  { $from = $alias[param('from')]; }
  else
  {
    $from = $hasharray[0]{'from'};
    $from =~ s/^ *//;
    $from =~ s/'/`/g;
    if(!grep($_ eq $from, @alias)){ $from = $settings{'defaultaddress'}; }
  }
  if(!$from){ $from = $credentials{'username'}.'@splitreflection.com'; }
  my $to = $hasharray[0]{'to'};
  $to =~ s/^ *//;
  $to =~ s/'/`/g;
  my $cc = $hasharray[0]{'cc'};
  $cc =~ s/^ *//;
  $cc =~ s/'/`/g;
  my $bcc = $hasharray[0]{'bcc'};
  $bcc =~ s/^ *//;
  $bcc =~ s/'/`/g;
  my $subject = $hasharray[0]{'subject'};
  $subject =~ s/^ *//;
  $subject =~ s/'/`/g;

  print "<table border=1 width=100 height='100%'><tr><td align='center' colspan=10>\n";

  &headerfolder();

  print
  "</td></tr>\n".
  "<form name='compose' method='post' action='mail.pl' enctype='multipart/form-data'>\n".
  "<input type='hidden' name='message' value='$mimefile'>\n".
  "<input type='hidden' name='folder' value='$folder'>\n".
  $controls.
  "<tr><td align='right' $width><font face='verdana' size=2 color=#FFFFFF><b>From:</b></font></td>\n".
  "<td bgcolor=#DDDDDD $width2><select name='from'>\n";

  for(my $x=0; $x < @alias; $x++) {
    print "<option value='$x'";
    if($alias[$x] eq $from)
    { print "selected='selected'"; }
    print ">$alias[$x]\n";
  }

  print
  "</select>";
  
  
  print
  "</td></tr>\n".
  "<tr><td align='right' $width><a href='javascript:openAddressBook(\"to\");'><font face='verdana' size=2 color=#FFFFFF><b>To:</b></font></a></td>\n".
  "<td bgcolor=#DDDDDD $width2><input name='to' type='text' id='msgto' size=60 value='$to'></td></tr>\n".
  "<tr><td align='right' $width><a href='javascript:openAddressBook(\"cc\");'><font face='verdana' size=2 color=#FFFFFF><b>Cc:</b></font></a></td>\n".
  "<td bgcolor=#DDDDDD $width2><input name='cc' type='text' size=60 value='$cc'></td></tr>\n".
  "<tr><td align='right' $width><a href='javascript:openAddressBook(\"bcc\");'><font face='verdana' size=2 color=#FFFFFF><b>Bcc:</b></font></a></td>\n".
  "<td bgcolor=#DDDDDD $width2><input name='bcc' type='text' size=60 value='$bcc'></td></tr>\n".
  "<tr><td align='right' $width><font face='verdana' size=2 color=#FFFFFF><b>Subject:</b></td>\n".
  "<td bgcolor=#DDDDDD $width2><input name='subject' type='text' size=60 value='$subject'></td></tr>\n";

  my $count = 0;
  mime:  while($count <= $hashcounter) {
    if(lc ($hasharray[$count]{'content-type'}) =~ /^\W*multipart\/alternative/) {
      if((lc ($hasharray[$count+1]{'content-type'}) =~ /text\/plain/ &&
         !$edityet) ||
          (lc ($hasharray[$count+1]{'content-type'}) =~ /text\/html/ &&
         $edityet)) {
        $hasharray[$count+2] = $hasharray[$count+1];
      }
      $count += 2;
      next mime;
    }
    if(lc ($hasharray[$count]{'content-type'}) =~ /multipart\//i) {
      $count += 1;
      next mime;
    }
    if($hasharray[$count]{'content-type'} =~ /^$/) {
      $hasharray[$count]{'content-type'} = "text/plain";
    }
    if(lc ($hasharray[$count]{'content-disposition'}) =~ /attachment/) {
      $attachment = $hasharray[$count]{'content-disposition'};
      if($attachment =~ /[Ff][Ii][Ll][Ee][Nn][Aa][Mm][Ee]="(.*)"/) {
        $attachment = $1;
      }

      print
      "<tr><td colspan=2>\n".
      "<font face='verdana' size=2 color=#FFFFFF>Attachment: &nbsp;\n".
      "<a href='mail.pl?action=down&folder=$folder&message=$mimefile&file=".
      &text2href($attachment)."'>\n".
      "<font color=#FFFF00>$attachment</font></a>\n".
      "</td></tr>\n";
      $hasharray[$count]{'content-type'} = 'Attachment';
    }
    if(lc ($hasharray[$count]{'content-type'}) =~ /text\//) {
      if(lc ($hasharray[$count]{'content-type'}) =~ /text\/plain/ &&
        $edityet) {
        $hasharray[$count]{'blob'} = &text2html($hasharray[$count]{'blob'});
      }
      else {
        $hasharray[$count]{'blob'} =~ s/<base /<XXbase /gi;
        $hasharray[$count]{'blob'} =~ s/<object/<XXobject/gi;
        $hasharray[$count]{'blob'} =~ s/<applet/<XXapplet/gi;
        $hasharray[$count]{'blob'} =~ s/<script/<XXscript/gi;
      }
      print
      "<tr><td colspan=2 bgcolor=#D0E2FF height='90%'>";
      if(!$edityet){ print "<textarea name='body' id='msgbody' style='width: 100%; height: 100%;'>\n"; }
      print $hasharray[$count]{'blob'};
      if(!$edityet){ print "</textarea>"; }
      print "</td></tr>\n";
      $edityet = 1;
    }
    $count += 1;
  }

  $controls =~ s/name='attach'/name='attach2'/;

  print
  $controls."</form></table>\n";

  print
  "</body>\n".
  "</html>";

}

if($action eq "down") {
  my $filename = param('message');
  my $attachment = &href2text(param('file'));
  my $path;
  if($filename =~ /:[0-9],/) {$path = "$credentials{'home'}/.Maildir/$folder/cur/$filename";}
  else {$path = "$credentials{'home'}/.Maildir/.web/$filename";}

  open FILE, "<$path";
  my @data = <FILE>;
  close FILE;
  my $file = join "", @data;
  $hashcounter = 0;
  $hashdepth = 0;
  undef @hasharray;
  %{@hasharray};

  &parsemime($file);

  my $contents = "";

  my $count = 0;
  while($count <= $hashcounter) {
    $contents = $contents.$hasharray[$count]{'content-disposition'}."\n";
    grep
    {
      if($_ eq $attachment)
      {
        print
        "Accept-Ranges: bytes\n".
        "Content-Length: ".length($hasharray[$count]{'blob'})."\n".
        "Content-type: $hasharray[$count]{'content-type'}\n".
	"Cache-Control: no-cache\n".
        "Content-disposition: ";
	if(param('disposition')){print param('disposition');}
	else{print $hasharray[$count]{'content-disposition'};}
	print "\n\n".
        $hasharray[$count]{'blob'}."\n";
        exit;
      }
    } (split('"', $hasharray[$count]{'content-disposition'}));
#    if($hasharray[$count]{'content-disposition'} =~ /$attachment/) {
#      print
#      "Accept-Ranges: bytes\n".
#      "Content-Length: ".length($hasharray[$count]{'blob'})."\n".
#      "Content-type: $hasharray[$count]{'content-type'}\n".
#      "Content-disposition: $hasharray[$count]{'content-disposition'}\n\n".
#      $hasharray[$count]{'blob'}."\n";
#      exit;
#    }
    $count += 1;
  }
  #$contents = &text2html($contents);
print "\n\nAttached file \"$attachment\" not found in\n".
  $contents."\n  This is probably a bug, let Calin know.";
}

sub quprint2text {
  my $line = join "", @_;
  $line =~ s/=\n//g;
  while($line =~ /=([0-9A-E][0-9A-E])/) {
    my $char = chr(hex($1));
    $line =~ s/=$1/$char/g;
  }
  return $line;
} 

sub text2href {
  my $percent = sprintf "%%%x", ord "%";
  my $line = join "", @_;
  $line =~ s/%/$percent/g;

  while($line =~ /([^a-zA-Z0-9%\\\]])/){
    my $char = sprintf "%%%x", ord $1;
    $line =~ s/[$1]/$char/g;
  }
return $line;
}

sub href2text {
  my $line = join "", @_;
  while($line =~ /%([0-9A-Fa-f][0-9A-Fa-f])/){
    my $char = chr(hex($1));
    $line =~ s/%$1/$char/g;
  }
return $line;
}

sub text2html {
  my $line = join "", @_;
  $line =~ s/</&lt;/g;
  $line =~ s/>/&gt;/g;
  $line =~ s/"/&quot;/g;
  $line =~ s/  /&nbsp; /g;
  $line =~ s/\t/&nbsp; &nbsp; /g;
  $line =~ s/\n/<br>/g;
  return $line;
}

sub parsemime {
  my $blob = $_[0];
  $blob =~ s/\r//g;
  my $header = $blob;
  $header =~ s/\n\n[^\0]*$//;
  $blob =~ s/\n\n/\0\0/;
  $blob =~ s/^[^\0]*\0\0//;

  $header =~ s/\n[ \t]/    /gs;

  my @attribs = split "\n", $header;
  grep {
    $_ =~ s/:/:::/;
    (my $attr, my $val) = split ":::", $_;
    $hasharray[$hashcounter]{lc($attr)} = $val;
  } @attribs;#? a
  $hasharray[$hashcounter]{'depth'} = $hashdepth;
  $hasharray[$hashcounter]{'rawblob'} = $blob;

  if($hasharray[$hashcounter]{'content-id'} ne "" && $hasharray[$hashcounter]{'content-disposition'} eq "")
  {
    $hasharray[$hashcounter]{'content-id'} =~ s/^\s*//;
    $hasharray[$hashcounter]{'content-disposition'} = "attachment; filename=\"$hasharray[$hashcounter]{'content-id'}\"";
    if(lc($hasharray[$hashcounter]{'content-type'}) !~ /name=/)
    {
      $hasharray[$hashcounter]{'content-type'} .= "; name=\"$hasharray[$hashcounter]{'content-id'}\"";
    }
  }

  if(lc ($hasharray[$hashcounter]{'content-type'}) =~ /name=/) {
    my $name = $hasharray[$hashcounter]{'content-type'};
    my $originalname;
    if($name =~ /^.*name="([^"]*)".*$/i)
    {
      $name = $originalname = $1;
    }

    my $count = 0;
    while($count < $hashcounter) {
      if($hasharray[$count]{'content-type'} =~ /name="$name"/i) {
        ($name =~ s/<+[0-9]+>+\./<$hashcounter>./) ||
        ($name =~ s/\./<$hashcounter>./) ||
        ($name =~ s/<+[0-9]+>+/<$hashcounter>/) ||
        ($name =~ s/$/<$hashcounter>/);
      }
      $count++;
    }

    $hasharray[$hashcounter]{'content-type'} =~ s/$originalname/$name/g;
    $hasharray[$hashcounter]{'content-disposition'} = "attachment; filename=\"$name\"";
  }

  if(lc ($hasharray[$hashcounter]{'content-type'}) =~ /multipart\//i ) {
    my $boundary = $hasharray[$hashcounter]{'content-type'};
    $boundary =~ s/.*boundary="*([^"\s]*).*/$1/;
    my @tmp = split "--".$boundary, $blob;
    pop @tmp; $tmp[0] = "";
    $blob = join $boundary, @tmp;
    $blob =~ s/^$boundary//;
    $blob =~ s/$boundary$//;
    @tmp = split $boundary, $blob;

    grep {
      $hashcounter += 1;
      $hashdepth += 1;
      &parsemime($_);
      $hashdepth -= 1;
    } @tmp;
    
    return;
  }
  if(lc ($hasharray[$hashcounter]{'content-type'}) =~ /message\// ) {
    $hashcounter += 1;
    $hashdepth += 1;
    &parsemime($blob);
    $hashdepth -= 1;
    
    return;
  }
  if(lc ($hasharray[$hashcounter]{'content-transfer-encoding'}) =~ /quoted-printable/) {
    $blob = &quprint2text($blob);
  }
  if(lc ($hasharray[$hashcounter]{'content-transfer-encoding'}) =~ /base64/) {
    if((param('action') eq 'down') || ($hasharray[$hashcounter]{'content-type'} =~ /text\/plain/i)) {
      $blob = decode_base64($blob);
    }
    else {
      $blob = "Unable to display Base64 encoded MIME object.\n";
    }
  }


  $hasharray[$hashcounter]{'blob'} = $blob;
  return;

}

sub splitmail {   # &splitmail("full path to message")
  &rm ("$credentials{'home'}/.Maildir/.web/tmp/", ".*mime");

  open MSG, "<".$_[0];
  my $file = join "", <MSG>;
  close MSG;

  $hashcounter = 0;
  $hashdepth = 0;
  undef @hasharray;
  %{@hasharray};

  &parsemime($file);

  my $textyet = 0;
  my $count = 0;
  while($count <= $hashcounter) {
    if($hasharray[$count]{'depth'} == 0 &&
       (lc($hasharray[$count]{'content-type'}) !~ /multipart/ ||
        lc($hasharray[$count]{'content-type'}) =~ /alternative/)) {
      open RAW, ">$credentials{'home'}/.Maildir/.web/tmp/$count.mime";
      print RAW "Content-type:";
      if($hasharray[$count]{'content-type'}) {
        print RAW $hasharray[$count]{'content-type'};
      }
      else {
        print RAW " text/plain";
      }
      print RAW "\n\n$hasharray[$count]{'rawblob'}";
      close RAW;
      $count += 2;
    }
    else {
      if($hasharray[$count]{'depth'} == 1) {
        open RAW, ">$credentials{'home'}/.Maildir/.web/tmp/$count.mime";
        while(my ($key, $value) = each %{$hasharray[$count]}) {
          if($key ne "depth" &&
             $key ne "blob" && $key ne "" && $key ne "rawblob") {
            print RAW $key.":$value\n";
          }
        }
        print RAW "\n$hasharray[$count]{'rawblob'}";
        close RAW;
      }
    }
    $count += 1;
  }
}

sub joinmail {  # $newfilename = &joinmail($header)
  &rm ("$credentials{'home'}/.Maildir/.web/", ".*mime");
  my $stamp = time;
  my $mimefile = "$stamp.$$.mime";
  open NEW, ">$credentials{'home'}/.Maildir/.web/$mimefile";
  chomp $_[0];
  if($_[0]) { print NEW $_[0]."\n"; }
  
  opendir DIR, "$credentials{'home'}/.Maildir/.web/tmp";
  my @raw = readdir DIR;
  closedir DIR;

  grep {
    if($_ =~ /(.*)/) { $_ = $1; }
  } @raw;

  @raw = grep ( $_ !~ /^\.*$/, @raw);

  @raw = sort {uc($a) cmp uc($b)} @raw;
  if(@raw == 0) {return; }
  if(@raw == 1) {
    open TMP, "<$credentials{'home'}/.Maildir/.web/tmp/$raw[0]";
    my $temp = join "", <TMP>;
    close TMP;
    print NEW $temp;
  }
  else {
    $boundary = "----=_NextPart_$stamp.$$";
    print NEW "Content-type: multipart/mixed;\n".
    "\tboundary=\"$boundary\"\n\n";

    grep {
      print NEW "--$boundary\n";
      open TMP, "<$credentials{'home'}/.Maildir/.web/tmp/$_";
      my $temp = join "", <TMP>;
      close TMP;
      print NEW $temp."\n";
    } @raw;

    print NEW "--$boundary--\n"
  }
  close NEW;
  return $mimefile;
}

sub rm {  # &rm($path, $filespec) Don't forget the trailing /
  opendir DIR, $_[0];
  while (my $line = readdir DIR) {
    if ($line =~ /($_[1])/) { unlink $_[0].$1; }
  }
}

sub restamp {
  my $blob = $_[0];
  $blob =~ s/^/> /g;
  $blob =~ s/\n/\n> /g;
  $blob = "\n\n\n--Original Message--\n".
          "From: $hasharray[0]{'from'}\n".
          "Sent: $hasharray[0]{'date'}\n".
          "To: $hasharray[0]{'to'}\n".
          "Subject: $hasharray[0]{'subject'}\n\n\n".
          $blob;
  return $blob;
}

sub mimetype {  #  &mimetype('filename') will return the content-type
  my $extension = lc($_[0]);
  $extension =~ s/^.*\.//;

  open TYPES, "</etc/mime.types";
  types: while (my $line = <TYPES>) {
    $line = lc($line);
    if($line eq "" || $line =~ /^#/) {next types;}
    $line =~ s/[\t]+/\t/g;
    (my $type, my $ext) = split "\t", $line;
    if($ext =~ /$extension/) {return $type; }
  }
  return "text/plain";

}

sub fixaddresses {   #&fixaddresses(rawlist) returns space delimited nice list
  my $list = $_[0];
  $list =~ s/,/;/g;$list =~ s/ *; */;/g;
  my @newaddresses = split ";", $list;

  for (my $x = 0; $x < @newaddresses; $x++) {
    $newaddresses[$x] =~ s/^[ ;\t\r\n]//g;
    $newaddresses[$x] =~ s/[ ;\t\r\n]$//g;
    $newaddresses[$x] = &findaddress($newaddresses[$x]);
  }

  @newaddresses = sort {uc($a) cmp uc($b)} @newaddresses;
  
  $list = join "; ", @newaddresses;

  return $list;

#  $list =~ s/[\r\n \t]+/ /g;
#  $list =~ s/[,;]//g;
#  $list =~ s/[[<{]/</g;
#  $list =~ s/[\]>}]/>/g;
#
#  my @address = split " ", $list;
#  @address = grep($_ =~ /\@/, @address);
#  grep {
#   $_ =~ s/^.*<//;
#   $_ =~ s/>.*$//;
#  } @address;
#
#  @address = sort {uc($b) cmp uc($a)} @address;
#  $prev = "Nope.";
#  @address = grep($_ ne $prev && ($prev = $_, 1), @address);
#
#  $list = join " ", @address;
#  return $list;
}

sub deletemsg {
  my @delete = split " ", $_[0];

  grep {
    if($_ =~ /(.*)/) { $_ = $1; }
    unlink "$credentials{'home'}/.Maildir/$folder/cur/$_";
  } @delete;

}

sub findaddress {
  my $name = $_[0];
  my $address;
  my $taddress;
  my $tname;
  if($name eq "")
  { return ""; }
  $name =~ s/BUILTIN//g;
  $name =~ s/[^ a-zA-Z0-9@._\-,]//g;
  if($name =~ /([^ ]*@[^ ]*\.[^ ]*)/) {
    $address = $1;
    $name =~ s/$address//g;
  }
  $name =~ s/^ *//;$name =~ s/ *$//;
  $address =~ s/^ *//;$address =~ s/ *$//;

  findaddr: for(my $x = 0; $x < @addresses; $x ++)  {
    my $abname; my $abaddress;
    if($addresses[$x] =~ /"([^"]*)" <([^>]*)>/) {
      $abname = $1;
      $abaddress = $2;
    }
    if(lc($abaddress) eq lc($address)) {
      $name = $abname;
      last 'findaddr';
    }
    if($address eq "") {
      if(lc($abname) eq lc($name)) {
        $name = $abname;
        $address = $abaddress;
        last 'findaddr';
      }
      if($abaddress =~ /^$name/i) {
        $tname = $abname;
        $taddress = $abaddress;
#        last 'findaddr';
      }
      if($abname =~ /^$name/i) {
        $tname = $abname;
        $taddress = $abaddress;
#        last 'findaddr';
      }
    }
  }
  if($taddress ne "" && $address eq ""){
    $address =$taddress;
    $name = $tname;
  }
  if($name eq "" && $address =~ /([^@]*)/) { $name = $1; }

  return ("\"$name\" <$address>");
}

sub loadaddressbook {
  # format: "Rachel Gunn" <pearlybug@yahoo.com>
  undef @addresses;
  @addresses;

  open my $fh, "/etc/group";
  while(my $line = <$fh>)
  {
    if($line =~ /^SRmail:x:[0-9]+:(.*)/)
    {
      my @list = split ",", $1;
      grep
      {
        push @addresses, "\"$_\" <$_\@splitreflection.com>BUILTIN";
      } @list;
    }
  }
  close $fh;

  open TMP, "$credentials{'home'}/.web/addressbook";
  $temp = join "", <TMP>;
  @password = split "\n", $temp;
  close TMP;

  push @addresses, @password;
 
  grep {
    $_ =~ s/^[ ;\t\r\n]//g;
    $_ =~ s/[ ;\t\r\n]$//g;
  } @addresses;
}

sub headerfolder {
  print "<font face='verdana' size=2 color=#FFFFFF>\n".
  "<a href='javascript:abopener(\"\");'><font size=1 color=#FFFF00>Edit AddressBook</font></a>\n</font>\n".
  "<script language='javascript'>\n".
  "  function abopener(list) {\n".
  "    if(document.layers) { list = unescape(list); }\n".
  "    window.open(\"mail.pl?action=addressbook&list=\" + list, \"AddressBook\", \"dependent=yes,menubar=no,scrollbars=yes,resizable=yes,height=350,width=365\");\n".
  "  }\n".
  "</script>\n"
}

sub loadalias 
{
  my %domtag;
  open my $fh, "</var/qmail/control/virtualdomains";
  while(my $line = <$fh>)
  {
    if($line =~ /([^:\s]+):([^:\s]+)/)
    { $domtag{$2} = $1; }
  }
  opendir my $dh, "/var/qmail/alias";
  while(my $file = readdir $dh)
  {
    my $name;
    if($file =~ /\.qmail-(.*)-(.*)/)
    { $name = $2.'@'.$domtag{$1}; }
    elsif($file =~ /\.qmail-(.*)/)
    { $name = $1.'@splitreflection.com'; }
    open my $fh, "</var/qmail/alias/$file";
    my $line = join "", <$fh>;
    chomp $line;
    if($line eq $credentials{'username'} && $file !~ /-default$/)
    { push @alias, $name; }
  }
  @alias = grep($_ ne $credentials{'username'}.'@splitreflection.com', @alias);
  @alias = grep($_, @alias);
  unshift @alias, $credentials{'username'}.'@splitreflection.com';
  @alias = sort
  {
    my ($aa, $bb);
    if($a =~ /@(.*)/){$aa = $1;}
    if($b =~ /@(.*)/){$bb = $1;}
    uc($aa) cmp uc($bb)
  } @alias;
  $prev = "Nope.";
  @alias = grep($_ ne $prev && ($prev = $_, 1), @alias);
}

sub draw_frames
{ # Drawing a frameset!
 return	#"Content-type: text/html\n\n".
        "<html>\n".
	" <head>\n".
	"  <title>Split|Reflection WebMail</title>\n".
	" </head>\n".
	" <frameset cols='200,*'>\n".
	"  <noframe>You must use a browser that can display frames to see this page.</noframe>\n".
	"  <frame src='?action=folders' name='folders' />\n".
	"  <frame src='?action=inbox' name='list' />\n".
	" </frameset>\n".
	"</html>\n";
}

sub draw_folders
{
  return
#  "Content-type: text/html\n\n".
  "<html>\n".
  " <script type='text/javascript' language='javascript' src='/jslib/cookies.js'></script>\n".
  " <script language='javascript'>\n".
  "  function toggle(id)\n".
  "  {\n".
  "    lid = document.getElementById(id + ':lid');\n".
  "    if(lid.innerHTML == '-')\n".
  "    {\n".
  "      collapse(id);\n".
  "    }\n".
  "    else\n".
  "    {\n".
  "      expand(id);\n".
  "    }\n".
  "  }\n".
  "  function collapse(id)\n".
  "  {\n".
  "    setCookie('folder:' + id, 'collapsed');\n".
  "    lid = document.getElementById(id + ':lid');\n".
  "    if(document.getElementById(id))\n".
  "    {\n".
  "      obj = document.getElementById(id).style;\n".
  "      obj.visibility = 'hidden';\n".
  "      obj.position = 'absolute';\n".
  "      lid.innerHTML = '+';\n".
  "    }\n".
  "    else {lid.innerHTML = ''; lid.onClick = '';}\n".
  "  }\n".
  "  function expand(id)\n".
  "  {\n".
  "    setCookie('folder:' + id, 'expanded');\n".
  "    lid = document.getElementById(id + ':lid');\n".
  "    if(document.getElementById(id))\n".
  "    {\n".
  "      obj = document.getElementById(id).style;\n".
  "      obj.visibility = 'inherit';\n".
  "      obj.position = 'relative';\n".
  "      lid.innerHTML = '-';\n".
  "    }\n".
  "    else {lid.innerHTML = ''; lid.onClick = '';}\n".
  "  }\n".
  "  function resetToCookie()\n".
  "  {\n".
  "    dirs = document.getElementsByTagName('tr');\n".
  "    for(var x=0;x<dirs.length;x++)\n".
  "    {\n".
  "      var cval = getCookie('folder:' + dirs[x].id);\n".
  "      if(document.getElementById(dirs[x].id + ':lid'))\n".
  "      {\n".
  "        collapse(dirs[x].id);\n".
  "        if(cval == 'expanded') expand(dirs[x].id);\n".
  "      }\n".
  "    }\n".
  "  }\n".
  " </script>\n".
  " <body onLoad='resetToCookie()'>\n".
  "  <table cellspacing='0'>\n".
  &draw_folder_list("$credentials{'home'}/.Maildir").
  "  </table>\n".
  " </body>\n".
  "</html>\n";
}

sub draw_folder_list
{ # given a folder path, returns html describing it
  my $maildir = shift;
  my $folder = shift;
  my $basename = $folder;
  if($folder =~ /.*\.(.*)/)
  { $basename = $1; }

  opendir my $dh, $maildir;
  my @folders = readdir $dh;
  closedir $dh;

  if($folder)
  {
    @folders = grep($_ =~ /^$folder\.[^\.]*$/ && -d "$maildir/$_/new" && -d "$maildir/$_/cur", @folders);
  }
  else
  {
    @folders = grep($_ !~ /\./ && -d "$maildir/$_/cur" && -d "$maildir/$_/new", @folders);
  }

  @folders = sort { $a cmp $b } @folders;

  my $retval;
  if($folder)
  {
    $retval .=
    "<tr>\n".
    " <td onClick='toggle(\"$maildir/$folder\");' id='$maildir/$folder:lid'></td>\n".
    " <td><a href='?action=inbox&folder=$folder' target='list'>$basename</a>";
    if(my $cnt = &msgcnt("$maildir/$folder"))
    {
      $retval .= "&nbsp;(";
      if(my $new = &msgcnt("$maildir/$folder","[^S]*\$"))
      {
        $retval .= "<b>$new</b>/";
      }
      $retval .= "$cnt)";
    }
    $retval .= "</td>\n".
    "</tr>\n";
  }
  if(@folders)
  {
    $retval .=
    "<tr id='$maildir/$folder'>\n".
    " <td />\n".
    " <td>\n".
    "  <table>\n";
  }
  grep
  {
    &move2cur($_);
    $retval .= &draw_folder_list($maildir, $_);
  } @folders;

  if(@folders)
  {
    $retval .=
    "  </table>\n".
    " </td>\n".
    "</tr>\n";
  }
  return $retval;
}

sub msgcnt
{
  my $folder = shift;
  my $flags = shift;
  opendir my $dh, "$folder/cur";
  my @msgs = readdir $dh;
  closedir $dh;

  @msgs = grep($_ =~ /^[^\.]/, @msgs);
  if($flags)
  {
    @msgs = grep($_ =~ /:2,$flags/, @msgs);
  }
  return @msgs;
}

sub msg_stats
{
  my $msg = shift;
  my %stats;

  if($msg =~ /:2,(.*)$/)
  {
    $stats{'status'} = $1;
  }

  my @stat = stat($msg);
  $stats{'size'} = $stat[7];

  open my $fh, "<$msg";
  my $header;
  while(my $line = <$fh>)
  {
    if($line =~ /^$/){last}

    if($line =~ /^([^:\s]*): *(.*)/)
    {
      $header = lc($1);
      $stats{$header} = $2;
    }

    if($line =~ /^\s+(.*)/)
    {
      $stats{$header} .= " $1";
    }

  }
  close $fh;

  if(!$stats{'temp'} && $stats{'received'} =~ /([0-9]+) (...) ([0-9]{4}) (..):(..):(..) ([+-]?)(..)(..)/)
  {# Received: (qmail 28272 invoked by alias); 27 Apr 2006 03:18:39 -0700
    my $offset = ($9 + ($8 * 60)) * 60;
    if($7 eq "+"){ $offset *= -1; }
    my $sec = $6 % 60;
    my $min = $5 % 60;
    my $hour =$4 % 24;
    my $daysIn = &days_in($3,$monthsh{$2}+1);
    my $mday =(($1-1) % $daysIn)+1;
    #my $mday =(($1-1) % 31)+1;
    $stats{'rcvtime'} = timegm($sec,$min,$hour,$mday,$monthsh{$2},$3) + $offset;
  }

  if(!$stats{'rcvtime'} && $stats{'date'} =~ /^..., ([0-9]+) (...) ([0-9]{4}) ([0-9]+):([0-9]+):([0-9]+)/)
  {# Date: Wed, 14 Jan 2004 12:16:7
    my $sec = $6 % 60;
    my $min = $5 % 60;
    my $hour =$4 % 24;
    my $daysIn = &days_in($3,$monthsh{$2}+1);
    my $mday =(($1-1) % $daysIn)+1;
    #my $mday =(($1-1) % 31)+1;
    $stats{'rcvtime'} = timegm($sec,$min,$hour,$mday,$monthsh{$2},$3);
  }
  if(!$stats{'rcvtime'})
  {
    my @stat = stat($msg);
    $stats{'rcvtime'} = $stat[9] . $stats{'temp'};
  }
  return \%stats;
}

sub shorten
{
  my $string = shift;
  my $len = shift;
  if(length($string) <= $len) { return $string; }
  $len -= 3;
  if($string =~ /(.{$len})/){ return "$1..."; }
}

sub time2text
{
  my $time = shift;
  my @ltime = localtime($time);
  $ltime[5] += 1900;
  my $m = "AM";
  if($ltime[2] >= 12){ $m = "PM"; }
  $ltime[2] %= 12;
  $ltime[2] ||= 12;
  return "$wday[$ltime[6]] $month[$ltime[4]] $ltime[3] $ltime[5] ".sprintf("%02d:%02d:%02d",$ltime[2],$ltime[1],$ltime[0])." $m";
}

sub move2cur
{
  my $folder = shift;
  if($folder =~ /(.*)/){ $folder = $1; }
  if($credentials{'home'} =~ /(.*)/){ $credentials{'home'} = $1; }
  $folder = "$credentials{'home'}/.Maildir/$folder";
  opendir my $dh, "$folder/new";
  while(my $file = readdir $dh)
  {
    if($file =~ /(.*)/){ $file = $1; }
    if($file !~ /^\./)
    {
      my $newfile = $file;
      $newfile =~ s/;.*//g;
      $newfile = $newfile.":2,";
      rename "$folder/new/$file", "$folder/cur/$newfile";
    }
  }
  closedir $dh;
}

sub loadsettings
{
  if(-e "$credentials{'home'}/.web/mail.conf")
  {
    open my $fh, "<$credentials{'home'}/.web/mail.conf";
    while(my $line = <$fh>)
    {
      chomp $line;
      $line =~ s/\s+$//;
      $line =~ s/^\s+//;
      if($line)
      {
        my ($key, $value) = split ": ", $line;
        if($value =~ ", ")
        {
          @{$settings{$key}} = split ", ", $value;
        }
        else
        {
          $settings{$key} = $value;
        }
      }
    }
    close $fh;
  }
}

sub savesettings
{
  my $text = "";
  while(my ($key, $value) = each %settings)
  {
    $text .= "$key: ";
    if(&is_array($value))
    {
      grep
      {
        $text .= "$_, ";
      } @$value;
      $text =~ s/, $/\n/;
    }
    else { $text .= "$value\n"; }
  }
  open my $fh, ">$credentials{'home'}/.web/mail.conf";
  print $fh $text;
  close $fh;
}

sub is_array
{
  my ($ref) = @_;
  # Firstly arrays need to be references, throw
  #  out non-references early.
  return 0 unless ref $ref;

  # Now try and eval a bit of code to treat the
  #  reference as an array.  If it complains
  #  in the 'Not an ARRAY reference' then we're
  #  sure it's not an array, otherwise it was.
  eval
  {
    my $a = @$ref;
  };
  if ($@=~/^Not an ARRAY reference/)
  {
    return 0;
  }
  elsif ($@)
  {
    die "Unexpected error in eval: $@\n";
  }
  else
  {
    return 1;
  }
}
