function get_data($_POST)
{
    extract($_POST);
    $es = qryEmailSettings();
    #check if we have a list ....
    $get_email_list = "SELECT * FROM email_groups WHERE email_group = '{$group}' LIMIT 1";
    $run_email_list = db_exec($get_email_list) or errDie("Unable to get email group information.");
    if (pg_numrows($run_email_list) < 1) {
        #no group ... only create new
        $options = "";
    } else {
        $options = "<option value='old'>Use Previous List</option>";
    }
    $display = "\n\t\t<h2>Select Email Group</h2>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t<input type='hidden' name='key' value='process'>\n\t\t\t<input type='hidden' name='group' value='{$group}'>\n\t\t\t<tr>\n\t\t\t\t<th>Select Email Group</th>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<select name='list'>\n\t\t\t\t\t\t{$options}\n\t\t\t\t\t\t<option value='new'>Create New List</option>\n\t\t\t\t\t</select>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t\t<tr>\n\t\t\t\t<td><input type='submit' value='Next'></td>\n\t\t\t</tr>\n\t\t</form>\n\t\t</table>";
    return $display;
}
function send_email_groups($_POST)
{
    extract($_POST);
    if (!isset($sendgroups) or !is_array($sendgroups)) {
        return show_email_groups("<li class='err'>Please Select At Least 1 Email Batch To Send.</li><br>");
    }
    db_connect();
    $sendgroup = "";
    $listing = "";
    $groupcounter = 0;
    $ran = TRUE;
    foreach ($sendgroups as $groupname) {
        $ran2 = TRUE;
        $sendgroup .= "&sendgroups[]={$groupname}";
        $listing .= "\n\t\t\t<tr>\n\t\t\t\t<td><h3>{$groupname}</h3></td>\n\t\t\t</tr>";
        #determine how many have been sent
        $get_sent = "SELECT count(id) FROM email_queue WHERE groupname = '{$groupname}' AND status = 'sent'";
        $run_sent = db_exec($get_sent) or errDie("Unable to get sent email information.");
        if (pg_numrows($run_sent) < 1) {
            $sent_items = 0;
        } else {
            $sent_items = pg_fetch_result($run_sent, 0, 0);
        }
        $get_sent = "SELECT count(id) FROM email_queue WHERE groupname = '{$groupname}' AND status = 'failed' AND status2 = 'active'";
        $run_sent = db_exec($get_sent) or errDie("Unable to get sent email information.");
        if (pg_numrows($run_sent) < 1) {
            $unsent_items = 0;
        } else {
            $unsent_items = pg_fetch_result($run_sent, 0, 0);
        }
        $listing .= "\n\t\t\t<tr>\n\t\t\t\t<th>{$sent_items} Emails Have Been Sent</th>\n\t\t\t\t<th colspan='3'>{$unsent_items} Emails Remain</th>\n\t\t\t</tr>";
        #get list of 5 queue items to display
        $get_list = "SELECT * FROM email_queue WHERE groupname = '{$groupname}' AND status = 'failed' AND status2 = 'active' OFFSET {$groupcounter} LIMIT 10";
        $run_list = db_exec($get_list) or errDie("Unable to get list of emails to be sent.");
        if (pg_numrows($run_list) < 1) {
            //			$listing .= "
            //				<tr class='".bg_class()."'>
            //					<td colspan='2'>All Emails Have Been Sent.</td>
            //				</tr>
            //				".TBL_BR;
            //			return show_email_groups("<li class='err'>Requested Email(s) Have Been Sent.</li><br>");
            print "\n\t\t\t\t\t<script>\n\t\t\t\t\t\tdocument.location='email-queue-manage.php';\n\t\t\t\t\t</script>";
        } else {
            $listing .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Email Address</th>\n\t\t\t\t\t<th>Subject</th>\n\t\t\t\t\t<th>Date Added</th>\n\t\t\t\t\t<th>Status</th>\n\t\t\t\t</tr>";
            while ($larr = pg_fetch_array($run_list)) {
                if ($ran && $ran2) {
                    $larr['status'] = "Sending";
                    $ran2 = FALSE;
                } else {
                    $larr['status'] = "Queued";
                }
                $listing .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$larr['emailaddress']}</td>\n\t\t\t\t\t\t<td>{$larr['subject']}</td>\n\t\t\t\t\t\t<td>{$larr['date_added']}</td>\n\t\t\t\t\t\t<td>{$larr['status']}</td>\n\t\t\t\t\t</tr>";
            }
        }
        //		$count = 0;
        #only update 1 email message
        $get_emails = "SELECT * FROM email_queue WHERE groupname = '{$groupname}' AND status = 'failed' AND status2 = 'active' ORDER BY id LIMIT 1";
        $run_emails = db_exec($get_emails) or errDie("Unable to get group information.");
        while ($larr = pg_fetch_array($run_emails)) {
            if ($ran) {
                $bodydata = $larr['message'];
                $subject = $larr['subject'];
                $es = qryEmailSettings();
                $body = $bodydata;
                #generate removal tail code
                $tail = "<br><br> \n\nIf you would like to stop receiving these emails, please leave the following link intact, and reply to this email.\n<a href='http://" . $_SERVER['SERVER_ADDR'] . "/unsub-email.php?email={$larr['emailaddress']}'>http://" . $_SERVER['SERVER_ADDR'] . "/unsub-email.php?email={$larr['emailaddress']}</a>";
                if ($larr['send_format'] != "html") {
                    $tail = strip_tags($tail);
                }
                $body = $body . $tail;
                $send_cc = "";
                $send_bcc = "";
                $smtp_data['signature'] = $es['sig'];
                $smtp_data['smtp_from'] = getCSetting("MARKET_MAIL_FROM");
                //$es['fromname'];
                $smtp_data['smtp_reply'] = $es['reply'];
                $smtp_data['smtp_host'] = $es['smtp_host'];
                $smtp_data['smtp_auth'] = $es['smtp_auth'];
                $smtp_data['smtp_user'] = $es['smtp_user'];
                $smtp_data['smtp_pass'] = $es['smtp_pass'];
                // 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"]);
                if ($larr['attachment'] != 0) {
                    $has_attachment = TRUE;
                } else {
                    $has_attachment = false;
                }
                //				$has_attachment = false;
                // modify message and create content_type header depending on whether or not an attachment was posted
                if ($has_attachment == false) {
                    $content_type = "text/{$larr['send_format']};charset=US-ASCII";
                    $transfer_encoding = "8bit";
                } else {
                    // has attachment
                    $get_attach = "SELECT * FROM email_attachments WHERE id = '{$larr['attachment']}' LIMIT 1";
                    $run_attach = db_exec($get_attach) or errDie("Unable to get email attachment information.");
                    if (pg_numrows($run_attach) < 1) {
                        return "Email attachment not found.";
                    }
                    $aarr = pg_fetch_array($run_attach);
                    $content_type = "multipart/mixed";
                    // create the main body
                    $body_text = "Content-Type: text/{$larr['send_format']}; charset=US-ASCII\n";
                    $body_text .= "Content-Transfer-Encoding: base64\n";
                    $body_text .= "\n" . chunk_split(base64_encode($body));
                    // get the attachment data
                    $attachment = array();
                    //					$attachment["data"] = state($id,$fromdate,$todate,$type);
                    $attachment["name"] = $aarr['attach_filename'];
                    //"statement.pdf";
                    // delete the temporary file
                    $attachment["data"] = chunk_split($aarr["attach_data"]);
                    //chunk_split(base64_encode($attachment["data"]));
                    $attachment["headers"] = "Content-Type: {$aarr['attach_mime']}; 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']}";
                    // generate a unique boundary ( md5 of filename + ":=" + filesize )
                    $boundary = md5($attachment["name"]) . "=:" . strlen($attachment["data"]);
                    $content_type .= "; boundary=\"{$boundary}\"";
                    // put together the body
                    $body = "\n--{$boundary}\n{$body_text}\n\n--{$boundary}\n{$attachment['data']}\n\n--{$boundary}--\n";
                }
                // build headers
                $headers = array();
                $headers[] = "From: " . getCSetting("MARKET_MAIL_FROM");
                //$smtp_data[smtp_from]";
                $headers[] = "To: {$larr['emailaddress']}";
                $headers[] = "Reply-To: " . getCSetting("MARKET_MAIL_FROM");
                //$smtp_data[smtp_reply]";
                $headers[] = "X-Mailer: Cubit Mail";
                $headers[] = "Return-Path: " . getCSetting("MARKET_MAIL_FROM");
                //$smtp_data[smtp_reply]";
                $headers[] = "Content-Type: {$content_type}";
                $headers[] = "cc: {$send_cc}";
                $headers[] = "bcc: {$send_bcc}";
                // create the mime header if should
                if ($has_attachment == TRUE) {
                    $headers[] = "MIME-Version: 1.0";
                }
                // 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);
                //return "done";
                // 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"], $larr['emailaddress'], $smtp_data["smtp_from"], "{$subject}", $body, $headers);
                if ($sendmail->bool_success) {
                    #email system reports success!
                    #update this entry ..
                    $upd_sql = "UPDATE email_queue SET status = 'sent' WHERE id = '{$larr['id']}'";
                    $run_upd = db_exec($upd_sql) or errDie("Unable to update email queue information.");
                    $ran = FALSE;
                } else {
                    #problem sending mail ...
                    #if email system reports network problem, loop, else mark ...
                    $upd_sql = "UPDATE email_queue SET status = 'failed', status2 = 'failed', failed_reason = '{$OUTPUT}' WHERE id = '{$larr['id']}'";
                    $run_upd = db_exec($upd_sql) or errDie("Unable to update email queue information.");
                    $ran = FALSE;
                }
            }
            //			$count++;
        }
        //		print "group sent ...";
    }
    $display = "\n\t\t\t\t\t<script>\n\t\t\t\t\t\twindow.setTimeout(' window.location=\"email-queue-failures.php?key=confirm{$sendgroup}\"; ',3000);\n\t\t\t\t\t</script>\n\t\t\t\t\t<h2>Email Management</h2>\n\t\t\t\t\t<table " . TMPL_tblDflts . ">\n\t\t\t\t\t\t{$listing}\n\t\t\t\t\t</table>\n\t\t\t\t";
    return $display;
}
function details($_GET)
{
    # get vars
    foreach ($_GET as $key => $value) {
        ${$key} = $value;
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice number.");
    # display errors, if any
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class=err>" . $e["msg"];
        }
        $confirm .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get invoice info
    db_connect();
    $sql = "SELECT * FROM invoices WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $invRslt = db_exec($sql) or errDie("Unable to get invoice information");
    if (pg_numrows($invRslt) < 1) {
        return "<i class=err>Not Found</i>";
    }
    $inv = pg_fetch_array($invRslt);
    # Check if invoice has been printed
    if ($inv['printed'] != "y") {
        $error = "<li class=err> Error : Invoice number <b>{$invid}</b> has not been printed yet.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    /* --- Start some checks --- */
    # Check if stock was selected(yes = put done button)
    db_connect();
    $sql = "SELECT stkid FROM inv_items WHERE invid = '{$inv['invid']}' AND div = '" . USER_DIV . "'";
    $crslt = db_exec($sql);
    if (pg_numrows($crslt) < 1) {
        $error = "<li class=err> Error : Invoice number <b>{$invid}</b> has no items.";
        $error .= "<p><input type=button onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $error;
    }
    /* --- End some checks --- */
    /* --- Start Products Display --- */
    # Products layout
    $products = "";
    $disc = 0;
    $taxex = 0;
    # Get selected stock in this invoice
    db_connect();
    $sql = "SELECT * FROM inv_items  WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    $stkdRslt = db_exec($sql);
    while ($stkd = pg_fetch_array($stkdRslt)) {
        # Get warehouse name
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid = '{$stkd['whid']}' AND div = '" . USER_DIV . "'";
        $whRslt = db_exec($sql);
        $wh = pg_fetch_array($whRslt);
        # Get selected stock in this warehouse
        db_connect();
        $sql = "SELECT * FROM stock WHERE stkid = '{$stkd['stkid']}' AND div = '" . USER_DIV . "'";
        $stkRslt = db_exec($sql);
        $stk = pg_fetch_array($stkRslt);
        $sp = "&nbsp;&nbsp;&nbsp;&nbsp;";
        # Check Tax Excempt
        if ($stk['exvat'] == 'yes') {
            $taxex += $stkd['amt'];
            $ex = "#";
        } else {
            $ex = "&nbsp;&nbsp;";
        }
        # Keep track of discounts
        $disc += $stkd['disc'];
        # Put in product
        $products .= "<tr valign=top>\n\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t<td>{$ex} {$sp} {$stk['stkdes']}</td>\n\t\t\t<td>{$stkd['qty']}</td>\n\t\t\t<td>{$stkd['unitcost']}</td>\n\t\t\t<td>{$stkd['disc']}</td>\n\t\t\t<td>" . CUR . " {$stkd['amt']}</td>\n\t\t</tr>";
    }
    /* --- Start Some calculations --- */
    # Subtotal
    $SUBTOT = sprint($inv['subtot']);
    # Calculate tradediscm
    if (strlen($inv['traddisc']) > 0) {
        $traddiscm = sprint($inv['traddisc'] / 100 * $SUBTOT);
    } else {
        $traddiscm = "0.00";
    }
    # Calculate subtotal
    $VATP = TAX_VAT;
    $SUBTOT = sprint($inv['subtot']);
    $VAT = sprint($inv['vat']);
    $TOTAL = sprint($inv['total']);
    $inv['delchrg'] = sprint($inv['delchrg']);
    /* --- End Some calculations --- */
    # todays date
    $date = date("d-m-Y");
    $sdate = date("Y-m-d");
    # Avoid little box
    if (strlen($inv['comm']) > 0) {
        $inv['comm'] = "<table border=1 cellspacing='0' bordercolor='#000000'>\n\t\t\t<tr><td>" . nl2br($inv['comm']) . "</td></tr>\n\t\t</table>";
    }
    # Update number of prints
    $inv['prints']++;
    db_connect();
    $Sql = "UPDATE invoices SET prints = '{$inv['prints']}' WHERE invid = '{$invid}' AND div = '" . USER_DIV . "'";
    //$upRslt = db_exec($Sql) or errDie ("Unable to update invoice information");
    /* -- Final Layout -- */
    $details = "<html><center><h2>Tax Invoice</h2>\n\t<table " . TMPL_tblDflts . " width=770>\n\t<tr><td valign=top width=30%>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<td>{$inv['surname']}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>" . nl2br($inv['cusaddr']) . "</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>(Vat No. {$inv['cusvatno']})</td>\n\t\t\t</tr>\n\t\t</table>\n\t</td><td valign=top width=30%>\n\t\t" . COMP_NAME . "<br>\n\t\t" . COMP_ADDRESS . "<br>\n\t\t" . COMP_PADDR . "<br>\n\t\t" . COMP_TEL . "<br>\n\t\t" . COMP_FAX . "<br>\n\t\tReg No. " . COMP_REGNO . "<br>\n\t\tVAT No. " . COMP_VATNO . "<br>\n\t</td><td align=left width=20%>\n\t\t<img src='compinfo/getimg.php' width=230 height=47>\n\t</td><td valign=bottom align=right width=20%>\n\t\t<table cellpadding='2' cellspacing='0' border=1 bordercolor='#000000'>\n\t\t\t<tr>\n\t\t\t\t<td><b>Invoice No.</b></td>\n\t\t\t\t<td valign=center>{$inv['invnum']}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Proforma Inv No.</b></td>\n\t\t\t\t<td>{$inv['docref']}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Order No.</b></td>\n\t\t\t\t<td valign=center>{$inv['ordno']}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Terms</b></td>\n\t\t\t\t<td valign=center>{$inv['terms']} Days</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Invoice Date</b></td>\n\t\t\t\t<td valign=center>{$inv['odate']}</td>\n\t\t\t</tr>\n\t\t</table>\n\t</td></tr>\n\t<tr><td><br></td></tr>\n\t<tr><td colspan=4>\n\t<table cellpadding='5' cellspacing='0' border=1 width=100% bordercolor='#000000'>\n\t\t<tr>\n\t\t\t<th>ITEM NUMBER</th>\n\t\t\t<th width=45%>DESCRIPTION</th>\n\t\t\t<th>QTY</th>\n\t\t\t<th>UNIT PRICE</th>\n\t\t\t<th>UNIT DISCOUNT</th>\n\t\t\t<th>AMOUNT</th>\n\t\t<tr>\n\t\t{$products}\n\t</table>\n\t</td></tr>\n\t<tr><td>\n\t{$inv['comm']}\n\t</td><td>\n\t\t" . BNK_BANKDET . "\n\t</td><td align=right colspan=2>\n\t\t<table cellpadding='5' cellspacing='0' border=1 width=50% bordercolor='#000000'>\n\t\t\t<tr>\n\t\t\t\t<td><b>SUBTOTAL</b></td>\n\t\t\t\t<td align=right>" . CUR . " {$SUBTOT}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Trade Discount</b></td>\n\t\t\t\t<td align=right>" . CUR . " {$inv['discount']}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>Delivery Charge</b></td>\n\t\t\t\t<td align=right>" . CUR . " {$inv['delivery']}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td><b>VAT @ {$VATP}%</b></td>\n\t\t\t\t<td align=right>" . CUR . " {$VAT}</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th><b>GRAND TOTAL<b></th>\n\t\t\t\t<td align=right>" . CUR . " {$TOTAL}</td>\n\t\t\t\t</tr>\n\t\t</table>\n\t</td></tr>\n\t<tr><td><br></td></tr>\n\t<tr><td>\n\t\t<table cellpadding='2' cellspacing='0' border=1>\n\t\t\t<tr><td colspan=2>VAT Exempt indicator = #</td></tr>\n\t\t</table>\n\t</td><td><br></td></tr>\n\t</table></center></html>";
    $body = $details;
    $es = qryEmailSettings();
    db_conn("cubit");
    $Sl = "SELECT * FROM customers WHERE cusnum='{$inv['cusnum']}'";
    $Ri = db_exec($Sl);
    $cd = pg_fetch_array($Ri);
    if (strlen($cd['email']) < 1) {
        return "This customer does not have an email address";
    }
    //$send_cc="*****@*****.**";
    //$send_bcc="*****@*****.**";
    $send_cc = "";
    $send_bcc = "";
    $smtp_data['signature'] = $es['sig'];
    $smtp_data['smtp_from'] = $es['fromname'];
    $smtp_data['smtp_reply'] = $es['reply'];
    $smtp_data['smtp_host'] = $es['smtp_host'];
    $smtp_data['smtp_auth'] = $es['smtp_auth'];
    $smtp_data['smtp_user'] = $es['smtp_user'];
    $smtp_data['smtp_pass'] = $es['smtp_pass'];
    //db_conn('cubit');
    // 	$rslt = db_exec("SELECT smtp_from, smtp_reply, signature, smtp_host, smtp_auth, smtp_user, smtp_pass
    // 		FROM mail_accounts");
    // 	$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"]);
    $has_attachment = FALSE;
    // modify message and create content_type header depending on whether or not an attachment was posted
    if ($has_attachment == FALSE) {
        $content_type = "text/html;charset=US-ASCII";
        $transfer_encoding = "8bit";
    } else {
        // has attachment
        $content_type = "multipart/mixed";
        // create the main body
        $body_text = "Content-Type: text/plain; charset=US-ASCII\n";
        $body_text .= "Content-Transfer-Encoding: base64\n";
        $body_text .= "\n" . chunk_split(base64_encode($body));
        // 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
        $body = "\n--{$boundary}\n{$body_text}\n\n--{$boundary}\n{$attachment_data}\n\n--{$boundary}--\n\n\t\t";
    }
    print $body;
    // build headers
    $headers[] = "From: {$smtp_data['smtp_from']}";
    $headers[] = "To: {$cd['email']}";
    $headers[] = "Reply-To: {$smtp_data['smtp_reply']}";
    $headers[] = "X-Mailer: Cubit Mail";
    $headers[] = "Return-Path: {$smtp_data['smtp_reply']}";
    $headers[] = "Content-Type: {$content_type}";
    $headers[] = "cc: {$send_cc}";
    $headers[] = "bcc: {$send_bcc}";
    // create the mime header if should
    if ($has_attachment == TRUE) {
        $headers[] = "MIME-Version: 1.0";
    }
    // 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"], $cd['email'], $smtp_data["smtp_from"], "Invoice: {$inv['invnum']}", $body, $headers);
    /*if ( mail($send_to, $subject, $body, $headers) == TRUE )
    		$OUTPUT = "Successfully sent mail to $send_to.<br>";
    	else
    		$OUTPUT = "Error sending mail.<br>";*/
    return $OUTPUT;
}
function sendvoice($quoid, $invfunc, $email, $message)
{
    $es = qryEmailSettings();
    require_lib("validate");
    $v = new validate();
    $v->isOk($quoid, "num", 1, 20, "Invalid quote number.");
    if ($v->isError()) {
        $err = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $err .= "<li class='err'>{$e['msg']}</li>";
        }
        $confirm .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
        return $confirm;
    }
    # Get invoice info
    if ($invfunc == "genpdf") {
        db_conn("cubit");
        $sql = "SELECT cusnum, quoid FROM quotes WHERE quoid = '{$quoid}' AND div = '" . USER_DIV . "'";
        $invRslt = db_exec($sql) or errDie("Unable to get quote information");
        if (pg_numrows($invRslt) < 1) {
            return "<i class='err'>Not Found</i>";
        }
        $inv = pg_fetch_array($invRslt);
    }
    $quoid = $inv['quoid'];
    $Sl = "SELECT * FROM customers WHERE cusnum='{$inv['cusnum']}'";
    $Ri = db_exec($Sl);
    $cd = pg_fetch_array($Ri);
    if (strlen($email) < 1) {
        return "This customer does not have an email address";
    }
    $body = $message;
    $send_cc = "";
    $send_bcc = "";
    $smtp_data['signature'] = $es['sig'];
    $smtp_data['smtp_from'] = $es['reply'];
    $smtp_data['smtp_reply'] = $es['reply'];
    $smtp_data['smtp_host'] = $es['smtp_host'];
    $smtp_data['smtp_auth'] = $es['smtp_auth'];
    $smtp_data['smtp_user'] = $es['smtp_user'];
    $smtp_data['smtp_pass'] = $es['smtp_pass'];
    // 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"]);
    $has_attachment = true;
    // modify message and create content_type header depending on whether or not an attachment was posted
    if ($has_attachment == false) {
        $content_type = "text/html;charset=US-ASCII";
        $transfer_encoding = "8bit";
    } else {
        // has attachment
        $content_type = "multipart/mixed";
        // create the main body
        $body_text = "Content-Type: text/plain; charset=US-ASCII\n";
        $body_text .= "Content-Transfer-Encoding: base64\n";
        $body_text .= "\n" . chunk_split(base64_encode($body));
        // get the attachment data
        $attachment = array();
        $attachment["data"] = $invfunc($quoid);
        $attachment["name"] = "quote{$quoid}.pdf";
        // delete the temporary file
        $attachment["data"] = chunk_split(base64_encode($attachment["data"]));
        $attachment["headers"] = "Content-Type: application/x-pdf; 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']}";
        // generate a unique boundary ( md5 of filename + ":=" + filesize )
        $boundary = md5($attachment["name"]) . "=:" . strlen($attachment["data"]);
        $content_type .= "; boundary=\"{$boundary}\"";
        // put together the body
        $body = "\n--{$boundary}\n{$body_text}\n\n--{$boundary}\n{$attachment['data']}\n\n--{$boundary}--\n";
    }
    // build headers
    $headers[] = "From: {$smtp_data['smtp_from']}";
    $headers[] = "Reply-To: {$smtp_data['smtp_reply']}";
    $headers[] = "X-Mailer: Cubit Mail";
    $headers[] = "Return-Path: {$smtp_data['smtp_reply']}";
    $headers[] = "Content-Type: {$content_type}";
    // create the mime header if should
    if ($has_attachment == TRUE) {
        $headers[] = "MIME-Version: 1.0";
    }
    // 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);
    //return "done";
    // 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"], $email, $smtp_data["smtp_from"], "Quote: {$inv['quoid']}", $body, $headers);
    /*if ( mail($send_to, $subject, $body, $headers) == TRUE )
    		$OUTPUT = "Successfully sent mail to $send_to.<br>";
    	else
    		$OUTPUT = "Error sending mail.<br>";*/
    return $OUTPUT;
}
function sendMsg()
{
    global $_GET;
    $v =& new validate();
    $OUTPUT = "";
    // restore the variables
    extract($_GET);
    extract($_FILES);
    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($subject, "string", 1, 255, "Invalid subject.");
    // $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>";
    $smtp_data = qryEmailSettings();
    // build msg body
    $body = "{$body}\n\n{$smtp_data['sig']}";
    // 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
    $a = explode("@", $smtp_data["fromname"]);
    if (count($a) < 2) {
        $OUTPUT = "<li class='err'>Invalid from address. Click <a href='email-settings.php'>here</a> to change.</li>";
        require "template.php";
    }
    list($buf, $domain) = $a;
    // build headers
    $headers[] = "From: {$smtp_data['fromname']}";
    $headers[] = "Reply-To: {$smtp_data['reply']}";
    $headers[] = "X-Mailer: Cubit Mail";
    $headers[] = "Return-Path: {$smtp_data['reply']}";
    $headers[] = "Message-ID: <" . date("YmdHi") . "." . md5($bodydata) . "@{$domain}>";
    $headers[] = "MIME-Version: 1.0";
    $headers[] = "Content-Type: {$content_type}; charset=UTF-8";
    $headers[] = "To: \"Cubit Clients\" <*****@*****.**>";
    // 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["fromname"], $subject, $bodydata, $headers);
    return $OUTPUT;
}