<?php

// shouldn't have to modify anything in this file...
define('VERSION', "AeroMail 2.41");

if (!file_exists('config.inc.php') or filesize('config.inc.php') < 6)
{
    header("Location: configure.php");
    exit;
}

include("config.inc.php");
include(THEME_FILE);
include(LANGUAGE_FILE);


if (USE_COOKIES)
{
    session_name("AeroMail");
    session_save_path(SESSION_SAVE_PATH);
    session_start();
}

define('FILTER', IMAP_SERVER_TYPE == "Cyrus" ? "INBOX" : PROG_DIR);
define('IMAP_STR', "{".IMAP_SERVER.":".IMAP_PORT.IMAP_OPTS."}");

function mailbox_log_in($user, $pass, $folder)
{
    error_reporting(error_reporting() - 2);

    $folder = $folder == "INBOX" ? "INBOX" : construct_folder_str($folder);
    $mbox = imap_open(IMAP_STR . "$folder", $user , $pass);

    error_reporting(error_reporting() + 2);
    return $mbox;
}

function construct_folder_str( $folder )
{
    // Cyrus style: INBOX.Junque
    // UWash style: ./aeromail/Junque

    $folder_str = IMAP_SERVER_TYPE == "Cyrus" ? "INBOX." . $folder : PROG_DIR . $folder;
    return $folder_str;
}

function deconstruct_folder_str( $folder )
{
    // Cyrus style: INBOX.Junque
    // UWash style: ./aeromail/Junque

    $srch_str = IMAP_SERVER_TYPE == "Cyrus" ? "INBOX." : PROG_DIR;

    $folder_str = substr($folder, strlen($srch_str), strlen($folder));

    return $folder_str;
}

function decode_header_string($hed_str)
{
    $output = "";
              
    if($hed_str)
    {
        $element=imap_mime_header_decode($hed_str);
        for($i=0; $i < count($element); $i++) {
            if ($element[$i]->charset == "default")
                $output .= $element[$i]->text;
            else
            {
                $output .= make_utf8($element[$i]->text, $element[$i]->charset);
            }
        }
    }
    return $output;
}

function make_address_list($header_arr)
{
    $out = array();
    if (is_array($header_arr) && count($header_arr)) 
    {
        foreach ($header_arr as $adr)
        {
            if ($adr)
            {
                $outaddr = imap_rfc822_write_address($adr->mailbox, 
                            $adr->host, $adr->personal);
                // remove trailing @
                if (!$adr->host)
                    $outaddr = str_replace("@", "", $outaddr);
                    
                $out[] = $outaddr;
            }
        }
    }
    return $out;
}

function make_formaddress_list($header_arr)
{
    $list = make_address_list($header_arr);
    $l = array();
    foreach ($list as $adr)
    {
        $l[] = htmlentities(decode_header_string($adr));
    }
    return implode(", ", $l);
}


function make_clickable_list($header_arr, $folder, $maxaddresses=0)
{    
    $addrcounter = 0;
    $list = make_address_list($header_arr);
    $l = array();
    foreach ($list as $adr)
    {
        $linkdisplay = decode_header_string($adr);
        if (!DISPLAY_FULL_ADDR)
        {
            // Be caraful. First check John <john@doe.com>
            if (ereg("^(.+)[[:blank:]]+<(.+)>$", $linkdisplay, $regs))
            {
                $linkdisplay = $regs[1];
                // Remove quotes if any
                if (ereg("^\"(.*)\"$", $linkdisplay, $regs))
                    $linkdisplay = $regs[1];
            }
            // Now check <john@doe.com>
            if (ereg("^[[:blank:]]*<(.+)>[[:blank:]]*$", $linkdisplay, $regs))
                $linkdisplay = $regs[1];
            // else we leave it as it is.
        }
        $linkdisplay = htmlspecialchars($linkdisplay);
        if (WRITE_MESSAGES)
            $addr = "<a class=\"intf\" href=\"compose.php?folder="
                    . urlencode($folder) 
                    . "&amp;to=" . urlencode($adr) . "\">"
                    . $linkdisplay
                    . "</a>";
        else
            $addr = $linkdisplay;
        $l[] = $addr;
        if (++$addrcounter == $maxaddresses)
        {
            if (count($list) > $maxaddresses)
                $l[] = "...";
            break;
        }
    }
    return implode(", ", $l);
}

function list_folders($mailbox)
{
    $mailboxes = imap_listmailbox($mailbox, IMAP_STR, FILTER . "*");
    if($mailboxes)
    {
        sort($mailboxes);
        $num_boxes = count($mailboxes);
        if (FILTER != "INBOX" and !NO_INBOX_EXPLICIT) { echo "<option>INBOX"; }
        for ($index = 0; $index < $num_boxes; $index++)
        {
            $nm = substr($mailboxes[$index], strrpos($mailboxes[$index], "}") + 1, strlen($mailboxes[$index]));
            echo "<option>";
            if ($nm != "INBOX")
            {
                echo deconstruct_folder_str($nm);
            }
            else
            {
                echo "INBOX";
            }
            echo "\n";
        }
    }
    else
    {
        echo "<option>INBOX";
    }
}

function get_mime_encoding($de_part)
{
    switch ($de_part->encoding)
    {
        case ENCBASE64:         $mime_encoding = "base64"; break;
        case ENCQUOTEDPRINTABLE:    $mime_encoding = "qprint"; break;
        case ENCOTHER:          $mime_encoding = "other"; break;
        default:            $mime_encoding = "other";
    }
    return $mime_encoding;
}

function get_charset($de_part)
{
    $charset = "US-ASCII";
    for ($i = 0; $i < count($de_part->parameters); $i++)
    {
        $param = $de_part->parameters[$i];
        if ($param->attribute == "CHARSET")
        {
            $charset = $param->value;
        }
    }
    return $charset;
}


function make_utf8($str, $charset)
{
    /* Try, but at least return something! */
    if (function_exists('iconv')) 
    {
        if (!$charset)
            $charset="US-ASCII";
        $charset = strtoupper($charset);
        /* Do some processing to catch sloppy charsets */
        $charset = ereg_replace("^WINDOWS-", "CP", $charset);
        /* Found in the wild: "CHINESEBIG5" */
        $charset = ereg_replace("^CHINESE", "", $charset);
        $out = iconv($charset, "UTF-8", $str);
        if ($out)
            return $out;
    }
    return $str;
}

function get_att_name($de_part)
{
    $att_name = 0;
    $att_filename = "Unknown";
    for ($i = 0; $i < count($de_part->parameters); $i++)
    {
        $param = $de_part->parameters[$i];
        if ($param->attribute == "NAME")
        {
            $att_name = $param->value;
        }
    }
    for ($i = 0; $i < count($de_part->dparameters); $i++)
    {
        $param = $de_part->dparameters[$i];
        if ($param->attribute == "FILENAME")
        {
            $att_filename = $param->value;
        }
    }
    if ($att_name)
        return $att_name;
    else
        return $att_filename;
}

/* imap_qprint doesn't handle soft returns correctly */
function my_qprint($dsp)
{
    $dsp = str_replace("=\r\n", "", $dsp);
    $dsp = quoted_printable_decode($dsp);
    return $dsp;
}

function self_with_param($params, $values)
{
    global $HTTP_SERVER_VARS;
    // params and values can be a string or an array
    if (is_array($params))
    {
        $p = $params;
        $v = $values;
    }
    else
    {
        $p = array($params);
        $v = array($values);
    }
    $url = $HTTP_SERVER_VARS["REQUEST_URI"];
    for ($i = 0; $i < count($p); $i++)
    {
        $paramname = $p[$i];
        $value = $v[$i];
        /* first strip out the old value of $paramname */
        $url = ereg_replace("\&$paramname=[^&]*", "", $url);
        $url = ereg_replace("$paramname=[^&]*\&", "", $url);
        $url = ereg_replace("\?$paramname=[^&]*", "", $url);
        /* Then insert the new one */
        /* Note: $value != "" is FALSE when $value is the string "0". You gotta 
           love PHP... */
        if ($value != "" or $value == "0")
        {
            if (strpos($url, "?"))
                $url .= "&";
            else
                $url .= "?";
            $url .= "$paramname=$value";
        }
    }
    return htmlspecialchars($url);
}

function login_prompt()
{
    if (USE_COOKIES)
    {
        Header("Location: login.php");
    }
    else
    {
        Header("WWW-Authenticate: Basic realm=\"" . PROG_NAME . "\"");
        Header("HTTP/1.0 401 Unauthorized");
        echo "<meta HTTP-EQUIV=\"Refresh\" CONTENT=\"0; URL= " . SERVER_REDIR . "\">";
    }
    exit;
}

include('layout.inc.php');

if (!USE_COOKIES)
{
    $user = $PHP_AUTH_USER;
    $pass = $PHP_AUTH_PW;
}

if ((!$user) or (!$pass) or ($time > time()))
{
    login_prompt();
} 
else
{ 
    $folder = !$folder ? "INBOX" : $folder;
    $mailbox = mailbox_log_in($user, $pass, $folder);

    if(!$mailbox)
    {
        login_prompt();
    }
} 

?>
