Beispiel #1
0
    $reqperm = "View Billable Items";
} else {
    $reqperm = "Manage Billable Items";
}
$aInt = new WHMCS_Admin($reqperm);
$aInt->title = $aInt->lang("billableitems", "title");
$aInt->sidebar = "billing";
$aInt->icon = "billableitems";
$aInt->requiredFiles(array("invoicefunctions", "gatewayfunctions"));
if ($action == "save") {
    check_token("WHMCS.admin.default");
    if (!$userid) {
        $aInt->gracefulExit($aInt->lang("billableitems", "noclientsmsg"));
    }
    $duedate = toMySQLDate($duedate);
    getUsersLang($userid);
    if ($id) {
        if ($hours != 0) {
            if (strpos($description, " " . $_LANG['billableitemshours'] . " @ ")) {
                $description = substr($description, 0, strrpos($description, " - ")) . " - " . $hours . " " . $_LANG['billableitemshours'] . " @ " . $amount . "/" . $_LANG['billableitemshour'];
            }
            $amount = $amount * $hours;
        }
        update_query("tblbillableitems", array("userid" => $userid, "description" => $description, "hours" => $hours, "amount" => $amount, "recur" => $recur, "recurcycle" => $recurcycle, "recurfor" => $recurfor, "invoiceaction" => $invoiceaction, "duedate" => $duedate, "invoicecount" => $invoicecount), array("id" => $id));
    } else {
        if ($hours != 0) {
            $description .= " - " . $hours . " " . $_LANG['billableitemshours'] . " @ " . $amount . "/" . $_LANG['billableitemshour'];
            $amount = $amount * $hours;
        }
        $id = insert_query("tblbillableitems", array("userid" => $userid, "description" => $description, "hours" => $hours, "amount" => $amount, "recur" => $recur, "recurcycle" => $recurcycle, "recurfor" => $recurfor, "invoiceaction" => $invoiceaction, "duedate" => $duedate));
    }
Beispiel #2
0
 public function getLineItems($entitydecode = false)
 {
     global $whmcs;
     getUsersLang($this->getData("userid"));
     $invoiceid = $this->getID();
     $invoiceitems = array();
     if ($whmcs->get_config("GroupSimilarLineItems")) {
         $result = full_query("SELECT COUNT(*),id,type,relid,description,amount,taxed FROM tblinvoiceitems WHERE invoiceid=" . (int) $invoiceid . " GROUP BY `description`,`amount` ORDER BY id ASC");
     } else {
         $result = select_query("tblinvoiceitems", "0,id,type,relid,description,amount,taxed", array("invoiceid" => $invoiceid), "id", "ASC");
     }
     while ($data = mysql_fetch_array($result)) {
         $qty = $data[0];
         $description = $data[4];
         $amount = $data[5];
         $taxed = $data[6] ? true : false;
         if (1 < $qty) {
             $description = $qty . " x " . $description . " @ " . $amount . $whmcs->get_lang("invoiceqtyeach");
             $amount *= $qty;
         }
         if ($entitydecode) {
             $description = htmlspecialchars(html_entity_decode($description, ENT_QUOTES));
         } else {
             $description = nl2br($description);
         }
         $invoiceitems[] = array("id" => $data[1], "type" => $data[2], "relid" => $data[3], "description" => $description, "rawamount" => $amount, "amount" => formatCurrency($amount), "taxed" => $taxed);
     }
     return $invoiceitems;
 }
Beispiel #3
0
        calcCartTotals(true);
        unset($_SESSION['uid']);
        if ($orderstatus == "Active") {
            update_query("tblorders", array("status" => "Active"), array("id" => $_SESSION['orderdetails']['OrderID']));
            if (is_array($_SESSION['orderdetails']['Products'])) {
                foreach ($_SESSION['orderdetails']['Products'] as $productid) {
                    update_query("tblhosting", array("domainstatus" => "Active"), array("id" => $productid));
                }
            }
            if (is_array($_SESSION['orderdetails']['Domains'])) {
                foreach ($_SESSION['orderdetails']['Domains'] as $domainid) {
                    update_query("tbldomains", array("status" => "Active"), array("id" => $domainid));
                }
            }
        }
        getUsersLang(0);
        redir("action=view&id=" . $_SESSION['orderdetails']['OrderID'], "orders.php");
        exit;
    }
}
releaseSession();
$regperiods = $regperiodss = "";
$regperiod = 1;
while ($regperiod <= 10) {
    $regperiods .= "<option value=\"" . $regperiod . "\">" . $regperiod . " " . $aInt->lang("domains", "year" . $regperiodss) . "</option>";
    $regperiodss = "s";
    ++$regperiod;
}
$jquerycode = "\n\$(function(){\n    var prodtemplate = \$(\"#products .product:first\").clone();\n    var productsCount = 0;\n    window.addProduct = function(){\n        productsCount++;\n        var order = prodtemplate.clone().find(\"*\").each(function(){\n            var newId = this.id.substring(0, this.id.length-1) + productsCount;\n\n            \$(this).prev().attr(\"for\", newId); // update label for\n            this.id = newId; // update id\n\n        }).end()\n        .attr(\"id\", \"ord\" + productsCount)\n        .appendTo(\"#products\");\n        return false;\n    }\n    \$(\".addproduct\").click(addProduct);\n\n    var domainsCount = 0;\n    window.addDomain = function(){\n        domainsCount++;\n        \$('<table class=\"form\" width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"3\" style=\"margin-top:10px;\"><tr><td width=\"130\" class=\"fieldlabel\">" . $aInt->lang("domains", "regtype", 1) . "</td><td class=\"fieldarea\"><input type=\"radio\" name=\"regaction['+domainsCount+']\" id=\"domnon'+domainsCount+'\" value=\"\" onclick=\"loaddomainoptions(this,0);updatesummary()\" checked /> <label for=\"domnon'+domainsCount+'\">" . $aInt->lang("global", "none", 1) . "</label> <input type=\"radio\" name=\"regaction['+domainsCount+']\" value=\"register\" id=\"domreg'+domainsCount+'\" onclick=\"loaddomainoptions(this,1);updatesummary()\" /> <label for=\"domreg'+domainsCount+'\">" . $aInt->lang("domains", "register", 1) . "</label> <input type=\"radio\" name=\"regaction['+domainsCount+']\" value=\"transfer\" id=\"domtrf'+domainsCount+'\" onclick=\"loaddomainoptions(this,2);updatesummary()\" /> <label for=\"domtrf'+domainsCount+'\">" . $aInt->lang("domains", "transfer", 1) . "</label></td></tr><tr class=\"hiddenrow\" id=\"domrowdn'+domainsCount+'\" style=\"display:none;\"><td class=\"fieldlabel\">" . $aInt->lang("fields", "domain", 1) . "</td><td class=\"fieldarea\"><input type=\"text\" class=\"regdomain\" id=\"regdomain'+domainsCount+'\" name=\"regdomain['+domainsCount+']\" size=\"40\" onkeyup=\"updatesummary()\" /></td></tr><tr class=\"hiddenrow\" id=\"domrowrp'+domainsCount+'\" style=\"display:none;\"><td class=\"fieldlabel\">" . $aInt->lang("domains", "regperiod", 1) . "</td><td class=\"fieldarea\"><select name=\"regperiod['+domainsCount+']\" onchange=\"updatesummary()\">" . $regperiods . "</select></td></tr><tr class=\"hiddentransrow\" id=\"domrowep'+domainsCount+'\" style=\"display:none;\"><td class=\"fieldlabel\">" . $aInt->lang("domains", "eppcode", 1) . "</td><td class=\"fieldarea\"><input type=\"text\" name=\"eppcode['+domainsCount+']\" size=\"20\" /></td></tr><tr class=\"hiddenrow\" id=\"domrowad'+domainsCount+'\" style=\"display:none;\"><td class=\"fieldlabel\">" . $aInt->lang("domains", "addons", 1) . "</td><td class=\"fieldarea\"><label><input type=\"checkbox\" name=\"dnsmanagement['+domainsCount+']\" onclick=\"updatesummary()\" /> " . $aInt->lang("domains", "dnsmanagement", 1) . "</label> <label><input type=\"checkbox\" name=\"emailforwarding['+domainsCount+']\" onclick=\"updatesummary()\" /> " . $aInt->lang("domains", "emailforwarding", 1) . "</label> <label><input type=\"checkbox\" name=\"idprotection['+domainsCount+']\" onclick=\"updatesummary()\" /> " . $aInt->lang("domains", "idprotection", 1) . "</label></td></tr><tr id=\"domainaddlfieldserase'+domainsCount+'\" style=\"display:none\"></tr></table>').appendTo(\"#domains\");\n        return false;\n    }\n    \$(\".adddomain\").click(addDomain);\n\n    \$(\"#domain0\").keyup(function() {\n      \$(\"#regdomain0\").val(\$(\"#domain0\").val());\n    });\n\n\t\$(\".regdomain\").live(\"keyup\", function(){\n    \tvar domainname = \$(this).val();\n\t\tif(domainname.length >= 5){\n\t\t\tvar ord = \$(this).attr(\"id\").replace(\"regdomain\",\"\");\n\t\t\t\$.post(\"ordersadd.php\", { action: \"getdomainaddlfields\", domain: domainname, order:ord, token: \"" . generate_token("plain") . "\" },\n\t\t\tfunction(data){\n\t\t\t\t\$(\".domainaddlfields\"+ord).remove();\n\t\t\t\t\$(\"#domainaddlfieldserase\"+ord).after(data);\n\t\t\t});\n\t\t}\n    });\n\n});\n";
$jscode = "\nfunction loadproductoptions(piddd) {\n    var ord = piddd.id.substring(3);\n    var pid = piddd.value;\n    var billingcycle = \$(\"#billingcycle option:selected\").val();\n    if (pid==0) {\n        \$(\"#productconfigoptions\"+ord).html(\"\");\n        \$(\"#addonsrow\"+ord).hide();\n        updatesummary();\n    } else {\n    \$(\"#productconfigoptions\"+ord).html(\"<p align=\\\"center\\\">" . $aInt->lang("global", "loading") . "<br><img src=\\\"../images/loading.gif\\\"></p>\");\n    \$.post(\"ordersadd.php\", { action: \"getconfigoptions\", pid: pid, cycle: billingcycle, orderid: ord, token: \"" . generate_token("plain") . "\" },\n    function(data){\n        if (data.addons) {\n            \$(\"#addonsrow\"+ord).show();\n            \$(\"#addonscont\"+ord).html(data.addons);\n        } else {\n            \$(\"#addonsrow\"+ord).hide();\n        }\n        \$(\"#productconfigoptions\"+ord).html(data.options);\n        updatesummary();\n    },\"json\");\n    }\n}\nfunction loaddomainoptions(domrd,type) {\n    var ord = domrd.id.substring(6);\n    if (type==1) {\n        \$(\"#domrowdn\"+ord).css(\"display\",\"\");\n        \$(\"#domrowrp\"+ord).css(\"display\",\"\");\n        \$(\"#domrowep\"+ord).css(\"display\",\"none\");\n        \$(\"#domrowad\"+ord).css(\"display\",\"\");\n    } else if (type==2) {\n        \$(\"#domrowdn\"+ord).css(\"display\",\"\");\n        \$(\"#domrowrp\"+ord).css(\"display\",\"\");\n        \$(\"#domrowep\"+ord).css(\"display\",\"\");\n        \$(\"#domrowad\"+ord).css(\"display\",\"\");\n    } else {\n        \$(\"#domrowdn\"+ord).css(\"display\",\"none\");\n        \$(\"#domrowrp\"+ord).css(\"display\",\"none\");\n        \$(\"#domrowep\"+ord).css(\"display\",\"none\");\n        \$(\"#domrowad\"+ord).css(\"display\",\"none\");\n    }\n}\nfunction updatesummary() {\n    jQuery.post(\"ordersadd.php\", \"submitorder=1&calconly=1&\"+jQuery(\"#orderfrm\").serialize(),\n    function(data){\n        jQuery(\"#ordersumm\").html(data);\n    });\n}\n";
ob_start();
Beispiel #4
0
function convertQuotetoInvoice($id, $invoicetype, $invoiceduedate, $depositpercent, $depositduedate, $finalduedate, $sendemail)
{
    global $CONFIG;
    global $_LANG;
    $result = select_query("tblquotes", "", array("id" => $id));
    $data = mysql_fetch_array($result);
    $userid = $data['userid'];
    $firstname = $data['firstname'];
    $lastname = $data['lastname'];
    $companyname = $data['companyname'];
    $email = $data['email'];
    $address1 = $data['address1'];
    $address2 = $data['address2'];
    $city = $data['city'];
    $state = $data['state'];
    $postcode = $data['postcode'];
    $country = $data['country'];
    $phonenumber = $data['phonenumber'];
    $currency = $data['currency'];
    if ($userid) {
        getUsersLang($userid);
        $clientsdetails = getClientsDetails($userid);
        $state = $clientsdetails['state'];
        $country = $clientsdetails['country'];
    } else {
        if (!function_exists("addClient")) {
            require ROOTDIR . "/clientfunctions.php";
        }
        $_SESSION['currency'] = $currency;
        $userid = addClient($firstname, $lastname, $companyname, $email, $address1, $address2, $city, $state, $postcode, $country, $phonenumber, substr(md5($id), 0, 10), 0, "", "on");
    }
    if ($CONFIG['TaxEnabled'] == "on") {
        $taxlevel1 = getTaxRate(1, $state, $country);
        $taxlevel2 = getTaxRate(2, $state, $country);
        $taxrate = $taxlevel1['rate'];
        $taxrate2 = $taxlevel2['rate'];
    }
    $subtotal = $data['subtotal'];
    $tax1 = $data['tax1'];
    $tax2 = $data['tax2'];
    $total = $data['total'];
    $result = select_query("tblpaymentgateways", "gateway", array("setting" => "name"), "order", "ASC");
    $data = mysql_fetch_array($result);
    $gateway = $data['gateway'];
    $duedate = $finaldate = "";
    if ($invoicetype == "deposit") {
        if ($depositduedate) {
            $duedate = toMySQLDate($depositduedate);
        }
        $finaldate = $finalduedate ? toMySQLDate($finalduedate) : date("Y-m-d");
    } else {
        if ($invoiceduedate) {
            $duedate = toMySQLDate($invoiceduedate);
        }
    }
    if (!$duedate) {
        $duedate = date("Y-m-d");
    }
    $invoiceid = insert_query("tblinvoices", array("date" => "now()", "duedate" => $duedate, "userid" => $userid, "status" => "Unpaid", "paymentmethod" => $gateway, "taxrate" => $taxrate, "taxrate2" => $taxrate2, "subtotal" => $subtotal, "tax" => $tax1, "tax2" => $tax2, "total" => $total, "notes" => $_LANG['quoteref'] . $id));
    if ($finaldate) {
        $finalinvoiceid = insert_query("tblinvoices", array("date" => "now()", "duedate" => $finaldate, "userid" => $userid, "status" => "Unpaid", "paymentmethod" => $gateway, "taxrate" => $taxrate, "taxrate2" => $taxrate2, "subtotal" => $subtotal, "tax" => $tax1, "tax2" => $tax2, "total" => $total, "notes" => $_LANG['quoteref'] . $id));
    }
    $result = select_query("tblquoteitems", "", array("quoteid" => $id), "id", "ASC");
    while ($data = mysql_fetch_array($result)) {
        $line_id = $data['id'];
        $line_desc = $data['description'];
        $line_qty = $data['quantity'];
        $line_unitprice = $data['unitprice'];
        $line_discount = $data['discount'];
        $line_taxable = $data['taxable'];
        $line_total = format_as_currency($line_qty * $line_unitprice * (1 - $line_discount / 100));
        $lineitemdesc = "" . $line_qty . " x " . $line_desc . " @ " . $line_unitprice;
        if (0 < $line_discount) {
            $lineitemdesc .= " - " . $line_discount . "% " . $_LANG['orderdiscount'];
        }
        if ($finalinvoiceid) {
            $originalamount = $line_total;
            $line_total = $originalamount * ($depositpercent / 100);
            $final_amount = $originalamount - $line_total;
            insert_query("tblinvoiceitems", array("invoiceid" => $finalinvoiceid, "userid" => $userid, "description" => $lineitemdesc . " (" . (100 - $depositpercent) . "% " . $_LANG['quotefinalpayment'] . ")", "amount" => $final_amount, "taxed" => $line_taxable));
            $lineitemdesc .= " (" . $depositpercent . "% " . $_LANG['quotedeposit'] . ")";
        }
        insert_query("tblinvoiceitems", array("invoiceid" => $invoiceid, "userid" => $userid, "description" => $lineitemdesc, "amount" => $line_total, "taxed" => $line_taxable));
    }
    if (!function_exists("updateInvoiceTotal")) {
        require ROOTDIR . "/includes/invoicefunctions.php";
    }
    updateInvoiceTotal($invoiceid);
    if ($finalinvoiceid) {
        updateInvoiceTotal($finalinvoiceid);
    }
    run_hook("InvoiceCreationPreEmail", array("invoiceid" => $invoiceid));
    if ($finalinvoiceid) {
        run_hook("InvoiceCreationPreEmail", array("invoiceid" => $finalinvoiceid));
    }
    if ($sendemail) {
        sendMessage("Invoice Created", $invoiceid);
        if ($finalinvoiceid) {
            sendMessage("Invoice Created", $finalinvoiceid);
        }
    }
    run_hook("InvoiceCreated", array("invoiceid" => $invoiceid));
    if ($finalinvoiceid) {
        run_hook("InvoiceCreated", array("invoiceid" => $finalinvoiceid));
    }
    if (1 < $CONFIG['InvoiceIncrement']) {
        $invoiceincrement = $CONFIG['InvoiceIncrement'] - 1;
        $counter = 1;
        while ($counter <= $invoiceincrement) {
            $tempinvoiceid = insert_query("tblinvoices", array("date" => "now()"));
            delete_query("tblinvoices", array("id" => $tempinvoiceid));
            $counter += 1;
        }
    }
    update_query("tblquotes", array("userid" => $userid, "stage" => "Accepted"), array("id" => $id));
    return $invoiceid;
}
Beispiel #5
0
 function sendMessage($func_messagename, $func_id, $extra = "", $displayresult = "", $attachments = "")
 {
     global $whmcs;
     global $CONFIG;
     global $_LANG;
     global $encryption_key;
     global $currency;
     global $downloads_dir;
     global $fromname;
     global $fromemail;
     global $whmcs;
     $sysurl = $CONFIG['SystemSSLURL'] ? $CONFIG['SystemSSLURL'] : $CONFIG['SystemURL'];
     $nosavemaillog = false;
     $email_merge_fields = array();
     if ($func_messagename == "defaultnewacc") {
         $result = select_query("tblproducts", "tblproducts.welcomeemail", array("tblhosting.id" => $func_id), "", "", "", "tblhosting ON tblhosting.packageid=tblproducts.id");
         $data = mysql_fetch_array($result);
         if (!$data['welcomeemail']) {
             return false;
         }
         $result = select_query("tblemailtemplates", "name", array("id" => $data['welcomeemail']));
         $data = mysql_fetch_array($result);
         $func_messagename = $data['name'];
     }
     if ($func_messagename == "Order Confirmation") {
         $userid = $func_id;
     }
     $result = select_query("tblemailtemplates", "", array("name" => $func_messagename, "language" => ""));
     $data = mysql_fetch_array($result);
     $emailtplid = $data['id'];
     $type = $data['type'];
     $subject = $data['subject'];
     $message = $data['message'];
     $tplattachments = $data['attachments'];
     $fromname = $data['fromname'];
     $fromemail = $data['fromemail'];
     $disabled = $data['disabled'];
     $copyto = $data['copyto'];
     $plaintext = $data['plaintext'];
     if (!$emailtplid) {
         logActivity("EMAILERROR: Email Template " . $func_messagename . " Not Found");
         return false;
     }
     if (!$func_id && $type != "support") {
         return false;
     }
     if ($disabled) {
         if ($displayresult) {
             echo "<p>The '" . $func_messagename . "' email template has been disabled (" . $subject . ")</p>";
         }
         return false;
     }
     if ($type == "invoice") {
         $invoice = new WHMCS_Invoice($func_id);
         $valid = $invoice->loadData();
         if (!$valid) {
             return false;
         }
         $data = $invoice->getOutput();
         $userid = $data['userid'];
         $invoicedescription = "";
         $invoiceitems = $invoice->getLineItems();
         foreach ($invoiceitems as $item) {
             $invoicedescription .= $item['description'] . " " . $item['amount'] . "<br>\r\n";
         }
         $invoicedescription .= "------------------------------------------------------<br>\r\n";
         $invoicedescription .= $_LANG['invoicessubtotal'] . ": " . $data['subtotal'] . "<br>\r\n";
         if (0 < $data['taxrate']) {
             $invoicedescription .= $data['taxrate'] . "% " . $data['taxname'] . ": " . $data['tax'] . "<br>\r\n";
         }
         if (0 < $data['taxrate2']) {
             $invoicedescription .= $data['taxrate2'] . "% " . $data['taxname2'] . ": " . $data['tax2'] . "<br>\r\n";
         }
         $invoicedescription .= $_LANG['invoicescredit'] . ": " . $data['credit'] . "<br>\r\n";
         $invoicedescription .= $_LANG['invoicestotal'] . ": " . $data['total'] . "";
         $paymentbutton = $invoice->getPaymentLink();
         $email_merge_fields['invoice_id'] = $data['invoiceid'];
         $email_merge_fields['invoice_num'] = $data['invoicenum'];
         $email_merge_fields['invoice_date_created'] = $data['date'];
         $email_merge_fields['invoice_date_due'] = $data['duedate'];
         $email_merge_fields['invoice_date_paid'] = $data['datepaid'];
         $email_merge_fields['invoice_items'] = $invoiceitems;
         $email_merge_fields['invoice_html_contents'] = $invoicedescription;
         $email_merge_fields['invoice_subtotal'] = $data['subtotal'];
         $email_merge_fields['invoice_credit'] = $data['credit'];
         $email_merge_fields['invoice_tax'] = $data['tax'];
         $email_merge_fields['invoice_tax_rate'] = $data['taxrate'] . "%";
         $email_merge_fields['invoice_tax2'] = $data['tax2'];
         $email_merge_fields['invoice_tax_rate2'] = $data['taxrate2'] . "%";
         $email_merge_fields['invoice_total'] = $data['total'];
         $email_merge_fields['invoice_amount_paid'] = $data['amountpaid'];
         $email_merge_fields['invoice_balance'] = $data['balance'];
         $email_merge_fields['invoice_status'] = $data['statuslocale'];
         $email_merge_fields['invoice_last_payment_amount'] = $data['lastpaymentamount'];
         $email_merge_fields['invoice_last_payment_transid'] = $data['lastpaymenttransid'];
         $email_merge_fields['invoice_payment_link'] = $paymentbutton;
         $email_merge_fields['invoice_payment_method'] = $data['paymentmethod'];
         $email_merge_fields['invoice_link'] = "<a href=\"" . $sysurl . "/viewinvoice.php?id=" . $data['id'] . "\">" . $sysurl . "/viewinvoice.php?id=" . $data['id'] . "</a>";
         $email_merge_fields['invoice_notes'] = $data['notes'];
         $email_merge_fields['invoice_subscription_id'] = $data['subscrid'];
         $email_merge_fields['invoice_previous_balance'] = $data['clientpreviousbalance'];
         $email_merge_fields['invoice_all_due_total'] = $data['clienttotaldue'];
         $email_merge_fields['invoice_total_balance_due'] = $data['clientbalancedue'];
         if ($CONFIG['EnablePDFInvoices']) {
             $invoice->pdfCreate();
             $invoice->pdfInvoicePage();
             $attachmentdata = $invoice->pdfOutput();
             $attachmentfilename = $_LANG['invoicefilename'] . $data['invoicenum'] . ".pdf";
         }
     } else {
         if ($type == "support") {
             if ($func_messagename == "Bounce Message") {
                 $firstname = $extra[0];
                 $email = $extra[1];
             } else {
                 $result = select_query("tbltickets", "", array("id" => $func_id));
                 $data = mysql_fetch_array($result);
                 $id = $data['id'];
                 $deptid = $data['did'];
                 $tid = $data['tid'];
                 $ticketcc = $data['cc'];
                 $c = $data['c'];
                 $userid = $data['userid'];
                 $date = $data['date'];
                 $title = $data['title'];
                 $tmessage = $data['message'];
                 $status = $data['status'];
                 $urgency = $data['urgency'];
                 $attachment = $data['attachment'];
                 if ($userid) {
                     getUsersLang($userid);
                 } else {
                     $whmcs->loadLanguage($_SESSION['Language']);
                 }
                 $urgency = $_LANG["supportticketsticketurgency" . strtolower($urgency)];
                 if (function_exists("getStatusColour")) {
                     $status = getStatusColour($status);
                 }
                 if ($userid == "0") {
                     $firstname = $data['name'];
                     $email = $data['email'];
                 }
                 $result = select_query("tblticketdepartments", "", array("id" => $deptid));
                 $data = mysql_fetch_array($result);
                 $fromname = $CONFIG['CompanyName'] . " " . $data['name'];
                 $fromemail = $data['email'];
                 $departmentname = $data['name'];
                 $replyid = 0;
                 if ($extra) {
                     $result = select_query("tblticketreplies", "", array("id" => $extra));
                     $data = mysql_fetch_array($result);
                     $replyid = $data['id'];
                     $tmessage = $data['message'];
                     $attachment = $data['attachment'];
                 }
                 if ($attachment) {
                     global $attachments_dir;
                     $attachment = explode("|", $attachment);
                     $attachments = array();
                     foreach ($attachment as $file) {
                         $attachments[$attachments_dir . $file] = substr($file, 7);
                     }
                 }
                 $date = fromMySQLDate($date, 0, 1);
                 if ($func_messagename != "Support Ticket Feedback Request") {
                     $subject = "[Ticket ID: {\$ticket_id}] {\$ticket_subject}";
                 }
                 $tmessage = strip_tags($tmessage);
                 if (!function_exists("getKBAutoSuggestions")) {
                     require ROOTDIR . "/includes/ticketfunctions.php";
                 }
                 $kbarticles = getKBAutoSuggestions($tmessage);
                 $kb_auto_suggestions = "";
                 foreach ($kbarticles as $kbarticle) {
                     $kb_auto_suggestions .= "<a href=\"" . $CONFIG['SystemURL'] . "/knowledgebase.php?action=displayarticle&id=" . $kbarticle['id'] . "\" target=\"_blank\">" . $kbarticle['title'] . "</a> - " . $kbarticle['article'] . "...<br />\r\n";
                 }
                 $tmessage = nl2br($tmessage);
                 if (!function_exists("ticketAutoHyperlinks")) {
                     require ROOTDIR . "/includes/ticketfunctions.php";
                 }
                 $tmessage = ticketAutoHyperlinks($tmessage);
                 $email_merge_fields['ticket_id'] = $tid;
                 $email_merge_fields['ticket_reply_id'] = $replyid;
                 $email_merge_fields['ticket_department'] = $departmentname;
                 $email_merge_fields['ticket_date_opened'] = $date;
                 $email_merge_fields['ticket_subject'] = $title;
                 $email_merge_fields['ticket_message'] = $tmessage;
                 $email_merge_fields['ticket_status'] = $status;
                 $email_merge_fields['ticket_priority'] = $urgency;
                 $email_merge_fields['ticket_url'] = $sysurl . ("/viewticket.php?tid=" . $tid . "&c=" . $c);
                 $email_merge_fields['ticket_link'] = "<a href=\"" . $sysurl . ("/viewticket.php?tid=" . $tid . "&c=" . $c . "\">") . $sysurl . ("/viewticket.php?tid=" . $tid . "&c=" . $c . "</a>");
                 $email_merge_fields['ticket_auto_close_time'] = $CONFIG['CloseInactiveTickets'];
                 $email_merge_fields['ticket_kb_auto_suggestions'] = $kb_auto_suggestions;
                 if ($CONFIG['DisableSupportTicketReplyEmailsLogging'] && $func_messagename == "Support Ticket Reply") {
                     $nosavemaillog = true;
                 }
             }
         } else {
             if ($type == "domain") {
                 $result = select_query("tbldomains", "", array("id" => $func_id));
                 $data = mysql_fetch_array($result);
                 $id = $data['id'];
                 $userid = $data['userid'];
                 $orderid = $data['orderid'];
                 $registrationdate = $data['registrationdate'];
                 $status = $data['status'];
                 $domain = $data['domain'];
                 $firstpaymentamount = $data['firstpaymentamount'];
                 $recurringamount = $data['recurringamount'];
                 $registrar = $data['registrar'];
                 $registrationperiod = $data['registrationperiod'];
                 $expirydate = $data['expirydate'];
                 $nextduedate = $data['nextduedate'];
                 $gateway = $data['paymentmethod'];
                 $dnsmanagement = $data['dnsmanagement'];
                 $emailforwarding = $data['emailforwarding'];
                 $idprotection = $data['idprotection'];
                 $donotrenew = $data['donotrenew'];
                 getUsersLang($userid);
                 $currency = getCurrency($userid);
                 $status = $_LANG["clientarea" . strtolower(str_replace(" ", "", $status))];
                 $expirydays_todaysdate = date("Ymd");
                 $expirydays_todaysdate = strtotime($expirydays_todaysdate);
                 $expirydays_expirydate = strtotime($expirydate);
                 $expirydays = round(($expirydays_expirydate - $expirydays_todaysdate) / 86400);
                 $expirydays_nextduedate = strtotime($nextduedate);
                 $nextduedays = round(($expirydays_nextduedate - $expirydays_todaysdate) / 86400);
                 if ($expirydays < 0) {
                     $expirydays = $nextduedays;
                 }
                 if ($expirydays < 0) {
                     $expirydays = 0;
                     $nextduedays = 0;
                 }
                 $registrationdate = fromMySQLDate($registrationdate, 0, 1);
                 $expirydate = fromMySQLDate($expirydate, 0, 1);
                 $nextduedate = fromMySQLDate($nextduedate, 0, 1);
                 $domainparts = explode(".", $domain, 2);
                 $email_merge_fields['domain_id'] = $id;
                 $email_merge_fields['domain_order_id'] = $orderid;
                 $email_merge_fields['domain_reg_date'] = $registrationdate;
                 $email_merge_fields['domain_status'] = $status;
                 $email_merge_fields['domain_name'] = $domain;
                 $email_merge_fields['domain_sld'] = $domainparts[0];
                 $email_merge_fields['domain_tld'] = $domainparts[1];
                 $email_merge_fields['domain_first_payment_amount'] = formatCurrency($firstpaymentamount);
                 $email_merge_fields['domain_recurring_amount'] = formatCurrency($recurringamount);
                 $email_merge_fields['domain_registrar'] = $registrar;
                 $email_merge_fields['domain_reg_period'] = $registrationperiod . " " . $_LANG['orderyears'];
                 $email_merge_fields['domain_expiry_date'] = $expirydate;
                 $email_merge_fields['domain_next_due_date'] = $nextduedate;
                 $email_merge_fields['domain_days_until_expiry'] = $expirydays;
                 $email_merge_fields['domain_days_until_nextdue'] = $nextduedays;
                 $email_merge_fields['domain_dns_management'] = $dnsmanagement ? "1" : "0";
                 $email_merge_fields['domain_email_forwarding'] = $emailforwarding ? "1" : "0";
                 $email_merge_fields['domain_id_protection'] = $idprotection ? "1" : "0";
                 $email_merge_fields['domain_do_not_renew'] = $donotrenew ? "1" : "0";
             } else {
                 if ($type == "product") {
                     $gatewaysarray = array();
                     $result = select_query("tblpaymentgateways", "gateway,value", array("setting" => "name"), "order", "ASC");
                     while ($data = mysql_fetch_array($result)) {
                         $gatewaysarray[$data['gateway']] = $data['value'];
                     }
                     $result = select_query("tblhosting", "tblhosting.*,tblproducts.name,tblproducts.description", array("tblhosting.id" => $func_id), "", "", "", "tblproducts ON tblproducts.id=tblhosting.packageid");
                     $data = mysql_fetch_array($result);
                     $id = $data['id'];
                     $userid = $data['userid'];
                     $orderid = $data['orderid'];
                     $regdate = $data['regdate'];
                     $nextduedate = $data['nextduedate'];
                     $orderno = $data['orderno'];
                     $domain = $data['domain'];
                     $server = $data['server'];
                     $package = $data['name'];
                     $productdescription = $data['description'];
                     $packageid = $data['packageid'];
                     $upgrades = $data['upgrades'];
                     $paymentmethod = $data['paymentmethod'];
                     $paymentmethod = $gatewaysarray[$paymentmethod];
                     if ($regdate == $nextduedate) {
                         $amount = $data['firstpaymentamount'];
                     } else {
                         $amount = $data['amount'];
                     }
                     $firstpaymentamount = $data['firstpaymentamount'];
                     $recurringamount = $data['amount'];
                     $billingcycle = $data['billingcycle'];
                     $domainstatus = $data['domainstatus'];
                     $username = $data['username'];
                     $password = decrypt($data['password']);
                     $dedicatedip = $data['dedicatedip'];
                     $assignedips = nl2br($data['assignedips']);
                     $dedi_ns1 = $data['ns1'];
                     $dedi_ns2 = $data['ns2'];
                     $subscriptionid = $data['subscriptionid'];
                     $suspendreason = $data['suspendreason'];
                     $canceltype = get_query_val("tblcancelrequests", "type", array("relid" => $data['id']), "id", "DESC");
                     $regdate = fromMySQLDate($regdate, 0, 1);
                     if ($nextduedate != "-") {
                         $nextduedate = fromMySQLDate($nextduedate, 0, 1);
                     }
                     getUsersLang($userid);
                     $currency = getCurrency($userid);
                     if ($domainstatus == "Suspended" && !$suspendreason) {
                         $suspendreason = $_LANG['suspendreasonoverdue'];
                     }
                     $domainstatus = $_LANG["clientarea" . strtolower(str_replace(" ", "", $domainstatus))];
                     $canceltype = $_LANG["clientareacancellation" . strtolower(str_replace(" ", "", $canceltype))];
                     if ($server) {
                         $result3 = select_query("tblservers", "", array("id" => $server));
                         $data3 = mysql_fetch_array($result3);
                         $servername = $data3['name'];
                         $serverip = $data3['ipaddress'];
                         $serverhostname = $data3['hostname'];
                         $ns1 = $data3['nameserver1'];
                         $ns1ip = $data3['nameserver1ip'];
                         $ns2 = $data3['nameserver2'];
                         $ns2ip = $data3['nameserver2ip'];
                         $ns3 = $data3['nameserver3'];
                         $ns3ip = $data3['nameserver3ip'];
                         $ns4 = $data3['nameserver4'];
                         $ns4ip = $data3['nameserver4ip'];
                     }
                     $billingcycleforconfigoptions = strtolower($billingcycle);
                     $billingcycleforconfigoptions = preg_replace("/[^a-z]/i", "", $billingcycleforconfigoptions);
                     $langbillingcycle = $billingcycleforconfigoptions;
                     $billingcycleforconfigoptions = str_replace("lly", "l", $billingcycleforconfigoptions);
                     if ($billingcycleforconfigoptions == "free account") {
                         $billingcycleforconfigoptions = "monthly";
                     }
                     $configoptions = array();
                     $configoptionshtml = "";
                     $query4 = "SELECT tblproductconfigoptions.id, tblproductconfigoptions.optionname AS confoption, tblproductconfigoptions.optiontype AS conftype, tblproductconfigoptionssub.optionname, tblhostingconfigoptions.qty FROM tblhostingconfigoptions INNER JOIN tblproductconfigoptions ON tblproductconfigoptions.id = tblhostingconfigoptions.configid INNER JOIN tblproductconfigoptionssub ON tblproductconfigoptionssub.id = tblhostingconfigoptions.optionid INNER JOIN tblhosting ON tblhosting.id=tblhostingconfigoptions.relid INNER JOIN tblproductconfiglinks ON tblproductconfiglinks.gid=tblproductconfigoptions.gid WHERE tblhostingconfigoptions.relid='" . (int) $id . "' AND tblproductconfiglinks.pid=tblhosting.packageid ORDER BY tblproductconfigoptions.`order`,tblproductconfigoptions.id ASC";
                     $result4 = full_query($query4);
                     while ($data4 = mysql_fetch_array($result4)) {
                         $confoption = $data4['confoption'];
                         $conftype = $data4['conftype'];
                         if (strpos($confoption, "|")) {
                             $confoption = explode("|", $confoption);
                             $confoption = trim($confoption[1]);
                         }
                         $optionname = $data4['optionname'];
                         $optionqty = $data4['qty'];
                         if (strpos($optionname, "|")) {
                             $optionname = explode("|", $optionname);
                             $optionname = trim($optionname[1]);
                         }
                         if ($conftype == 3) {
                             if ($optionqty) {
                                 $optionname = $_LANG['yes'];
                             } else {
                                 $optionname = $_LANG['no'];
                             }
                         } else {
                             if ($conftype == 4) {
                                 $optionname = "" . $optionqty . " x " . $optionname;
                             }
                         }
                         $configoptions[] = array("id" => $data4['id'], "option" => $confoption, "type" => $conftype, "value" => $optionname, "qty" => $optionqty, "setup" => $CONFIG['CurrencySymbol'] . $data4['setup'], "recurring" => $CONFIG['CurrencySymbol'] . $data4['recurring']);
                         $configoptionshtml .= "" . $confoption . ": " . $optionname . " " . $CONFIG['CurrencySymbol'] . $data4['recurring'] . "<br>\n";
                     }
                     $email_merge_fields['service_order_id'] = $orderid;
                     $email_merge_fields['service_id'] = $id;
                     $email_merge_fields['service_reg_date'] = $regdate;
                     $email_merge_fields['service_product_name'] = $package;
                     $email_merge_fields['service_product_description'] = $productdescription;
                     $email_merge_fields['service_config_options'] = $configoptions;
                     $email_merge_fields['service_config_options_html'] = $configoptionshtml;
                     $email_merge_fields['service_domain'] = $domain;
                     $email_merge_fields['service_server_name'] = $servername;
                     $email_merge_fields['service_server_hostname'] = $serverhostname;
                     $email_merge_fields['service_server_ip'] = $serverip;
                     $email_merge_fields['service_dedicated_ip'] = $dedicatedip;
                     $email_merge_fields['service_assigned_ips'] = $assignedips;
                     if ($dedi_ns1 != "") {
                         $email_merge_fields['service_ns1'] = $dedi_ns1;
                         $email_merge_fields['service_ns2'] = $dedi_ns2;
                     } else {
                         $email_merge_fields['service_ns1'] = $ns1;
                         $email_merge_fields['service_ns2'] = $ns2;
                         $email_merge_fields['service_ns3'] = $ns3;
                         $email_merge_fields['service_ns4'] = $ns4;
                     }
                     $email_merge_fields['service_ns1_ip'] = $ns1ip;
                     $email_merge_fields['service_ns2_ip'] = $ns2ip;
                     $email_merge_fields['service_ns3_ip'] = $ns3ip;
                     $email_merge_fields['service_ns4_ip'] = $ns4ip;
                     $email_merge_fields['service_payment_method'] = $paymentmethod;
                     $email_merge_fields['service_first_payment_amount'] = formatCurrency($firstpaymentamount);
                     $email_merge_fields['service_recurring_amount'] = formatCurrency($recurringamount);
                     $email_merge_fields['service_billing_cycle'] = $_LANG["orderpaymentterm" . $langbillingcycle];
                     $email_merge_fields['service_next_due_date'] = $nextduedate;
                     $email_merge_fields['service_status'] = $domainstatus;
                     $email_merge_fields['service_username'] = $username;
                     $email_merge_fields['service_password'] = $password;
                     $email_merge_fields['service_subscription_id'] = $subscriptionid;
                     $email_merge_fields['service_suspension_reason'] = $suspendreason;
                     $email_merge_fields['service_cancellation_type'] = $canceltype;
                     if (!function_exists("getCustomFields")) {
                         require dirname(__FILE__) . "/customfieldfunctions.php";
                     }
                     $customfields = getCustomFields("product", $packageid, $func_id, true, "");
                     $email_merge_fields['service_custom_fields'] = array();
                     foreach ($customfields as $customfield) {
                         $customfieldname = preg_replace("/[^0-9a-z]/", "", strtolower($customfield['name']));
                         $email_merge_fields["service_custom_field_" . $customfieldname] = $customfield['value'];
                         $email_merge_fields['service_custom_fields'][] = $customfield['value'];
                     }
                 } else {
                     if ($type == "affiliate") {
                         $result = select_query("tblaffiliates", "", array("id" => $func_id));
                         $data = mysql_fetch_array($result);
                         $id = $affiliateid = $data['id'];
                         $userid = $data['clientid'];
                         $visitors = $data['visitors'];
                         $balance = $data['balance'];
                         $withdrawn = $data['withdrawn'];
                         $currency = getCurrency($userid);
                         $balance = formatCurrency($balance);
                         $withdrawn = formatCurrency($withdrawn);
                         getUsersLang($userid);
                         $referralstable .= "<table cellspacing=\"1\" bgcolor=\"#cccccc\" width=\"100%\"><tr bgcolor=\"#efefef\" style=\"text-align:center;font-weight:bold;\"><td>" . $_LANG['affiliatessignupdate'] . "</td><td>" . $_LANG['orderproduct'] . "</td><td>" . $_LANG['affiliatesamount'] . "</td><td>" . $_LANG['orderbillingcycle'] . "</td><td>" . $_LANG['affiliatescommission'] . "</td><td>" . $_LANG['affiliatesstatus'] . "</td></tr>";
                         $service = "";
                         $result = select_query("tblaffiliatesaccounts", "tblaffiliatesaccounts.*,tblproducts.name,tblhosting.userid,tblhosting.domainstatus,tblhosting.amount,tblhosting.firstpaymentamount,tblhosting.regdate,tblhosting.billingcycle", array("affiliateid" => $affiliateid), "regdate", "DESC", "", "tblhosting ON tblhosting.id=tblaffiliatesaccounts.relid INNER JOIN tblproducts ON tblproducts.id=tblhosting.packageid INNER JOIN tblclients ON tblclients.id=tblhosting.userid");
                         while ($data = mysql_fetch_array($result)) {
                             $affaccid = $data['id'];
                             $lastpaid = $data['lastpaid'];
                             $relid = $data['relid'];
                             $ref_userid = $data['userid'];
                             $amount = $data['amount'];
                             $date = $data['regdate'];
                             $service = $data['name'];
                             $billingcycle = $data['billingcycle'];
                             $status = $data['domainstatus'];
                             if ($billingcycle == "One Time") {
                                 $amount = $data['firstpaymentamount'];
                             }
                             $commission = calculateAffiliateCommission($affiliateid, $relid);
                             $currency = getCurrency($ref_userid);
                             $amount = formatCurrency($amount);
                             $commission = formatCurrency($commission);
                             $date = fromMySQLDate($date, 0, 1);
                             if ($status == "Active") {
                                 $status = $_LANG['clientareaactive'];
                             } else {
                                 if ($status == "Pending") {
                                     $status = $_LANG['clientareapending'];
                                 } else {
                                     if ($status == "Suspended") {
                                         $status = $_LANG['clientareasuspended'];
                                     } else {
                                         if ($status == "Terminated") {
                                             $status = $_LANG['clientareaterminated'];
                                         } else {
                                             if ($status == "Cancelled") {
                                                 $status = $_LANG['clientareacancelled'];
                                             } else {
                                                 if ($status == "Fraud") {
                                                     $status = $_LANG['clientareafraud'];
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                             $billingcycle = strtolower($billingcycle);
                             $billingcycle = str_replace(" ", "", $billingcycle);
                             $billingcycle = str_replace("-", "", $billingcycle);
                             $billingcycle = $_LANG["orderpaymentterm" . $billingcycle];
                             $referralstable .= "<tr bgcolor=\"#ffffff\" style=\"text-align:center;\"><td>" . $date . "</td><td>" . $service . "</td><td>" . $amount . "</td><td>" . $billingcycle . "</td><td>" . $commission . "</td><td>" . $status . "</td></tr>";
                         }
                         if (!$service) {
                             $referralstable .= "<tr bgcolor=\"#ffffff\"><td colspan=\"6\" align=\"center\">" . $_LANG['affiliatesnosignups'] . "</td></tr>";
                         }
                         $referralstable .= "</table>";
                         $email_merge_fields['affiliate_total_visits'] = $visitors;
                         $email_merge_fields['affiliate_balance'] = $balance;
                         $email_merge_fields['affiliate_withdrawn'] = $withdrawn;
                         $email_merge_fields['affiliate_referrals_table'] = $referralstable;
                         $email_merge_fields['affiliate_referral_url'] = $CONFIG['SystemURL'] . ("/aff.php?aff=" . $id);
                     }
                 }
             }
         }
     }
     $contactid = "";
     if ($type == "general") {
         $userid = $func_id;
     }
     if (in_array($func_messagename, array("Password Reset Validation", "Password Reset Confirmation", "Automated Password Reset")) && $extra['contactid']) {
         $contactid = $extra['contactid'];
     }
     if ($userid || $contactid) {
         if ($contactid) {
             $result2 = select_query("tblcontacts", "tblcontacts.*,(SELECT groupid FROM tblclients WHERE id=tblcontacts.userid) AS clgroupid,(SELECT groupname FROM tblclientgroups WHERE id=clgroupid) AS clgroupname,(SELECT language FROM tblclients WHERE id=tblcontacts.userid) AS language", array("id" => $contactid));
         } else {
             $result2 = select_query("tblclients", "tblclients.*,tblclients.groupid AS clgroupid,(SELECT groupname FROM tblclientgroups WHERE id=tblclients.groupid) AS clgroupname", array("id" => $userid));
         }
         $data2 = mysql_fetch_array($result2);
         if (!$firstname && !$email) {
             $firstname = $data2['firstname'];
             $email = $data2['email'];
         }
         $lastname = $data2['lastname'];
         $companyname = $data2['companyname'];
         $address1 = $data2['address1'];
         $address2 = $data2['address2'];
         $city = $data2['city'];
         $state = $data2['state'];
         $postcode = $data2['postcode'];
         $country = $data2['country'];
         $phonenumber = $data2['phonenumber'];
         $language = $data2['language'];
         $credit = $data2['credit'];
         $status = $data2['status'];
         $language = $data2['language'];
         $clgroupid = $data2['clgroupid'];
         $clgroupname = $data2['clgroupname'];
         $gatewayid = $data2['gatewayid'];
         $datecreated = fromMySQLDate($data2['datecreated'], 0, 1);
         $password = "******";
         if ($CONFIG['NOMD5']) {
             $password = decrypt($data2['password']);
         }
         $cardtype = $data2['cardtype'];
         $cardnum = $data2['cardlastfour'];
         if (!function_exists("getCCDetails")) {
             require_once dirname(__FILE__) . "/ccfunctions.php";
         }
         $carddetails = getCCDetails($userid);
         $cardexp = $carddetails['expdate'];
         unset($carddetails);
         $currency = getCurrency($userid);
         $balance = get_query_val("tblinvoices", "SUM(total)-COALESCE((SELECT SUM(amountin-amountout) FROM tblaccounts WHERE tblaccounts.invoiceid=tblinvoices.id),0)", array("userid" => $userid, "status" => "Unpaid"));
         $email_merge_fields['client_due_invoices_balance'] = formatCurrency($balance);
         if ($func_messagename == "Automated Password Reset" && !$CONFIG['NOMD5']) {
             $length = 10;
             $seeds = "ABCDEFGHIJKLMNPQRSTUVYXYZ0123456789abcdefghijklmnopqrstuvwxyz";
             $seeds_count = strlen($seeds) - 1;
             $password = "";
             $i = 0;
             while ($i < $length) {
                 $password .= $seeds[rand(0, $seeds_count)];
                 ++$i;
             }
             if (!function_exists("generateClientPW")) {
                 require_once dirname(__FILE__) . "/clientfunctions.php";
             }
             $passwordhash = generateClientPW($password);
             if ($contactid) {
                 update_query("tblcontacts", array("password" => $passwordhash), array("id" => $contactid));
             } else {
                 update_query("tblclients", array("password" => $passwordhash), array("id" => $userid));
             }
             run_hook("ClientChangePassword", array("userid" => $userid, "password" => $password));
         }
         if ($extra['emailquote']) {
             $userid = $extra['client_id'];
             $firstname = $extra['client_first_name'];
             $lastname = $extra['client_last_name'];
             $companyname = $extra['client_company_name'];
             $email = $extra['client_email'];
             $address1 = $extra['client_address1'];
             $address2 = $extra['client_address2'];
             $city = $extra['client_city'];
             $state = $extra['client_state'];
             $postcode = $extra['client_postcode'];
             $country = $extra['client_country'];
             $phonenumber = $extra['client_phonenumber'];
             $language = $extra['client_language'];
             $attachmentfilename = $_LANG['quotefilename'] . $extra['quote_number'] . ".pdf";
             $attachmentdata = $extra['quoteattachmentdata'];
             $extra['quoteattachmentdata'] = "";
         }
     }
     if (!$email) {
         return false;
     }
     $fname = trim($firstname . " " . $lastname);
     if ($companyname) {
         $fname .= " (" . $companyname . ")";
     }
     $email_merge_fields['client_id'] = $userid;
     $email_merge_fields['client_name'] = $fname;
     $email_merge_fields['client_first_name'] = $firstname;
     $email_merge_fields['client_last_name'] = $lastname;
     $email_merge_fields['client_company_name'] = $companyname;
     $email_merge_fields['client_email'] = $email;
     $email_merge_fields['client_address1'] = $address1;
     $email_merge_fields['client_address2'] = $address2;
     $email_merge_fields['client_city'] = $city;
     $email_merge_fields['client_state'] = $state;
     $email_merge_fields['client_postcode'] = $postcode;
     $email_merge_fields['client_country'] = $country;
     $email_merge_fields['client_phonenumber'] = $phonenumber;
     $email_merge_fields['client_password'] = $password;
     $email_merge_fields['client_signup_date'] = $datecreated;
     $email_merge_fields['client_credit'] = formatCurrency($credit);
     $email_merge_fields['client_cc_type'] = $cardtype;
     $email_merge_fields['client_cc_number'] = $cardnum;
     $email_merge_fields['client_cc_expiry'] = $cardexp;
     $email_merge_fields['client_language'] = $language;
     $email_merge_fields['client_status'] = $status;
     $email_merge_fields['client_group_id'] = $clgroupid;
     $email_merge_fields['client_group_name'] = $clgroupname;
     $email_merge_fields['client_gateway_id'] = $gatewayid;
     $email_merge_fields['unsubscribe_url'] = $CONFIG['SystemURL'] . "/unsubscribe.php?email=" . $email . "&key=" . sha1($email . $userid . $cc_encryption_hash);
     if (!function_exists("getCustomFields")) {
         require dirname(__FILE__) . "/customfieldfunctions.php";
     }
     $customfields = getCustomFields("client", "", $userid, true, "");
     $email_merge_fields['client_custom_fields'] = array();
     foreach ($customfields as $customfield) {
         $customfieldname = preg_replace("/[^0-9a-z]/", "", strtolower($customfield['name']));
         $email_merge_fields["client_custom_field_" . $customfieldname] = $customfield['value'];
         $email_merge_fields['client_custom_fields'][] = $customfield['value'];
     }
     if (is_array($extra)) {
         foreach ($extra as $k => $v) {
             $email_merge_fields[$k] = $v;
         }
     }
     $email_merge_fields['company_name'] = $CONFIG['CompanyName'];
     $email_merge_fields['company_domain'] = $CONFIG['Domain'];
     $email_merge_fields['company_logo_url'] = $CONFIG['LogoURL'];
     $email_merge_fields['whmcs_url'] = $CONFIG['SystemURL'];
     $email_merge_fields['whmcs_link'] = "<a href=\"" . $CONFIG['SystemURL'] . "\">" . $CONFIG['SystemURL'] . "</a>";
     $email_merge_fields['signature'] = nl2br(html_entity_decode($CONFIG['Signature'], ENT_QUOTES));
     $email_merge_fields['date'] = date("l, jS F Y");
     $email_merge_fields['time'] = date("g:ia");
     $result = select_query("tblemailtemplates", "", array("name" => $func_messagename, "language" => $language));
     $data = mysql_fetch_array($result);
     if (substr($subject, 0, 10) != "[Ticket ID" && $data['subject']) {
         $subject = $data['subject'];
     }
     if ($data['message']) {
         $message = $data['message'];
     }
     $emailglobalheader = html_entity_decode($CONFIG['EmailGlobalHeader'], ENT_QUOTES);
     $emailglobalfooter = html_entity_decode($CONFIG['EmailGlobalFooter'], ENT_QUOTES);
     if ($emailglobalheader) {
         $message = $emailglobalheader . "\r\n" . $message;
     }
     if ($emailglobalfooter) {
         $message = $message . "\r\n" . $emailglobalfooter;
     }
     $hookresults = run_hook("EmailPreSend", array("messagename" => $func_messagename, "relid" => $func_id));
     foreach ($hookresults as $hookmergefields) {
         foreach ($hookmergefields as $k => $v) {
             if ($k == "abortsend" && $v == true) {
                 return false;
             }
             $email_merge_fields[$k] = $v;
         }
     }
     if (!$fromname) {
         $fromname = $CONFIG['CompanyName'];
     }
     if (!$fromemail) {
         $fromemail = $CONFIG['Email'];
     }
     global $templates_compiledir;
     if (!class_exists("Smarty")) {
         require ROOTDIR . "/includes/smarty/Smarty.class.php";
     }
     $smarty = new Smarty();
     $smarty->caching = 0;
     $smarty->compile_dir = $templates_compiledir;
     $smarty->compile_id = md5($subject . $message);
     $smarty->register_resource("emailtpl", array("emailtpl_template", "emailtpl_timestamp", "emailtpl_secure", "emailtpl_trusted"));
     $smarty->assign("emailsubject", $subject);
     $smarty->assign("emailmessage", $message);
     foreach ($email_merge_fields as $mergefield => $mergevalue) {
         $smarty->assign($mergefield, $mergevalue);
     }
     $subject = $smarty->fetch("emailtpl:emailsubject");
     $message = $smarty->fetch("emailtpl:emailmessage");
     if (!trim($subject) && !trim($message)) {
         logActivity("EMAILERROR: Email Message Empty so Aborting Sending - Template Name " . $func_messagename . " ID " . $func_id);
         return false;
     }
     $whmcs->load_class("phpmailer");
     $mail = new PHPMailer(true);
     try {
         $mail->From = $fromemail;
         $mail->FromName = html_entity_decode($fromname, ENT_QUOTES);
         if ($CONFIG['MailType'] == "mail") {
             $mail->Mailer = "mail";
         } else {
             if ($CONFIG['MailType'] == "smtp") {
                 $mail->IsSMTP();
                 $mail->Host = $CONFIG['SMTPHost'];
                 $mail->Port = $CONFIG['SMTPPort'];
                 $mail->Hostname = $_SERVER['SERVER_NAME'];
                 if ($CONFIG['SMTPSSL']) {
                     $mail->SMTPSecure = $CONFIG['SMTPSSL'];
                 }
                 if ($CONFIG['SMTPUsername']) {
                     $mail->SMTPAuth = true;
                     $mail->Username = $CONFIG['SMTPUsername'];
                     $mail->Password = decrypt($CONFIG['SMTPPassword']);
                 }
                 $mail->Sender = $mail->From;
                 if ($fromemail != $CONFIG['SMTPUsername']) {
                     $mail->AddReplyTo($fromemail, html_entity_decode($fromname, ENT_QUOTES));
                 }
             }
         }
         $mail->XMailer = $whmcs->get_config("CompanyName");
         $mail->CharSet = $CONFIG['Charset'];
         $mail->AddAddress(trim($email), html_entity_decode($firstname . " " . $lastname, ENT_QUOTES));
         if ($CONFIG['BCCMessages']) {
             $bcc = $CONFIG['BCCMessages'] . ",";
             $bcc = explode(",", $bcc);
             foreach ($bcc as $value) {
                 $ccaddress = trim($value);
                 if ($ccaddress) {
                     $mail->AddBCC($ccaddress);
                     continue;
                 }
             }
         }
         $additionalccs = "";
         if ($type == "support") {
             if ($ticketcc) {
                 $ticketcc = explode(",", $ticketcc);
                 foreach ($ticketcc as $ccaddress) {
                     $ccaddress = trim($ccaddress);
                     if ($ccaddress) {
                         $mail->AddAddress($ccaddress);
                         $additionalccs .= $ccaddress . ",";
                         continue;
                     }
                 }
             }
         } else {
             $result = select_query("tblcontacts", "", array("userid" => $userid, $type . "emails" => "1"));
             while ($data = mysql_fetch_array($result)) {
                 $ccaddress = trim($data['email']);
                 $mail->AddAddress($ccaddress, html_entity_decode($data['firstname'] . " " . $data['lastname'], ENT_QUOTES));
                 $additionalccs .= $ccaddress . ",";
             }
         }
         if ($copyto) {
             $copytoarray = explode(",", $copyto);
             if ($CONFIG['MailType'] == "mail") {
                 foreach ($copytoarray as $copytoemail) {
                     $mail->AddBCC(trim($copytoemail));
                 }
             } else {
                 foreach ($copytoarray as $copytoemail) {
                     $mail->AddCC(trim($copytoemail));
                 }
             }
         }
         if ($additionalccs) {
             if ($copyto) {
                 $copyto .= ",";
             }
             $copyto = substr($additionalccs, 0, 0 - 1);
         }
         $mail->Subject = html_entity_decode($subject, ENT_QUOTES);
         if ($plaintext) {
             $message = str_replace("<br>", "", $message);
             $message = str_replace("<br />", "", $message);
             $message = strip_tags($message);
             $mail->Body = html_entity_decode($message, ENT_QUOTES);
             $message = nl2br($message);
         } else {
             $message_text = str_replace("<p>", "", $message);
             $message_text = str_replace("</p>", "\r\n\r\n", $message_text);
             $message_text = str_replace("<br>", "\r\n", $message_text);
             $message_text = str_replace("<br />", "\r\n", $message_text);
             $message_text = strip_tags($message_text);
             $cssdata = "";
             if ($CONFIG['EmailCSS']) {
                 $cssdata = "<style>\r\n" . $CONFIG['EmailCSS'] . "\r\n</style>";
             }
             $message = $cssdata . "\r\n" . $message;
             $mail->Body = $message;
             $mail->AltBody = html_entity_decode($message_text, ENT_QUOTES);
         }
         if ($tplattachments) {
             $tplattachments = explode(",", $tplattachments);
             foreach ($tplattachments as $attachment) {
                 $filename = $downloads_dir . $attachment;
                 $displayname = substr($attachment, 7);
                 $mail->AddAttachment($filename, $displayname);
             }
         }
         if ($attachmentfilename) {
             if (is_array($attachmentfilename)) {
                 $count = 0;
                 foreach ($attachmentfilename as $filelist) {
                     $mail->AddStringAttachment($attachmentdata[$count], $filelist);
                     ++$count;
                 }
             } else {
                 $mail->AddStringAttachment($attachmentdata, $attachmentfilename);
             }
         }
         if (is_array($attachments)) {
             foreach ($attachments as $filename => $displayname) {
                 $mail->AddAttachment($filename, $displayname);
             }
         }
         global $smtp_debug;
         global $email_debug;
         global $email_preview;
         if ($smtp_debug) {
             $mail->SMTPDebug = true;
         }
         if ($email_debug) {
             echo "Email: " . $email . "<br>Subject: " . $subject . "<br>Message: " . $message . "<br>Attachment: " . $attachmentfilename . "<br><br>";
             return false;
         }
         if ($email_preview) {
             echo $message;
             return false;
         }
         $mail->Send();
         if ($displayresult) {
             echo "<p>Email Sent Successfully to <a href=\"clientssummary.php?userid=" . $userid . "\">" . $firstname . " " . $lastname . "</a></p>";
         }
         if ($userid && !$nosavemaillog) {
             insert_query("tblemails", array("userid" => $userid, "subject" => $subject, "message" => $message, "date" => "now()", "to" => $email, "cc" => $copyto, "bcc" => $CONFIG['BCCMessages']));
         }
         logActivity("Email Sent to " . $firstname . " " . $lastname . " (" . $subject . ")");
         $mail->ClearAddresses();
     } catch (phpmailerException $e) {
         logActivity("Email Sending Failed - " . $e->getMessage() . (" (User ID: " . $userid . " - Subject: " . $subject . ")"), "none");
         if ($displayresult) {
             echo "<p>Email Sending Failed - " . $e->errorMessage() . "</p>";
         }
     } catch (Exception $e) {
         logActivity("Email Sending Failed - " . $e->getMessage() . (" (User ID: " . $userid . " - Subject: " . $subject . ")"), "none");
         if ($displayresult) {
             echo "<p>Email Sending Failed - " . $e->getMessage() . "</p>";
         }
         return null;
     }
 }
Beispiel #6
0
function getInvoiceProductPromo($amount, $promoid, $userid = "", $serviceid = "", $orderamt = "")
{
    global $_LANG;
    global $currency;
    if (!$promoid) {
        return array();
    }
    $data = get_query_vals("tblpromotions", "", array("id" => $promoid));
    $promo_id = $data['id'];
    if (!$promo_id) {
        return array();
    }
    $promo_code = $data['code'];
    $promo_type = $data['type'];
    $promo_recurring = $data['recurring'];
    $promo_value = $data['value'];
    $promo_recurfor = $data['recurfor'];
    if ($userid) {
        $currency = getCurrency($userid);
    }
    if ($serviceid) {
        $data = get_query_vals("tblhosting", "packageid,regdate,nextduedate,firstpaymentamount,billingcycle", array("id" => $serviceid));
        $pid = $data['packageid'];
        $regdate = $data['regdate'];
        $nextduedate = $data['nextduedate'];
        $firstpaymentamount = $data['firstpaymentamount'];
        $billingcycle = $data['billingcycle'];
        $billingcycle = str_replace("-", "", strtolower($billingcycle));
        if ($billingcycle == "one time") {
            $billingcycle = "monthly";
        }
    }
    if ($serviceid && $promo_recurfor) {
        $promo_recurringcount = get_query_val("tblinvoiceitems", "COUNT(id)", array("userid" => $userid, "type" => "Hosting", "relid" => $serviceid));
        if ($promo_recurfor - 1 < $promo_recurringcount) {
            $amount = getInvoiceProductDefaultPrice($pid, $billingcycle, $regdate, $nextduedate);
            if (!function_exists("getCartConfigOptions")) {
                require ROOTDIR . "/includes/configoptionsfunctions.php";
            }
            $configoptions = getCartConfigOptions($pid, "", $billingcycle, $serviceid);
            foreach ($configoptions as $configoption) {
                $amount += $configoption['selectedrecurring'];
            }
            update_query("tblhosting", array("amount" => $amount, "promoid" => "0"), array("id" => $serviceid));
        }
    }
    if (!$promo_id) {
        return array();
    }
    if (!$serviceid || ($promo_recurring || !$promo_recurring && $regdate == $nextduedate)) {
        if ($promo_type == "Percentage") {
            $promo_amount = round($amount / (1 - $promo_value / 100), 2) - $amount;
            if (0 < $promo_value && $promo_amount <= 0) {
                $promo_amount = $orderamt ? $orderamt : getInvoiceProductDefaultPrice($pid, $billingcycle, $regdate, $nextduedate);
            }
            $promo_value .= "%";
        } else {
            if ($promo_type == "Fixed Amount") {
                if ($currency['id'] != 1) {
                    $promo_value = convertCurrency($promo_value, 1, $currency['id']);
                }
                $default_price = "";
                $default_price = getInvoiceProductDefaultPrice($pid, $billingcycle, $regdate, $nextduedate, $serviceid, $userid);
                if ($default_price < $promo_value) {
                    $promo_value = $default_price;
                }
                $default_price = "";
                $promo_amount = $promo_value;
                $promo_value = formatCurrency($promo_value);
            } else {
                if ($promo_type == "Price Override") {
                    if ($currency['id'] != 1) {
                        $promo_value = convertCurrency($promo_value, 1, $currency['id']);
                    }
                    $promo_amount = $orderamt ? $orderamt : getInvoiceProductDefaultPrice($pid, $billingcycle, $regdate, $nextduedate);
                    $promo_amount -= $promo_value;
                    $promo_value = formatCurrency($promo_value) . " " . $_LANG['orderpromopriceoverride'];
                } else {
                    if ($promo_type == "Free Setup") {
                        $promo_amount = $orderamt ? $orderamt : getInvoiceProductDefaultPrice($pid, $billingcycle, $regdate, $nextduedate);
                        $promo_amount -= $firstpaymentamount;
                        $promo_value = $_LANG['orderpromofreesetup'];
                    }
                }
            }
        }
        getUsersLang($userid);
        $promo_recurring = $promo_recurring ? $_LANG['recurring'] : $_LANG['orderpaymenttermonetime'];
        $promo_description = $_LANG['orderpromotioncode'] . (": " . $promo_code . " - " . $promo_value . " " . $promo_recurring . " ") . $_LANG['orderdiscount'];
        getUsersLang(0);
        return array("description" => $promo_description, "amount" => $promo_amount * (0 - 1));
    }
    return array();
}