<?php

include("global.inc.php");

if (!DELETE_MESSAGES and ($delall or $delete))
    exit;
if (!USE_FOLDERS and $move)
    exit;

if (($delall || $delete) && TRASH && $folder != TRASH)
{
    $tofolder = TRASH;
    $delall = 0;
    $delete = 0;
    $move = 1;
}

$tofolder = $tofolder == "INBOX" ? "INBOX" : construct_folder_str($tofolder);

if ($move)
{
        $msgs = $msgnum ? $msgnum : implode($msglist, ",");
        if(!imap_mail_move($mailbox, $msgs, $tofolder, CP_UID))
        {
            echo "ERROR<br>";
        }
}

if ($delall)
{
        for($i = 0; $i < count($msglist); $i++)
        {
            imap_delete($mailbox, $msglist[$i], FT_UID);
        }
}

if ($delete)
{
        imap_delete($mailbox, $msgnum, FT_UID);
}

if ($readall)
{
    $url = "message.php?folder=" . urlencode($folder);
    foreach ($msglist as $m)   
    {
        $url .= "&msglist[]=$m";
    }
    header("Location: $url");
    exit;
}

imap_expunge($mailbox);
imap_close($mailbox);

/*
    If we come from index.php, we have a messages list.
    If we come from message.php, we have a messages list and a message num.
    If msglist consists of only one item, that was deleted/moved right here
    so we can't go back to message.php.
*/
if (isset($msgnum) and is_array($msglist) and count($msglist) > 1)
{
    $url = "message.php?folder=" . urlencode($folder);
    foreach ($msglist as $m)   
    {
        if ($m != $msgnum)
        {
            $url .= "&msglist[]=$m";
        }
        // Else we just deleted/moved it!
    }
    header("Location: $url");  
}
else
{
    header("Location: index.php?folder=" . urlencode($folder));  
}

?>


