<?php   

Header("Cache-Control: no-cache");
Header("Pragma: no-cache");
Header("Expires: Sat, Jan 01 2000 01:01:01 GMT");

include("global.inc.php");


// Do this only once
$dnsbl_check = explode(":", SPAM_BLACKLISTS);
$blacklist = array();

function has_attachment($struct)
{
    if(!$struct->parts)
    {
        $att_name = get_att_name($struct);
        if ($att_name != "Unknown")
        {
            return true;
        }
    }
    else
    {
        for($j = 0; $j < count($struct->parts); $j++)
        {
            if (has_attachment($struct->parts[$j]))
                return true;
        }
    }
    return false;
}


function is_blacklisted($ip, $maxtime)
{
    global $dnsbl_check;
    global $blacklist;

    $starttime = time();
    /* $blacklist[$ip] is set to FALSE if $ip is found OK before. This
       will handle multiple emails from the same source much faster. */
    if (isset($blacklist[$ip]))
    {
        return $blacklist[$ip];
    }

    $listed = FALSE;
    if ($ip)
    {
        $quads = explode(".", $ip);
        $rip = $quads[3] . "." . $quads[2] . "." . $quads[1] . "." . $quads[0];
        for ($i=0; $i < count($dnsbl_check); $i++) 
        {
            if (checkdnsrr($rip . "." . $dnsbl_check[$i], "A")) 
            {
                $listed = $dnsbl_check[$i];
                break;
            }
            if ($maxtime and time() - $starttime > $maxtime)
                break;
        }
        /* cache results, as $listed or FALSE */
        $blacklist[$ip] = $listed;
        return $listed;
    }
}


function content()
{
?>
<script type="text/javascript">
<!--
function checkchecked()
{
    flag = false;
    for(i=0 ; i<document.delmov.elements.length; i++)
    {
        if(document.delmov.elements[i].type == "checkbox")
        {
            if(document.delmov.elements[i].checked)
            {
                flag = true;
            }
        }
    }
    if(!flag)
    {
        alert("<?php echo L_SELECT_ERROR ?>");
        document.delmov.tofolder.selectedIndex = 0;
    }
    return flag;
}

function doSubmit()
{
    if (checkchecked()) 
    {
        document.delmov.move.value = 1;
        document.delmov.submit();
    }
}

var newcheckstate = true;

function check_all()
{

    for(i=0 ; i<document.delmov.elements.length; i++)
    {
        if(document.delmov.elements[i].type == "checkbox")
        {
            document.delmov.elements[i].checked = newcheckstate;
        }
    }
    newcheckstate = !newcheckstate;
}
//-->
</script>
<?php
    content_start();
    header_start();
    
    global $folder;
    global $mailbox;
    global $start, $count;
    global $sort;

    header_left();
    global $user;
    echo "$folder - $user - " . PROG_NAME . " - ";

    $issentmail = (($folder == SENT_MAIL) && (SENT_MAIL));
    $numcols = 6;
    if (!DISPLAY_TO_FIELD || $issentmail)
        $numcols--;

    if ($sort=="")
    {
        if ($issentmail)
            $sort = 100 + SORTDATE;
        else
            $sort = 100 + SORTARRIVAL;
    }
    $nummsg = imap_num_msg($mailbox);
    if ($nummsg > 0)
    {
        $s = $sort;
        $r = 0;
        if ($s > 99)
        {
            $s -= 100;
            $r = 1;
        }
        
        $msg_array = imap_sort($mailbox, $s, $r, SE_UID);
    }
    /* Check for spam. This is slow, so lots of optimisation here... */
    flush(); // So the user sees *something*
    $spam_to_move = array();
    $possible_spam = array();
    if (SPAM_BLACKLISTS)
    {
        $starttime = time();
        for ($i=0 ; $i < $nummsg; $i++)
        {
            $msg = imap_headerinfo($mailbox, imap_msgno($mailbox, $msg_array[$i]));
            /* Don't bother if message is already read */
            if ($msg->Unseen == 'U' || $msg->Recent == 'N')
                $new = true;
            else
                $new = false;
            if ($new)
            {
                $rawheaders = imap_fetchbody($mailbox, $msg_array[$i], 0,
                                                FT_UID | FT_PEEK);
                $headers = explode("Received: ", $rawheaders);
                for ($h = 0; $h < count($headers); $h++)
                {
                    if (ereg("^from ([^ ]* )?\(([^ ]* )?\[([0-9\.]*)\]", $headers[$h], $regs))
                    {
                        $fromip = $regs[3];
                        $ret = is_blacklisted($fromip, MAX_SPAMFLAG_SECONDS);
                        if ($ret)
                        {
                            $possible_spam[$msg_array[$i]] = $ret;
                            break;
                        }
                    }
                }
            }
            if ($possible_spam[$msg_array[$i]] and JUNK_MAIL and $folder != JUNK_MAIL)
            {
                $spam_to_move[] = $msg_array[$i];
            }
            if (time() - $starttime > MAX_SPAMFLAG_SECONDS)
                break;
        }
        // If necessary, move spam to another folder.
        if (count($spam_to_move) > 0 and JUNK_MAIL and $folder != JUNK_MAIL)
        {
            $msglist = implode(",", $spam_to_move);
            $moved = imap_mail_move($mailbox, $msglist, JUNK_MAIL, CP_UID);
            if (!$moved)
            {
                // Assume it didn't work because the folder does not exist
                $junk_folder = construct_folder_str(JUNK_MAIL);
                imap_createmailbox($mailbox, IMAP_STR . "$junk_folder");
                // And try again
                $moved = imap_mail_move($mailbox, $msglist, JUNK_MAIL, CP_UID);
            }
            imap_expunge($mailbox);
        }
    }

    // Now, retrieve the list again (it has changed because of move spam)
    if (count($spam_to_move) > 0 and JUNK_MAIL and $folder != JUNK_MAIL)
    {
        $nummsg = imap_num_msg($mailbox);
        if ($nummsg > 0)
        {
            $msg_array = imap_sort($mailbox, $s, $r, SE_UID);
        }
    }
    echo "$nummsg"; 
    $out = " " . ($nummsg == 1 ? L_MESSAGE : L_MESSAGES);
    echo $out;
    header_left_right_end();

    // code to display start to count

    $msg_start = $start ? $start : 1;
    $msg_start--;
    $tmp_count = $count ? $count : MSG_COUNT;
    $tmp_display = $tmp_count > $nummsg ? $nummsg : $tmp_count;
    $nummsg_display = $tmp_display > ($nummsg - $msg_start) ? ($nummsg - $msg_start) : $tmp_display;
?>

<?php

    if (USE_FOLDERS) {
        header_right();
?>
        <form name="switchbox" action="index.php" method="GET">
        <select name=folder onChange="submit()">
        <option value=""><?php echo L_FOLDER_SWITCH ?>:
        <?php list_folders($mailbox); ?>
        </select>
        <noscript>
        <input type="submit" value="<?php echo L_SUBMIT_BTN ?>">
        </noscript>
        </form>
<?php
        header_left_right_end();
        header_right();
        echo "&nbsp;&nbsp;&nbsp;";
        header_left_right_end();
        header_right();
?>
        <form action="folder.php">
        <input type="hidden" name="folder" value="<?php echo $folder ?>">
        <input type="submit" value="<?php echo L_FOLDER_BTN ?>">
        </form>
<?php 
        header_left_right_end();
    }
    header_right();
?>
        <form action="logout.php" method="get">
        <input type="submit" value="<?php echo L_LOGON_BTN ?>">
        </form>
<?php
    header_left_right_end();
    header_end();
    body_start();
    title_start();
    title_left();
    if (WRITE_MESSAGES or DELETE_MESSAGES)
    {
?>

        <form name="delmov" action="action.php" method="GET" onsubmit="return checkchecked()">
        <input type="hidden" name="folder" value="<?php echo "$folder" ?>">
<?php
    }
    global $HTTP_SERVER_VARS;
?>
    <a href="<?php echo htmlspecialchars($HTTP_SERVER_VARS["REQUEST_URI"]) ?>"><img src="images/refresh.gif" alt="@" border="0" height="16" width="21"></a>
<?php 
    title_left_end();
    title_left();
    global $sort;
    echo "<a class=\"intf\" href=\"";
    if ($sort == SORTSUBJECT)
        $s = 100 + SORTSUBJECT;
    else
        $s = SORTSUBJECT;
    echo self_with_param("sort", $s);
    echo "\">";
    echo L_SUBJECT_HDR;
    echo "&nbsp;";
    if ($sort == SORTSUBJECT)
        echo "<img src=\"images/ascending.gif\" alt=\"^\" width=\"8\" height=\"8\" border=\"0\">";
    if ($sort == 100 + SORTSUBJECT)
        echo "<img src=\"images/descending.gif\" alt=\"v\" width=\"8\" height=\"8\" border=\"0\">";
    echo "</a>";
    title_left_end();
    if (!$issentmail)
    {
        title_left();
        echo "<a class=\"intf\" href=\"";
        if ($sort == SORTFROM)
            $s = 100 + SORTFROM;
        else
            $s = SORTFROM;
        echo self_with_param("sort", $s);
        echo "\">";
        echo L_FROM_HDR;
        echo "&nbsp;";
        if ($sort == SORTFROM)
            echo "<img src=\"images/ascending.gif\" alt=\"^\" width=\"8\" height=\"8\" border=\"0\">";
        if ($sort == 100 + SORTFROM)
            echo "<img src=\"images/descending.gif\" alt=\"v\" width=\"8\" height=\"8\" border=\"0\">";
        echo "</a>";
        title_left_end();
    }
    if (DISPLAY_TO_FIELD || $issentmail)
    {
        title_left();
        echo "<a class=\"intf\" href=\"";
        if ($sort == SORTTO)
            $s = 100 + SORTTO;
        else
            $s = SORTTO;
        echo self_with_param("sort", $s);
        echo "\">";
        echo L_TO_HDR;
        echo "&nbsp;";
        if ($sort == SORTTO)
            echo "<img src=\"images/ascending.gif\" alt=\"^\" width=\"8\" height=\"8\" border=\"0\">";
        if ($sort == 100 + SORTTO)
            echo "<img src=\"images/descending.gif\" alt=\"v\" width=\"8\" height=\"8\" border=\"0\">";
        echo "</a>";
        title_left_end();
    }
    title_left();
    echo "<a class=\"intf\" href=\"";
    if ($issentmail)
    {
        if ($sort == SORTDATE)
            $s = 100 + SORTDATE;
        else
            $s = SORTDATE;
    }
    else
    {
        if ($sort == SORTARRIVAL)
            $s = 100 + SORTARRIVAL;
        else
            $s = SORTARRIVAL;
    }
    echo self_with_param("sort", $s);
    echo "\">";
    echo $issentmail ? L_SENT_HDR : L_RECEIVED_HDR;
    echo "&nbsp;";
    if ($issentmail)
    {
        if ($sort == SORTDATE)
            echo "<img src=\"images/ascending.gif\" alt=\"^\" width=\"8\" height=\"8\" border=\"0\">";
        if ($sort == 100 + SORTDATE)
            echo "<img src=\"images/descending.gif\" alt=\"v\" width=\"8\" height=\"8\" border=\"0\">";
    }
    else
    {
        if ($sort == SORTARRIVAL)
            echo "<img src=\"images/ascending.gif\" alt=\"^\" width=\"8\" height=\"8\" border=\"0\">";
        if ($sort == 100 + SORTARRIVAL)
            echo "<img src=\"images/descending.gif\" alt=\"v\" width=\"8\" height=\"8\" border=\"0\">";
    }
    echo "</a>";
    title_left_end();
    title_left();
    echo "<a class=\"intf\" href=\"";
    if ($sort == SORTSIZE)
        $s = 100 + SORTSIZE;
    else
        $s = SORTSIZE;
    echo self_with_param("sort", $s);
    echo "\">";
    echo L_SIZE_HDR;
    echo "&nbsp;";
    if ($sort == SORTSIZE)
        echo "<img src=\"images/ascending.gif\" alt=\"^\" width=\"8\" height=\"8\" border=\"0\">";
    if ($sort == 100 + SORTSIZE)
        echo "<img src=\"images/descending.gif\" alt=\"v\" width=\"8\" height=\"8\" border=\"0\">";
    echo "</a>";
    title_left_end();
    title_end();

    $flipflop = 0;
    $nummsgdisplayed = 0;
    global $select;

    for( $i=$msg_start ; $i < $msg_start + $nummsg_display ; $i++ )
    {

        $struct = imap_fetchstructure($mailbox, $msg_array[$i], FT_UID);


        $attach = has_attachment($struct) ? "&nbsp;@" : "";
        $msg = imap_headerinfo($mailbox, imap_msgno($mailbox, $msg_array[$i]));
        $subject = !$msg->Subject ? L_NO_SUBJECT : $msg->Subject;
        $subject = decode_header_string($subject);

        $ksize = round($msg->Size/1024);
        $size = $msg->Size > 1024 ? "$ksize KB" : $msg->Size;

        if($flipflop == 0)
        {
            $bg = "rowon";
            $flipflop = 1;
        }
        else
        {
            $bg = "rowoff";
            $flipflop = 0;
        }
        if ($msg->Unseen == 'U' || $msg->Recent == 'N')
            $new = true;
        else
            $new = false;
        if ($new)
            $bg .= "new";
        // Let's start displaying.
        $nummsgdisplayed++;
        body_row('class="' . $bg . '"');
        body_left();
        if (WRITE_MESSAGES or DELETE_MESSAGES)
        {
            echo "<input type=\"checkbox\" name=\"msglist[]\" value=\"$msg_array[$i]\"";
            if ($select=="all")
                echo " checked=\"checked\"";
            if (/*$select=="spam" &&*/ $possible_spam[$msg_array[$i]])
                echo " checked=\"checked\"";
            echo ">";
        }
        body_left_end();
        body_left();
        if ($possible_spam[$msg_array[$i]])
            print "<font color=\"red\">***" . L_JUNK_MAIL . "*** </font>";
        echo "<a class=\"intf\" href=\"message.php?folder=" . urlencode($folder) . "&amp;msglist[]=$msg_array[$i]\">";
        echo $subject;
        echo "</a>$attach\n";
        if ($possible_spam[$msg_array[$i]])
            print "<br><font color=\"red\"><small>(" 
                    . $possible_spam[$msg_array[$i]] . ")</small></font>";
        body_left_end();
        if(!$issentmail)
        {
            body_left();
            if($msg->from)
                echo make_clickable_list($msg->from, $folder, MAX_DISPLAY_ADDRESSES);
            else
                echo L_NO_FROM;
            body_left_end();
        }
        if ($issentmail || DISPLAY_TO_FIELD)
        {
            body_left();
            if ($msg->to)
                echo make_clickable_list($msg->to, $folder, MAX_DISPLAY_ADDRESSES);
            else
                echo L_NO_TO;
            body_left_end();
        }
        body_left('nowrap="nowrap"');
        echo date(L_DATE_FORMAT, $msg->udate);
        body_left_end();
        body_left('nowrap="nowrap" align="right"');
        echo $size;
        body_left_end();
        body_row_end();
    }
    if ($nummsgdisplayed == 0)
    {
        body_row('class="rowon"');
        body_left('colspan="' . $numcols . '"');
        echo L_FOLDER_EMPTY;
        body_left_end();
        body_row_end();
    }


    title_start();
    title_left();
    if (WRITE_MESSAGES or DELETE_MESSAGES)
    {
?>
<script type="text/javascript">
    document.write('<a href="javascript:check_all()"><img src="images/check.gif" alt="V" border="0" height="16" width="21"></a>');
</script>
<noscript>
<?php

        if ($select!="all")
            $url = self_with_param("select", "all");
        else
            $url = self_with_param("select", "");
        echo "<a href=\"$url\"><img src=\"images/check.gif\" alt=\"V\" border=\"0\" height=\"16\" width=\"21\"></a>";
?>
</noscript>
<?php
        /*
        if (SPAM_BLACKLISTS)
        {
            if ($select!="spam")
            {
                $url = self_with_param("select", "spam");
                echo "<br><a class=\"intf\" href=\"$url\">spam</a>";
            }
        }
        */
    }
    title_left_end();
    $colsleft = $numcols-1;
    title_left('colspan="' . $colsleft . '"');

    $location = $msg_start + 1;

    for($k=1; $k <= $nummsg; $k += $tmp_count)
    {
        $end_tmp = $k + $tmp_count - 1;
        $end = $end_tmp >= $nummsg ? $nummsg : $end_tmp;

        $newlink = "<a class=\"msg\" href=\"index.php?folder=$folder&amp;sort=$sort&amp;start=$k&amp;count=$tmp_count\">";
        $link = (($k <= $location) and ($location <= $end)) ?  "" : $newlink;
        echo $link . "[$k-" . $end;
        $link = (($k <= $location) and ($location <= $end)) ?  "" : "</a>";
        echo "]" . $link;

        echo "&nbsp;&nbsp; ";
    }
    $numspam = count($spam_to_move);
    if (SPAM_BLACKLISTS and JUNK_MAIL and $folder != JUNK_MAIL)
    {
        print "<small>" . L_JUNK_MAIL . ": $numspam "
                . ($numspam == 1 ? L_MESSAGE : L_MESSAGES)
                . " -&gt; <a class=\"intf\" href=\"index.php?folder=" 
                . JUNK_MAIL . "\">" . JUNK_MAIL . "</a></small>";
    }

    title_left_end();
    title_end();
    body_end();

    header_start();
    header_left();
    if (USE_FOLDERS) {
?>        
        <select name="tofolder" onChange="doSubmit()">
        <option><?php echo L_FOLDER_MOVE ?>
        <?php list_folders($mailbox); ?>
        </select>
        <script type="text/javascript">
        <!--
            // A var named 'move' must always exist.
            document.write('<input type="hidden" name="move" value="">');
        //-->
        </script>
        <noscript>
            <input type="submit" name="move" value="<?php echo L_SUBMIT_BTN ?>">
        </noscript>
<?php
    }
    echo "&nbsp;";
    header_left_right_end();
    if (MULTIMESSAGE)
    {
        header_right();
?>
        <input type="submit" name="readall" value="<?php echo L_READ_BTN ?>">
<?php
        header_left_right_end();
    }
    if (DELETE_MESSAGES)
    {
        header_right();
?>
        <input type="submit" name="delall" value="<?php echo L_DELETE_BTN ?>">
        </form>
<?php
        header_left_right_end();
    }
    if (WRITE_MESSAGES)
    {
        header_right();
?>
        <form action="compose.php" method="get">
        <input type="hidden" name="folder" value="<?php echo $folder ?>">
        <input type="submit" value="<?php echo L_COMPOSE_BTN ?>">
        </form>
<?php
        header_left_right_end();
    }
    header_end();
    content_end();
    imap_close($mailbox); 
}

/* MAIN */
include(HTML_TEMPLATE);

?>
