function receiveMessages()
{
    $OUTPUT = "";
    // retrieve all accounts this user has access to
    $sql = "SELECT account_id, account_name, server_host, server_user, server_pass, leave_msgs\r\n\t\t\tFROM mail_accounts\r\n\t\t\tWHERE ( username = '******' OR \"public\" = '1' ) AND active = '1'\r\n\r\n\t\tUNION\r\n\t\tSELECT mail_accounts.account_id, account_name, server_host, server_user, server_pass, leave_msgs\r\n\t\t\tFROM mail_accounts,mail_priv_accounts\r\n\t\t\tWHERE ( mail_accounts.account_id = mail_priv_accounts.account_id\r\n\t\t\t\tAND priv_owner = '" . USER_NAME . "' ) AND active = '1'";
    $rslt = db_exec($sql);
    // go through each account and retrieve the messages
    $pop =& new clsPOPMail();
    $msg =& new clsMailMsg();
    if (pg_num_rows($rslt) <= 0) {
        $OUTPUT .= "No active accounts found.";
    } else {
        while ($account = pg_fetch_array($rslt)) {
            $accid = $account["account_id"];
            $accname = $account["account_name"];
            $host = $account["server_host"];
            $port = 110;
            $user = $account["server_user"];
            $pass = $account["server_pass"];
            $leave_msgs = $account["leave_msgs"];
            // if the retrieveMessages returned true, it means an error has been found.
            // Print and continue with next server.
            if ($connection = $pop->retrieveMessages($host, $port, $user, $pass, $leave_msgs)) {
                $OUTPUT .= "({$accname}) {$connection}<br>";
                continue;
            }
            // get each received message, pass to processor, and store in database
            $msgcount = 0;
            while ($buf = $pop->enumGetMessage()) {
                // get the data to be inserted
                if ($msg->processMessage($buf) == FALSE) {
                    continue;
                }
                $type_id = getMsgType($msg->type);
                // data and header is base64_encoded so weird characters can also be stored
                $data = base64_encode($buf);
                // insert body into Cubit
                if (!pglib_transaction("BEGIN")) {
                    continue;
                }
                $rslt = db_exec("INSERT INTO mail_msgbodies (type_id, data)\r\n\t\t\t\t\tVALUES( {$type_id}, '{$data}' )");
                if (pg_cmdtuples($rslt) <= 0) {
                    continue;
                }
                $msgbody_id = pglib_lastid("mail_msgbodies", "msgbody_id");
                if (!pglib_transaction("COMMIT")) {
                    continue;
                }
                // get the folder this message should be inserted into
                $rslt = db_exec("SELECT fid_inbox FROM mail_account_settings WHERE account_id={$accid}");
                if (pg_num_rows($rslt) > 0) {
                    $infolder = pg_fetch_result($rslt, 0, 0);
                } else {
                    $infolder = 0;
                }
                // move to no folder, but store, this way all is not lost
                // check if the user even MAY add to this folder (account of folder they have
                // privileges to, folder.username = their's, they have privileges to this folder
                // it is a public folder, public account
                $sql = "\r\n\t\t\t\tSELECT 1 FROM mail_folders WHERE folder_id = {$infolder}\r\n\t\t\t\t\tAND (\"public\" = '1' OR username='******')\r\n\t\t\t\tUNION\r\n\t\t\t\tSELECT 1 FROM mail_accounts, mail_folders WHERE folder_id = {$infolder}\r\n\t\t\t\t\tAND mail_accounts.account_id=mail_folders.account_id\r\n\t\t\t\t\tAND (mail_accounts.username = '******' OR mail_accounts.\"public\" = '1')\r\n\t\t\t\tUNION\r\n\t\t\t\tSELECT 1 FROM mail_priv_accounts, mail_folders WHERE folder_id = {$infolder}\r\n\t\t\t\t\tAND mail_priv_accounts.account_id = mail_folders.account_id\r\n\t\t\t\t\tAND priv_owner = '" . USER_NAME . "'\r\n\t\t\t\tUNION\r\n\t\t\t\tSELECT 1 FROM mail_priv_folders WHERE folder_id = {$infolder}\r\n\t\t\t\t\tAND priv_owner = '" . USER_NAME . "'";
                $rslt = db_exec($sql);
                if (pg_num_rows($rslt) <= 0) {
                    continue;
                }
                // you may not add to this folder (inbox folder for account);
                // insert the message linked to body
                $sql = " INSERT INTO mail_messages ( account_id, folder_id, subject, add_from, add_to, add_cc,\r\n\t\t\t\t\t\t\tadd_bcc, priority, attachments, msgbody_id, flag, date)\r\n\t\t\t\t\t\tVALUES ( '{$accid}', '{$infolder}', '{$msg->subject}', '{$msg->from}', '{$msg->to}',\r\n\t\t\t\t\t\t\t'{$msg->cc}', '{$msg->bcc}', '1', '0', '{$msgbody_id}', '1', CURRENT_TIMESTAMP)";
                $rslt = db_exec($sql);
                if (pg_cmdtuples($rslt) <= 0) {
                    continue;
                }
                $msgcount++;
            }
            $OUTPUT .= "Received {$msgcount} messages for {$accname}.<br>";
        }
    }
    return $OUTPUT;
}
function sendMsg()
{
    global $_GET;
    if (isset($_GET["save"])) {
        return saveMsg($_GET);
    }
    $v =& new validate();
    $OUTPUT = "";
    // restore the variables
    extract($_GET);
    extract($_FILES);
    // check if account is valid
    if (isset($_GET["aid"])) {
        if (!$v->isOk($_GET["aid"], "num", 0, 9, "")) {
            return "Invalid account number specified";
        }
        // check if you may send mail from here
        $sql = "SELECT 1\n\t\t\t FROM mail_accounts WHERE ( username='******' OR \"public\"='1' )\n\t\t\t \tAND enable_smtp = '1' AND account_id='{$aid}'\n\n\t\tUNION\n\t\tSELECT 1\n\t\t\tFROM mail_accounts,mail_priv_accounts\n\t\t\tWHERE mail_accounts.account_id = mail_priv_accounts.account_id AND\n\t\t\tmail_accounts.account_id='{$aid}'\n\t\t\t\tAND priv_owner = '" . USER_NAME . "' AND enable_smtp = '1'";
        $rslt = db_exec($sql);
        if (pg_num_rows($rslt) <= 0) {
            return "You may not send mail from this account<br>";
        }
    } else {
        return "No account specified<br>";
    }
    if ($lead_id) {
        $sql = "SELECT email FROM cubit.cons WHERE id='{$lead_id}'";
        $rslt = db_exec($sql) or errDie("Unable to retrieve email address for contact.");
        $email = pg_fetch_result($rslt, 0);
        $_GET["send_to"] = $email;
    }
    if (!isset($_GET["send_to"])) {
        $send_to = "";
    }
    if (!isset($_GET["send_bcc"])) {
        $send_bcc = "";
    }
    if (!isset($_GET["send_cc"])) {
        $send_cc = "";
    }
    if (!isset($_GET["subject"])) {
        $subject = "";
    }
    if (!isset($_FILES["attachment"])) {
        $attachment = "";
    }
    if (!isset($_GET["body"])) {
        $body = "";
    }
    $v->resetErrors();
    // $v->isOK($send_to, "email", 1, 255, "Invalid recipient.");
    //if ( strlen($send_to) <= 0 ) $v->addError("", "Invalid recipient");
    // $v->isOK($send_cc, "email", 0, 255, "Invalid cc recipient.");
    // $v->isOK($send_bcc, "email", 0, 255, "Invalid bcc recipient.");
    //if ( ! $v->isOK($bodydata, "string", 1, 255, "Invalid text in body.") ) {
    //	$_GET["body"] = htmlspecialchars($body); // makes sure we dont get cross site scripting
    //}
    // ok now print errors if any
    if ($v->isError()) {
        $errs = $v->getErrors();
        foreach ($errs as $arr => $errval) {
            $OUTPUT .= "{$errval['msg']}<br>";
        }
        $OUTPUT .= writeMsg();
        return $OUTPUT;
    }
    $bodydata = "<html>{$bodydata}</html>";
    // get the smtp data
    $rslt = db_exec("SELECT smtp_from, smtp_reply, signature, smtp_host, smtp_auth, smtp_user, smtp_pass\n\t\t\t\t\tFROM mail_accounts WHERE account_id={$_GET['aid']}");
    $smtp_data = pg_fetch_array($rslt);
    // build msg body
    $body = "{$body}\n\n{$smtp_data['signature']}";
    // determine whether or not here is an attachment
    $has_attachment = is_uploaded_file($attachment["tmp_name"]);
    // modify message and create content_type header depending on whether or not an attachment was posted
    if ($has_attachment == FALSE) {
        $msgtype = $content_type = "text/html";
        $transfer_encoding = "8bit";
    } else {
        // has attachment
        $msgtype = $content_type = "multipart/mixed";
        // create the main body
        $body_text = "Content-Type: text/html; charset=US-ASCII\n";
        $body_text .= "Content-Transfer-Encoding: base64\n";
        $body_text .= "\n" . chunk_split(base64_encode($bodydata));
        // get the attachment data
        if (($fd = fopen($attachment["tmp_name"], "r")) == TRUE) {
            $attachment_data = "";
            while (!feof($fd)) {
                $attachment_data .= fgets($fd, 4096);
            }
            fclose($fd);
            // delete the temporary file
            unlink($attachment["tmp_name"]);
            $attachment_data = chunk_split(base64_encode($attachment_data));
            $attachment_headers = "Content-Type: {$attachment['type']}; name=\"{$attachment['name']}\"\n";
            $attachment_headers .= "Content-Transfer-Encoding: base64\n";
            $attachment_headers .= "Content-Disposition: attachment; filename=\"{$attachment['name']}\"\n";
            $attachment_data = "{$attachment_headers}\n{$attachment_data}";
        } else {
            // error opening the attachment file
            $attachment_data = "";
        }
        // generate a unique boundary ( md5 of filename + ":=" + filesize )
        $boundary = md5($attachment["name"]) . "=:" . $attachment["size"];
        $content_type .= "; boundary=\"{$boundary}\"";
        // put together the body
        $bodydata = "\n--{$boundary}\n{$body_text}\n\n--{$boundary}\n{$attachment_data}\n\n--{$boundary}--\n";
    }
    // generate the msg id
    list($buf, $domain) = explode("@", $smtp_data["smtp_from"]);
    // build headers
    $headers[] = "From: {$smtp_data['smtp_from']}";
    $headers[] = "To: {$send_to}";
    $headers[] = "Date: " . date("Y-m-d");
    $headers[] = "Reply-To: {$smtp_data['smtp_reply']}";
    $headers[] = "X-Mailer: Cubit Mail";
    $headers[] = "Return-Path: {$smtp_data['smtp_reply']}";
    $headers[] = "Message-ID: <" . date("YmdHi") . "." . md5($bodydata) . "@{$domain}>";
    $headers[] = "MIME-Version: 1.0";
    $headers[] = "Content-Type: {$content_type}; charset=US-ASCII";
    $headers[] = "cc: {$send_cc}";
    $headers[] = "bcc: {$send_bcc}";
    // create the header variable (it is done this way, to make management of headers easier, since there
    // may be no tabs and unnecesary whitespace in mail headers)
    //$headers[] = "\n"; // add another new line to finish the headers
    $headers = implode("\n", $headers);
    // send the message
    $sendmail =& new clsSMTPMail();
    $OUTPUT = $sendmail->sendMessages($smtp_data["smtp_host"], 25, $smtp_data["smtp_auth"], $smtp_data["smtp_user"], $smtp_data["smtp_pass"], $send_to, $smtp_data["smtp_from"], $subject, $bodydata, $headers);
    if ($sendmail->bool_success) {
        $account_id = "{$_GET['aid']}";
        $type_id = getMsgType($msgtype);
        // data and header is base64_encoded so weird characters can also be stored
        $buf = "{$headers}\n\n{$bodydata}";
        $data = chunk_split(base64_encode($buf));
        db_conn("cubit");
        // insert body into Cubit
        if (!pglib_transaction("BEGIN")) {
            continue;
        }
        $rslt = db_exec("INSERT INTO mail_msgbodies (type_id, data)\n\t\t\tVALUES( {$type_id}, '{$data}' )");
        if (pg_cmdtuples($rslt) <= 0) {
            continue;
        }
        $msgbody_id = pglib_lastid("mail_msgbodies", "msgbody_id");
        pglib_transaction("COMMIT");
        // get the folder this message should be inserted into
        $rslt = db_exec("\n\t\t\tSELECT fid_sent FROM mail_account_settings\n\t\t\tWHERE account_id='{$account_id}'");
        if (pg_num_rows($rslt) > 0) {
            $infolder = pg_fetch_result($rslt, 0, 0);
        } else {
            $infolder = 0;
        }
        // move to no folder, but store, this way all is not lost
        // insert the message linked to body
        $sql = "\n\t\tINSERT INTO mail_messages (account_id, folder_id, subject,\n\t\t\tadd_from, add_to, add_cc, add_bcc, priority, attachments, msgbody_id,\n\t\t\tflag, date)\n\t\tVALUES ('{$account_id}', '{$infolder}', '{$subject}', '{$smtp_data['smtp_from']}',\n\t\t\t'{$send_to}', '{$send_cc}', '{$send_bcc}', '1',\n\t\t\t'" . ($has_attachment ? "1" : "0") . "', '{$msgbody_id}',\t'1', CURRENT_TIMESTAMP)";
        $rslt = db_exec($sql) or errDie("Error saving message in Sent Items.");
        $message_id = pglib_lastid("mail_messages", "message_id");
    }
    /*if ( mail($send_to, $subject, $body, $headers) == TRUE )
    		$OUTPUT = "Successfully sent mail to $send_to.<br>";
    	else
    		$OUTPUT = "Error sending mail.<br>";*/
    return writeMsg($OUTPUT);
}
        echo $val['uid'];
        ?>
</a></td>
	  <td><a href="<?php 
        echo U('home/log', array('uid' => $val['uid'], 'status' => $status));
        ?>
"><?php 
        echo getUser($val['uid']);
        ?>
</a></td>
	  <td><?php 
        echo $val['msg_id'];
        ?>
</td>
	  <td><?php 
        echo getMsgType($val['msg_type']);
        ?>
</td>
	  <td><?php 
        echo $val['content'];
        ?>
</td>
	  <td><?php 
        echo $val['create_time'] ? outTime($val['create_time']) : '';
        ?>
</td>
	  <td>
		<div class="btn-group"> 
		  <button class="btn btn-white btn-xs dropdown-toggle" data-toggle="dropdown">操作<span class="caret"></span></button> 
		  <ul class="dropdown-menu">
			  <li><a rel="pop" href="<?php