Пример #1
0
 /**
  * returns general email settings, and if done does an r2sListSet and goes to email settings page
  * 
  * @return array
  */
 function qryEmailSettings()
 {
     $qry = new dbSelect("esettings", "cubit");
     $qry->run();
     $invalid = false;
     if ($qry->num_rows() <= 0) {
         $invalid = true;
     } else {
         $d = $qry->fetch_array();
         $qry->free();
         if ($d["smtp_host"] == "" || $d["fromname"] == "") {
             $invalid = true;
         }
     }
     if ($invalid) {
         r2sListSet("emailsettings");
         header("Location: email-settings.php");
         exit;
     }
     return $d;
 }
Пример #2
0
/**
 * entry function, gathers information
 */
function enter($frm)
{
    $trhconf = getTrhConfig();
    if ($trhconf["MANAGEUSER"] <= 0) {
        r2sListSet("trh_comminit");
        header("Location: configuration.php");
        exit;
    }
    if (isset($_REQUEST["suppid"])) {
        $sc_desc = "Supplier";
        $sc_fld = "suppid";
    } else {
        $sc_desc = "Customer";
        $sc_fld = "custid";
    }
    $frm->setkey("confirm");
    $frm->settitle("Initialize Transheks Communications");
    $frm->add_heading("{$sc_desc} Information");
    $frm->add_hidden($sc_fld, $_REQUEST[$sc_fld], "int");
    $frm->add_text("{$sc_desc} Transheks Email Address", "email", "", "email", "1:255");
    $OUT = $frm->getfrm_input();
    return $OUT;
}
Пример #3
0
function errSend()
{
    /* check for valid email settings */
    $settings = new dbSelect("esettings", "cubit");
    $settings->run();
    if ($settings->num_rows() <= 0) {
        r2sListSet("emailsettings");
        header("Location: email-settings.php");
        exit;
    }
    $settings->fetch_array();
    $server = $settings->d["smtp_host"];
    $from = $settings->d["fromname"];
    $reply = $settings->d["reply"];
    /* build the email */
    $data = errData($_GET["id"]);
    $msg = new clsMailMsg();
    $msg->newMessage($from, $reply, "Error Report: {$data['errtime']}", "Error report file attached.");
    $msg->addAttachment("application/octet-stream", "error{$_GET['id']}-{$data['errtime']}.cer", $data["errdata"]);
    $md = $msg->getNewMessage();
    /* send the email */
    /**
     * ok, so lets stop catching errors because if the email sending fails
     * we are just going to go back to "an error has occured"
     */
    disableErrorNet();
    $smtp = new clsSMTPMail();
    $smtp->sendMessages($server, 25, false, false, false, ERRORNET_EMAIL, $md["from"], $md["subject"], $md["body"], $md["headers"]);
    $OUTPUT = "<h3>Error Report</h3>";
    if ($smtp->bool_success !== true) {
        $OUTPUT .= "Error sending report. Please save report and email it\n\t\t\tto <a class='nav' href='mailto: " . ERRORNET_EMAIL . "'>" . ERRORNET_EMAIL . "</a><br />\n\t\t\t<br />\n\t\t\t<input type='button' value='Save Error Report'\n\t\t\t\tonClick='document.location.href=\"" . relpath("geterror.php") . "?id={$_GET['id']}\";' />";
    } else {
        $OUTPUT .= "Successfully sent report. Thank You.";
    }
    return $OUTPUT;
}
function printStk($_POST, $errs = "")
{
    extract($_POST);
    $fields = array();
    $fields["search_val"] = "[_BLANK_]";
    extract($fields, EXTR_SKIP);
    if (!isset($whid) or count($whid) < 1) {
        return slct();
    }
    if (!is_array($whid)) {
        $temp = $whid;
        $whid = array();
        $whid[] = $temp;
    }
    if (!isset($sortby)) {
        $sortby = "normal";
    }
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($catid, "num", 1, 50, "Invalid Category.");
    $v->isOk($clasid, "num", 1, 50, "Invalid Classification.");
    $v->isOk($sortby, "string", 1, 10, "Invalid Sort Selection.");
    foreach ($whid as $temp) {
        $v->isOk($temp, "num", 1, 50, "Invalid Warehouse.");
    }
    $Whe = "";
    if ($catid != 0) {
        $Whe .= " AND catid = '{$catid}'";
    }
    if ($clasid != 0) {
        $Whe .= " AND prdcls = '{$clasid}'";
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>{$e['msg']}</li><br>";
        }
        return $confirm;
    }
    if (!isset($sortby)) {
        $sel1 = "";
        $sel2 = "";
        $sel3 = "";
    } elseif ($sortby == "cat") {
        $sel1 = "";
        $sel2 = "checked='yes'";
        $sel3 = "";
    } elseif ($sortby == "class") {
        $sel1 = "";
        $sel2 = "";
        $sel3 = "checked='yes'";
    } else {
        $sel1 = "checked='yes'";
        $sel2 = "";
        $sel3 = "";
    }
    $whids = "";
    foreach ($whid as $temp) {
        $whids .= "<input type='hidden' name='whid[]' value='{$temp}'>";
    }
    if ($key == "export") {
        $pure = true;
    } else {
        $pure = false;
    }
    $Whe .= " AND ((lower(stkcod) LIKE lower('%{$search_val}%')) OR (lower(stkdes) LIKE lower('%{$search_val}%')))";
    if ($search_val == "[_BLANK_]") {
        $search_val = "";
    }
    # Set up table to display in
    if ($pure) {
        $OUT = "<table " . TMPL_tblDflts . ">";
    } else {
        $OUT = "\n\t\t<h3>View Stock</h3>\n\t\t{$errs}\n\t\t<table " . TMPL_tblDflts . " width='30%'>\n\t\t<form action='" . SELF . "' method='POST' name='form1'>\n\t\t\t<input type='hidden' name='key' value='view'>\n\t\t\t<input type='hidden' name='catid' value='{$catid}'>\n\t\t\t<input type='hidden' name='clasid' value='{$clasid}'>\n\t\t\t<input type='hidden' name='search_val' value='{$search_val}'>\n\t\t\t{$whids}\n\t\t\t<tr>\n\t\t\t\t<th>Sort By:</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='radio' name='sortby' {$sel1} value='normal' onChange='javascript:document.form1.submit();'> Normal\n\t\t\t\t\t<input type='radio' name='sortby' {$sel2} value='cat' onChange='javascript:document.form1.submit();'> Category\n\t\t\t\t\t<input type='radio' name='sortby' {$sel3} value='class' onChange='javascript:document.form1.submit();'> Classification\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<th>Search</th>\n\t\t\t</tr>\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>\n\t\t\t\t\t<input type='text' size='25' name='search_val' value='{$search_val}'> \n\t\t\t\t\t<input type='submit' value='Search'>\n\t\t\t\t</tr>\n\t\t\t" . TBL_BR . "\n\t\t</form>\n\t\t</table>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t<form action='" . SELF . "' method='POST' name='form2'>\n\t\t\t<input type='hidden' name='key' value='remove'>";
    }
    #search parms
    if ($sortby == "cat") {
        $Ord = "catname,stkcod";
    } elseif ($sortby == "class") {
        $Ord = "classname,stkcod";
    } else {
        $Ord = "stkcod";
    }
    $stores = array();
    if ($whid != "0") {
        foreach ($whid as $temp) {
            if ($temp != 0) {
                $stores[] = " whid = '{$temp}'";
            }
        }
        if (count($stores) > 0) {
            $stores = implode(" OR ", $stores);
        } else {
            $stores = "true";
        }
    } else {
        $stores = "true";
    }
    # connect to database
    db_connect();
    if (!isset($offset)) {
        $offset = 0;
    }
    if (isset($next)) {
        $offset = $offset + 100;
    }
    if (isset($prev)) {
        $offset = $offset - 100;
    }
    if ($offset < 0) {
        $offset = 0;
    }
    if ($offset != 0) {
        $prev_but = "<input type='submit' name='prev' value='Previous'>";
    } else {
        $prev_but = "";
    }
    # Query server
    $i = 0;
    $searchs = "SELECT * FROM stock WHERE units<=0 AND ({$stores}) AND div = '" . USER_DIV . "' {$Whe} ORDER BY {$Ord} ASC LIMIT 100 OFFSET {$offset}";
    $stkRslt = db_exec($searchs) or errDie("Unable to retrieve stocks from database.");
    if (pg_numrows($stkRslt) < 1) {
        $whids = "<tr><li class='err'> No Stock Items Found. Please enter the first few letters of the stock item</li></td></tr>";
        //		return "
        //			<li class='err'> There are no stock items.</li>
        //			<p>
        //			<table ".TMPL_tblDflts." width='15%'>
        //				".TBL_BR."
        //				<tr><th>Quick Links</th></tr>
        //				<tr class='".bg_class()."'>
        //					<td><a href='stock-view.php'>Back</a></td>
        //				</tr>
        //				<tr class='".bg_class()."'>
        //					<td><a href='stock-add.php'>Add Stock</a></td>
        //				</tr>
        //				<tr class='".bg_class()."'>
        //					<td><a href='main.php'>Main Menu</a></td>
        //				</tr>
        //			</table>";
    }
    if (pg_numrows($stkRslt) > 0 and pg_numrows($stkRslt) == 100) {
        $next_but = "<input type='submit' name='next' value='Next'>";
    } else {
        $next_but = "";
    }
    $heading = "";
    $showheading = "";
    while ($stk = pg_fetch_array($stkRslt)) {
        $serd = $stk['serd'] == 'yes' ? $stk['units'] > 0 ? "<a href='stock-serials.php?stkid={$stk['stkid']}'>Allocate Serial No.</a>" : "<br>" : "<br>";
        $stk['selamt'] = sprint($stk['selamt']);
        if ($sortby == "cat") {
            if ($stk['catname'] == $heading) {
                $showheading = "";
            } else {
                $showheading = "\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td><font size='3' color='white'><b>{$stk['catname']}</b></font></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Store</th>\n\t\t\t\t\t\t\t\t<th>Code</th>\n\t\t\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t\t\t<th>Class</th>\n\t\t\t\t\t\t\t\t<th>Category</th>\n\t\t\t\t\t\t\t\t<th>On Hand</th>\n\t\t\t\t\t\t\t\t<th>Retail Price</th>\n\t\t\t\t\t\t\t\t<th>Allocated</th>\n\t\t\t\t\t\t\t\t<th>On order</th>\n\t\t\t\t\t\t\t\t" . ($pure ? "" : "<th colspan='10'>Options</th><th>Remove</th>") . "\n\t\t\t\t\t\t\t</tr>";
            }
        } elseif ($sortby == "class") {
            if ($stk['classname'] == $heading) {
                $showheading = "";
            } else {
                $showheading = "\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td><font size='3' color='white'><b>{$stk['classname']}</b></font></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Store</th>\n\t\t\t\t\t\t\t\t<th>Code</th>\n\t\t\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t\t\t<th>Class</th>\n\t\t\t\t\t\t\t\t<th>Category</th>\n\t\t\t\t\t\t\t\t<th>On Hand</th>\n\t\t\t\t\t\t\t\t<th>Retail Price</th>\n\t\t\t\t\t\t\t\t<th>Allocated</th>\n\t\t\t\t\t\t\t\t<th>On order</th>\n\t\t\t\t\t\t\t\t" . ($pure ? "" : "<th colspan='10'>Options</th><th>Remove</th>") . "\n\t\t\t\t\t\t\t</tr>";
            }
        } else {
            if ($heading == "normal") {
                $showheading = "";
            } else {
                $showheading = "\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<th>Store</th>\n\t\t\t\t\t\t\t\t<th>Code</th>\n\t\t\t\t\t\t\t\t<th>Description</th>\n\t\t\t\t\t\t\t\t<th>Class</th>\n\t\t\t\t\t\t\t\t<th>Category</th>\n\t\t\t\t\t\t\t\t<th>On Hand</th>\n\t\t\t\t\t\t\t\t<th>Retail Price</th>\n\t\t\t\t\t\t\t\t<th>Allocated</th>\n\t\t\t\t\t\t\t\t<th>On order</th>\n\t\t\t\t\t\t\t\t" . ($pure ? "" : "<th colspan='10'>Options</th><th>Remove</th>") . "\n\t\t\t\t\t\t\t</tr>";
            }
        }
        // Retrieve store name from the database
        db_conn("exten");
        $sql = "SELECT whname FROM warehouses WHERE whid='{$stk['whid']}'";
        $wh_rslt = db_exec($sql) or errDie("Unable to retrieve warehouses from Cubit.");
        $whname = pg_fetch_result($wh_rslt, 0);
        $OUT .= $showheading;
        $OUT .= "\n\t\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t\t<td>{$whname}</td>\n\t\t\t\t\t\t<td>{$stk['stkcod']}</td>\n\t\t\t\t\t\t<td>{$stk['stkdes']}</td>\n\t\t\t\t\t\t<td>{$stk['classname']}</td>\n\t\t\t\t\t\t<td>{$stk['catname']}</td>\n\t\t\t\t\t\t<td align='right'>{$stk['units']}</td>\n\t\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$stk['selamt']}</td>\n\t\t\t\t\t\t<td align='right'>{$stk['alloc']}</td>\n\t\t\t\t\t\t<td align='right'>{$stk['ordered']}</td>";
        if (!$pure) {
            // Check if we've got a recipe
            $sql = "SELECT * FROM cubit.recipies WHERE m_stock_id='{$stk['stkid']}'";
            $recipe_rslt = db_exec($sql) or errDie("Unable to retrieve recipe.");
            // Create a link if neccessary
            if (pg_num_rows($recipe_rslt)) {
                $manu_href = "\n\t\t\t\t\t<a href='manu_stock.php?m_stock_id={$stk['stkid']}&key=manuout'>\n\t\t\t\t\t\tManufacture\n\t\t\t\t\t</a>";
                $unmanu_href = "\n\t\t\t\t\t<a href='manu_stock.php?m_stock_id={$stk['stkid']}&key=unmanuout'>\n\t\t\t\t\t\tDisassemble\n\t\t\t\t\t</a>";
            } else {
                $manu_href = "";
                $unmanu_href = "\n\t\t\t\t\t<a href='manu_stock.php?m_stock_id={$stk['stkid']}&key=unmanuout'>\n\t\t\t\t\t\tDisassemble\n\t\t\t\t\t</a>";
            }
            $OUT .= "\n\t\t\t\t\t\t<td><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid={$stk['stkid']}\")'>Report</a></td>\n\t\t\t\t\t\t<td><a href='stock-det.php?stkid={$stk['stkid']}'>Details</a></td>\n\t\t\t\t\t\t<td><a href='stock-edit.php?stkid={$stk['stkid']}'>Edit</a></td>\n\t\t\t\t\t\t<td><a href='stock-balance.php?stkid={$stk['stkid']}'>Transaction</a></td>\n\t\t\t\t\t\t<td>{$serd}</td>\n\t\t\t\t\t\t<td><a href='pos.php?id={$stk['stkid']}'>Barcode</a></td>\n\t\t\t\t\t\t<td>{$manu_href}</td>\n\t\t\t\t\t\t<td>{$unmanu_href}</td>";
            if ($stk['blocked'] == 'y') {
                $OUT .= "<td><a href='stock-unblock.php?stkid={$stk['stkid']}'>Unblock</a></td>";
            } else {
                $OUT .= "<td><a href='stock-block.php?stkid={$stk['stkid']}'>Block</a></td>";
            }
            if ($stk['units'] < 1 && $stk['alloc'] < 1 && $stk['lcsprice'] == 0 && $stk['csprice'] == 0) {
                $OUT .= "\n\t\t\t\t\t\t\t\t<td><a href='stock-rem.php?stkid={$stk['stkid']}'>Remove</a></td>\n\t\t\t\t\t\t\t\t<td><input type='checkbox' name='remids[]' value='{$stk['stkid']}'></td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t";
            } elseif ($stk['alloc'] > 0) {
                $OUT .= "\n\t\t\t\t\t\t<td><a href='#' onclick='openwindow(\"stock-alloc.php?stkid={$stk['stkid']}\")'>View Allocation</a></td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t</tr>";
            } else {
                $OUT .= "\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t</tr>";
            }
        }
        if ($sortby == "cat") {
            $heading = $stk['catname'];
        } elseif ($sortby == "class") {
            $heading = $stk['classname'];
        } else {
            $heading = "normal";
        }
    }
    r2sListSet("stock_view");
    if (!$pure) {
        $OUT .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td colspan='20' align='right'><input type='submit' value='Remove Selected'></td>\n\t\t\t\t</tr>\n\t\t\t</form>\n\t\t\t<form action='" . SELF . "' method='POST'>\n\t\t\t\t<input type='hidden' name='key' value='view'>\n\t\t\t\t{$whids}\n\t\t\t\t<input type='hidden' name='offset' value='{$offset}'>\n\t\t\t\t<input type='hidden' name='catid' value='{$catid}'>\n\t\t\t\t<input type='hidden' name='clasid' value='{$clasid}'>\n\t\t\t\t<input type='hidden' name='sortby' value='{$sortby}'>\n\t\t\t\t<input type='hidden' name='search_val' value='{$search_val}'>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>{$prev_but}</td>\n\t\t\t\t\t<td colspan='3'></td>\n\t\t\t\t\t<td>{$next_but}</td>\n\t\t\t\t</tr>\n\t\t\t</form>\n\t\t\t<form action ='" . SELF . "' method='POST'>\n\t\t\t\t<input type='hidden' name='key' value='export'>\n\t\t\t\t<input type='hidden' name='catid' value='{$catid}'>\n\t\t\t\t<input type='hidden' name='clasid' value='{$clasid}'>\n\t\t\t\t<input type='hidden' name='sortby' value='{$sortby}'>\n\t\t\t\t{$whids}\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr><td><input type='submit' value='Export to Spreadsheet'>\n\t\t\t</form>\n\t\t\t</table>\n\t\t\t<p>\n\t\t\t<table " . TMPL_tblDflts . " width='15%'>\n\t\t\t\t<tr><td><br></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th>Quick Links</th>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='stock-add.php'>Add Stock</a></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td><a href='main.php'>Main Menu</a></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    } else {
        $OUT .= "\n\t\t\t\t\t</form>\n\t\t\t\t\t</table>\n\t\t\t\t";
    }
    return $OUT;
}
function sendvoice($invid, $invfunc, $email, $message = false)
{
    $es = qryEmailSettings();
    if (strlen($es['smtp_host']) < 1) {
        r2sListSet("emailsettings");
        header("Location: email-settings.php");
        exit;
    }
    require_lib("validate");
    $v = new validate();
    $v->isOk($invid, "num", 1, 20, "Invalid invoice 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, printed, invnum 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;
        }
    } else {
        $sql = "SELECT cusid AS cusnum, invnum FROM nons_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);
    }
    $invnum = $inv['invnum'];
    $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['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"]);
    $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($invid);
        $attachment["name"] = "invoice{$invnum}.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[] = "To: {$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);
    //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"], "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 send_mails()
{
    /* check for valid settings */
    $settings = new dbSelect("esettings", "cubit");
    $settings->run();
    if ($settings->num_rows() <= 0) {
        r2sListSet("emailsettings");
        header("Location: email-settings.php");
        exit;
    }
    /* send them */
    extract($_POST);
    require_lib("mail.smtp");
    $send = new clsSMTPMail();
    $settings->fetch_array();
    $server = $settings->d["smtp_host"];
    $from = $settings->d["fromname"];
    $reply = $settings->d["reply"];
    $content = chunk_split($emailsavepage_content);
    $boundary = md5($content) . "=:" . strlen($content);
    $headers = array();
    $headers[] = "From: {$from}";
    $headers[] = "Reply-To: {$reply}";
    $headers[] = "Content-Type: multipart/mixed; boundary=\"{$boundary}\"";
    $headers[] = "MIME-Version: 1.0";
    if (!isset($emailsavepage_mime)) {
        $attachmime = "text/html";
        $ext = ".html";
    } else {
        $attachmime = $emailsavepage_mime;
        if ($attachmime == "text/plain") {
            $ext = ".txt";
        } else {
            $ext = "";
        }
    }
    if ($emailsavepage_name == "") {
        $filename = "attachment{$ext}";
    } else {
        $filename = preg_replace("/.php\$/", "", $emailsavepage_name) . $ext;
    }
    // company image
    $get_img = "SELECT img, imgtype FROM compinfo LIMIT 1";
    $run_img = db_exec($get_img) or errDie("Unable to get company image information.");
    if (pg_numrows($run_img) > 0) {
        $carr = pg_fetch_array($run_img);
        // hack to limit a header line to 64 chars
        $temp = $carr['img'];
        $carr['img'] = "";
        $cnt = 0;
        for ($x = 0; $x <= strlen($temp); $x++) {
            $cnt++;
            $carr['img'] .= substr($temp, $x, 1);
            if ($cnt == 64) {
                $carr['img'] .= "\n";
                $cnt = 0;
            }
        }
        if (strlen($carr['img']) > 10) {
            if ($carr['imgtype'] == "image/jpeg") {
                $imgfilename = "logo.jpg";
            } elseif ($carr['imgtype'] == "image/png") {
                $imgfilename = "logo.png";
            } elseif ($carr['imgtype'] == "image/gif") {
                $imgfilename = "logo.gif";
            }
            $imagemsg = "Content-Type: {$carr['imgtype']}; charset=UTF-8\r\n" . "Content-Transfer-Encoding: base64\r\n" . "Content-Disposition: attachment; filename=\"{$imgfilename}\"" . "\r\n\r\n" . "{$carr['img']}\n";
            $content = base64_encode(str_replace("compinfo/getimg.php", "{$imgfilename}", base64_decode($content)));
        }
    }
    // hack to limit a header line to 64 chars
    $temp = $content;
    $content = "";
    $cnt = 0;
    for ($x = 0; $x <= strlen($temp); $x++) {
        $cnt++;
        $content .= substr($temp, $x, 1);
        if ($cnt == 64) {
            $content .= "\n";
            $cnt = 0;
        }
    }
    // the actual page
    $pagecontent = "Content-Type: {$attachmime}; charset=UTF-8\r\n" . "Content-Transfer-Encoding: base64\r\n" . "Content-Disposition: attachment; filename=\"{$filename}\"" . "\r\n\r\n" . "{$content}";
    $msg = "--{$boundary}\n" . "Content-Type: text/plain; charset=UTF-8\r\n\nDocument Attached\n\n" . "--{$boundary}\n" . "{$pagecontent}\n\n" . "--{$boundary}\n";
    if (isset($imagemsg) and strlen($imagemsg) > 0) {
        $msg .= "{$imagemsg}\n" . "--{$boundary}--\n";
    }
    $OUT = "\n\t<table " . TMPL_tblDflts . ">\n\t\t<tr>\n\t\t\t<th>Customer</th>\n\t\t\t<th>Email Status</th>\n\t\t</tr>";
    foreach ($emailcust as $cusnum => $email) {
        $custheaders = implode("\r\n", $headers);
        $custheaders .= "\r\nTo: \"{$surnames[$cusnum]}\" <{$email}>";
        $ret = $send->sendMessages($server, 25, "", "", "", $email, $from, $emailsavepage_subject, $msg, $custheaders);
        $redir = "";
        if ($cusnum == "custom_address") {
            $redir = "\n\t\t\t\t<td valign='center'>\n\t\t\t\t\t<form action='customers-new.php' method='POST'>\n\t\t\t\t\t\t<input type='hidden' name='surname' value='{$surnames[$cusnum]}'>\n\t\t\t\t\t\t<input type='hidden' name='email' value='{$email}'>\n\t\t\t\t\t\t<input type='submit' value='Add As Customer'>\n\t\t\t\t\t</form>\n\t\t\t\t</td>";
        }
        $OUT .= "\n\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t<td>{$surnames[$cusnum]}</td>\n\t\t\t\t<td>{$ret}</td>\n\t\t\t\t{$redir}\n\t\t\t</tr>";
    }
    $OUT .= "</table><br>" . mkQuickLinks();
    return $OUT;
}
function printInv($_POST)
{
    # get vars
    extract($_POST);
    # validate input
    require_lib("validate");
    $v = new validate();
    $v->isOk($from_day, "num", 1, 2, "Invalid from Date day.");
    $v->isOk($from_month, "num", 1, 2, "Invalid from Date month.");
    $v->isOk($from_year, "num", 1, 4, "Invalid from Date Year.");
    $v->isOk($to_day, "num", 1, 2, "Invalid to Date day.");
    $v->isOk($to_month, "num", 1, 2, "Invalid to Date month.");
    $v->isOk($to_year, "num", 1, 4, "Invalid to Date Year.");
    # mix dates
    $fromdate = $from_year . "-" . $from_month . "-" . $from_day;
    $todate = $to_year . "-" . $to_month . "-" . $to_day;
    if (!checkdate($from_month, $from_day, $from_year)) {
        $v->isOk($fromdate, "num", 1, 1, "Invalid from date.");
    }
    if (!checkdate($to_month, $to_day, $to_year)) {
        $v->isOk($todate, "num", 1, 1, "Invalid to date.");
    }
    # display errors, if any
    if ($v->isError()) {
        $confirm = "";
        $errors = $v->getErrors();
        foreach ($errors as $e) {
            $confirm .= "<li class='err'>-" . $e["msg"] . "</li>";
        }
        return $confirm;
    }
    $accnum = remval($accnum);
    if (strlen($accnum) > 0) {
        db_conn('cubit');
        $Sl = "SELECT * FROM customers WHERE lower(accno)=lower('{$accnum}')";
        $Ri = db_exec($Sl);
        if (pg_num_rows($Ri) < 1) {
            return "<li class='err'>Invalid account number</li>" . slct();
        }
        $cd = pg_fetch_array($Ri);
        $cusnum = $cd['cusnum'];
    }
    /* make named r2s snapshop */
    r2sListSet("invoice_stk_view");
    # Set up table to display in
    $printInv = "\n\t\t<h3>View invoices. Date Range {$fromdate} to {$todate}</h3>\n\t\t<form action='invoice-proc.php' method='GET'>\n\t\t<table " . TMPL_tblDflts . ">\n\t\t\t<tr>\n\t\t\t\t<th>Department</th>\n\t\t\t\t<th>No.</th>\n\t\t\t\t<th>Invoice Date</th>\n\t\t\t\t<th>Customer Name</th>\n\t\t\t\t<th>Order No</th>\n\t\t\t\t<th>Customer Order No</th>\n\t\t\t\t<th>Grand Total</th>\n\t\t\t\t<th colspan='2'>Balance</th>\n\t\t\t\t<th>Documents</th>\n\t\t\t\t<th colspan='6'>Options</th>\n\t\t\t</tr>";
    # connect to database
    db_connect();
    # Query server
    $i = 0;
    $tot1 = 0;
    $tot2 = 0;
    if (isset($all)) {
        $sql = "SELECT * FROM invoices WHERE done = 'y' AND odate>='{$fromdate}' AND odate <= '{$todate}' AND div = '" . USER_DIV . "' ORDER BY invid DESC";
    } else {
        $sql = "SELECT * FROM invoices WHERE done = 'y' AND odate>='{$fromdate}' AND odate <= '{$todate}' AND cusnum = {$cusnum} AND div = '" . USER_DIV . "' ORDER BY invid DESC";
    }
    $invRslt = db_exec($sql) or errDie("Unable to retrieve invoices from database.");
    // Retrieve the reprint setting
    db_conn("cubit");
    $sql = "SELECT filename FROM template_settings WHERE template='reprints' AND div='" . USER_DIV . "'";
    $tsRslt = db_exec($sql) or errDie("Unable to retrieve template settings from Cubit.");
    $template = pg_fetch_result($tsRslt, 0);
    if (pg_numrows($invRslt) < 1) {
        $printInv = "<li class='err'> No Outstanding Invoices found for the selected customer.</li><br>";
    } else {
        while ($inv = pg_fetch_array($invRslt)) {
            $inv['total'] = sprint($inv['total']);
            $inv['balance'] = sprint($inv['balance']);
            $tot1 = $tot1 + $inv['total'];
            $tot2 = $tot2 + $inv['balance'];
            # Get documents
            $docs = doclib_getdocs("inv", $inv['invnum']);
            # Format date
            $inv['odate'] = explode("-", $inv['odate']);
            $inv['odate'] = $inv['odate'][2] . "-" . $inv['odate'][1] . "-" . $inv['odate'][0];
            if ($inv['printed'] == "n") {
                $Dis = "TI {$inv['invid']}";
            } else {
                $Dis = "{$inv['invnum']}";
            }
            $det = "invoice-details.php";
            $print = "invoice-print.php";
            $edit = "cust-credit-stockinv.php";
            $reprint = "invoice-reprint.php";
            if (isset($mode) && $mode == "creditnote") {
                $note = "<input type='button' onClick='document.location.href=\"invoice-note.php?invid={$inv['invid']}\";' value='Credit Note'>";
            } else {
                $note = "<a href='invoice-note.php?invid={$inv['invid']}'>Credit Note</a>";
            }
            if ($template == "default") {
                $template = "invoice-pdf-reprint.php";
            } elseif ($template == "new") {
                $template = "pdf-tax-invoice.php";
            }
            $pdfreprint = $template;
            $chbox = "<input type=checkbox name='invids[]' value='{$inv['invid']}' checked=yes>";
            if ($inv['location'] == 'int') {
                $det = "intinvoice-details.php";
                $print = "intinvoice-print.php";
                $edit = "intinvoice-new.php";
                $reprint = "intinvoice-reprint.php";
                if (isset($mode) && $mode == "creditnote") {
                    $note = "<input type='button' onClick='document.location.href=\"intinvoice-note.php?invid={$inv['invid']}\";' value='Credit Note'>";
                } else {
                    $note = "<a href='intinvoice-note.php?invid={$inv['invid']}'>Credit Note</a>";
                }
                if ($template == "default") {
                    $template = "intinvoice-pdf-reprint.php";
                } elseif ($template == "new") {
                    $template = "pdf-tax-invoice.php";
                }
                $pdfreprint = $template;
                $chbox = "<br>";
            }
            if ($inv['serd'] == 'n') {
                $chbox = "";
            }
            $sp4 = "&nbsp;&nbsp;&nbsp;&nbsp;";
            $fbal = "{$sp4}--{$sp4}";
            $bcurr = CUR;
            if ($inv['location'] == 'int') {
                $fbal = "{$sp4} {$inv['currency']} {$inv['fbalance']}";
                $bcurr = $inv['currency'];
            }
            //<a href='invoice-email.php?invid=$inv[invid]'>Email</a>
            $printInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td>{$inv['deptname']}</td>\n\t\t\t\t\t<td>{$Dis}</td>\n\t\t\t\t\t<td align='center'>{$inv['odate']}</td>\n\t\t\t\t\t<td>{$inv['cusname']} {$inv['surname']}</td>\n\t\t\t\t\t<td align='right'>{$inv['ordno']}</td>\n\t\t\t\t\t<td align='right'>{$inv['cordno']}</td>\n\t\t\t\t\t<td align='right' nowrap>{$bcurr} {$inv['total']}</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$inv['balance']}</td>\n\t\t\t\t\t<td align='right' nowrap> {$fbal}</td>\n\t\t\t\t\t<td>{$docs}</td>\n\t\t\t\t\t<td><a href='{$det}?invid={$inv['invid']}'>Details</a></td>\n\t\t\t\t\t<td><input type='checkbox' name='evs[{$inv['invid']}]'></td>";
            if ($inv['printed'] == "n") {
                $printInv .= "\n\t\t\t\t\t\t<td><a href='{$edit}?invid={$inv['invid']}&cont=1&letters='>Edit</a></td>\n\t\t\t\t\t\t<td><a target='_blank' href='{$print}?invid={$inv['invid']}'>Process</a></td>\n\t\t\t\t\t\t<td align='center'>{$chbox}</td>\n\t\t\t\t\t\t<td>&nbsp</td>\n\t\t\t\t\t</tr>";
            } else {
                db_conn($inv["prd"]);
                $sql = "SELECT * FROM inv_notes WHERE invid='{$inv['invid']}'";
                $note_rslt = db_exec($sql) or errDie("Unable to retrieve credit notes from Cubit.");
                if (!pg_num_rows($note_rslt)) {
                    $delnote = "<td><a target='_blank' href='invoice-delnote.php?invid={$inv['invid']}'>Delivery Note</a></td>";
                } else {
                    $delnote = "<td>&nbsp;</td>";
                }
                if (round($inv['total'], 0) != round($inv['nbal'], 0)) {
                    $printInv .= "\n\t\t\t\t\t\t\t<td>{$note}</td>\n\t\t\t\t\t\t\t<td><a target='_blank' href='{$reprint}?invid={$inv['invid']}&type=invreprint'>Reprint</a></td>\n\t\t\t\t\t\t\t<td><a href='pdf/{$pdfreprint}?invid={$inv['invid']}&type=invreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t\t\t{$delnote}\n\t\t\t\t\t\t</tr>";
                } else {
                    $printInv .= "\n\t\t\t\t\t\t\t<td>Settled</td>\n\t\t\t\t\t\t\t<td><a target='_blank' href='{$reprint}?invid={$inv['invid']}&type=invreprint'>Reprint</a></td>\n\t\t\t\t\t\t\t<td><a href='pdf/{$pdfreprint}?invid={$inv['invid']}&type=invreprint' target='_blank'>Reprint in PDF</a></td>\n\t\t\t\t\t\t\t{$delnote}\n\t\t\t\t\t\t</tr>";
                }
            }
            $i++;
        }
    }
    $tot1 = sprint($tot1);
    $tot2 = sprint($tot2);
    //	$bgColor = bgcolor($i);
    // Layout
    if ($i > 0) {
        $printInv .= "\n\t\t\t\t<tr class='" . bg_class() . "'>\n\t\t\t\t\t<td colspan='6'>Totals:{$i}</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$tot1}</td>\n\t\t\t\t\t<td align='right' nowrap>" . CUR . " {$tot2}</td>\n\t\t\t\t\t<td colspan='3'><br></td>\n\t\t\t\t\t<td colspan='3' align='right'><input type='submit' value='Email Selected' name='email'>\n\t\t\t\t\t</td><td colspan='10' align='right'><input type='submit' value='Process Selected' name='proc'></td>\n\t\t\t\t</tr>\n\t\t\t</table>";
    }
    $printInv .= "\n\t\t</table>\n\t\t</form>";
    return $printInv;
}