Example #1
0
/**
 *	Email the invoice from an order to a customer
 *
 * @param int The ID of the order to email the invoice for.
 * @param int The optional ID of the order status. Will default to the already stored status ID of the order
 */
function EmailInvoiceToCustomer($orderId, $newStatusId=null)
{
	// Load the details for this order
	$order_row = GetOrder($orderId, true);
	if($order_row === false) {
		return false;
	}

	// All prices in the emailed invoices will be shown in the default currency of the store
	$defaultCurrency = GetDefaultCurrency();

	$GLOBALS['OrderNumber'] = $orderId;

	if (isId($newStatusId)) {
		$order_status = $newStatusId;
	} else {
		$order_status = $order_row['ordstatus'];
	}

	$order_payment_module = $order_row['orderpaymentmodule'];

	if($order_row['ordcustid'] > 0) {
		$GLOBALS['ViewOrderStatusMsg'] = GetLang('ASummaryIsShownBelow')." <a href='".$GLOBALS['ShopPath']."/orderstatus.php'>".GetLang('ClickHere')."</a>.";
	} else {
		$GLOBALS['ViewOrderStatusMsg'] = "";
	}

	$emailTemplate = FetchEmailTemplateParser();

	if ($order_row['shipping_address_count'] > 1) {
		// multiple shipping addresses
		$GLOBALS['ShippingAddress'] = GetLang('OrderWillBeShippedToMultipleAddresses');
	} else if ($order_row['shipping_address_count'] == 0) {
		// no shipping addresses (digital order)
		$GLOBALS['ShippingAddress'] = GetLang('ShippingImmediateDownload');
	} else {
		// single shipping address
		$address = $GLOBALS['ISC_CLASS_DB']->FetchRow("
			SELECT
				oa.*
			FROM
				`[|PREFIX|]order_addresses` oa
			WHERE
				oa.order_id = " . (int)$order_row['orderid'] . "
		");

		$GLOBALS['ShipFullName'] = isc_html_escape($address['first_name'].' '.$address['last_name']);

		$GLOBALS['ShipCompany'] = '';
		if($address['company']) {
			$GLOBALS['ShipCompany'] = '<br />'.isc_html_escape($address['company']);
		}

		$GLOBALS['ShipAddressLines'] = isc_html_escape($address['address_1']);

		if ($address['address_2'] != "") {
			$GLOBALS['ShipAddressLines'] .= '<br />' . isc_html_escape($address['address_2']);
		}

		$GLOBALS['ShipSuburb'] = isc_html_escape($address['city']);
		$GLOBALS['ShipState'] = isc_html_escape($address['state']);
		$GLOBALS['ShipZip'] = isc_html_escape($address['zip']);
		$GLOBALS['ShipCountry'] = isc_html_escape($address['country']);
		$GLOBALS['ShipPhone'] = isc_html_escape($address['phone']);

		// show shipping email, if any
		if(!$address['email']) {
			$GLOBALS['HideShippingEmail'] = 'display: none';
		} else {
			$GLOBALS['ShippingEmail'] = $address['email'];
		}

		$GLOBALS['ShippingAddress'] = $emailTemplate->GetSnippet("AddressLabel");
	}

	// Format the billing address
	$GLOBALS['ShipFullName'] = isc_html_escape($order_row['ordbillfirstname'].' '.$order_row['ordbilllastname']);

	$GLOBALS['ShipCompany'] = '';
	if($order_row['ordbillcompany']) {
		$GLOBALS['ShipCompany'] = '<br />'.isc_html_escape($order_row['ordbillcompany']);
	}

	$GLOBALS['ShipAddressLines'] = isc_html_escape($order_row['ordbillstreet1']);

	if ($order_row['ordbillstreet2'] != "") {
		$GLOBALS['ShipAddressLines'] .= '<br />' . isc_html_escape($order_row['ordbillstreet2']);
	}

	$GLOBALS['ShipSuburb'] = isc_html_escape($order_row['ordbillsuburb']);
	$GLOBALS['ShipState'] = isc_html_escape($order_row['ordbillstate']);
	$GLOBALS['ShipZip'] = isc_html_escape($order_row['ordbillzip']);
	$GLOBALS['ShipCountry'] = isc_html_escape($order_row['ordbillcountry']);
	$GLOBALS['ShipPhone'] = isc_html_escape($order_row['ordbillphone']);

	// show billing email, if any
	if(!$order_row['ordbillemail']) {
		$GLOBALS['HideBillingEmail'] = 'display: none';
	} else {
		$GLOBALS['BillingEmail'] = $order_row['ordbillemail'];
	}

	$GLOBALS['BillingAddress'] = $emailTemplate->GetSnippet("AddressLabel");

	// Format the shipping provider's details
	$shippingCostColumn = 'cost_ex_tax';
	$itemPriceColumn = 'price_ex_tax';
	$itemTotalColumn = 'total_ex_tax';
	$subTotalColumn = 'subtotal_ex_tax';

	if(getConfig('taxDefaultTaxDisplayOrders') == TAX_PRICES_DISPLAY_INCLUSIVE) {
		$shippingCostColumn = 'cost_inc_tax';
		$itemPriceColumn = 'price_inc_tax';
		$itemTotalColumn = 'total_inc_tax';
		$subTotalColumn = 'subtotal_inc_tax';
	}

	$GLOBALS['TotalCost'] = FormatPrice($order_row['total_inc_tax'], false, true, false, $defaultCurrency, true);

	$email = $order_row['ordbillemail'];
	if(!$order_row['ordbillemail']) {
		// Get the customer's email address
		$query = sprintf("select custconemail from [|PREFIX|]customers where customerid='%d'", $GLOBALS['ISC_CLASS_DB']->Quote($order_row['ordcustid']));
		$result = $GLOBALS['ISC_CLASS_DB']->Query($query);

		if ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
			$email = $row['custconemail'];
		}
	}

	if(!$email) {
		return false;
	}

	$prodHasSKU = false;
	$WrapCost = 0;
	$fieldArray = GetOrderProductFieldsData($orderId);

	// We need to loop throuh all the prodcts to see if any of them have an SKU
	foreach($order_row['products'] as $product_row) {
		if (trim($product_row['ordprodsku']) !== '') {
			$prodHasSKU = true;
		}
	}

	// OK, now set the proper columns for the product list
	if ($prodHasSKU) {
		$GLOBALS['CartItemColumns'] = $emailTemplate->GetSnippet("InvoiceProductColumns");
	} else {
		$GLOBALS['CartItemColumns'] = $emailTemplate->GetSnippet("InvoiceProductColumnsNoSKU");
	}

	$GLOBALS['SNIPPETS']['CartItems'] = '';
	$previousAddressId = null;
	foreach($order_row['products'] as $product_row) {
		if ($order_row['shipping_address_count'] > 1 && $product_row['order_address_id'] != $previousAddressId) {
			if ($product_row['order_address_id']) {
				$addressLine = array_filter(array(
					$product_row['address_1'],
					$product_row['address_2'],
					$product_row['city'],
					$product_row['state'],
					$product_row['zip'],
					$product_row['country'],
				));
				$addressLine = GetLang('ItemsShippedTo') . ' ' . Store_String::rightTruncate(implode(', ', $addressLine), 70);
			} else {
				$addressLine = GetLang('ItemsShippedToDigital');
			}

			$GLOBALS['AddressLine'] = $addressLine;
			$GLOBALS['SNIPPETS']['CartItems'] .= $emailTemplate->GetSnippet("InvoiceProductShipRow");
			$previousAddressId = $product_row['order_address_id'];
		}

		$pOptions = '';
		if($product_row['ordprodoptions'] != '') {
			$options = @unserialize($product_row['ordprodoptions']);
			if(!empty($options)) {
				$pOptions = "<br /><small>(";
				$comma = '';
				foreach($options as $name => $value) {
					$pOptions .= $comma.isc_html_escape($name).": ".isc_html_escape($value);
					$comma = ', ';
				}
				$pOptions .= ")</small>";
			}
		}
		$GLOBALS['ProductOptions'] = $pOptions;
		$GLOBALS['EventDate'] = '';
		if ($product_row['ordprodeventdate']) {
			$GLOBALS['EventDate'] = '<br /><span style="padding-left : 10px; padding-bottom:10px; font-size:11px; font-style:italic">('.$product_row['ordprodeventname'] . ': ' . isc_date('dS M Y', $product_row['ordprodeventdate']) . ')</span>';
		}
		$GLOBALS['ProductPrice'] = FormatPrice($product_row[$itemPriceColumn], false, true, false, $defaultCurrency, true);
		$GLOBALS['ProductTotal'] = FormatPrice($product_row[$itemTotalColumn], false, true, false, $defaultCurrency, true);
		$GLOBALS['ProductQuantity'] = $product_row['ordprodqty'];

		$GLOBALS['ProductName'] = isc_html_escape($product_row['ordprodname']);

		$GLOBALS['ProductSku'] = ' ';
		if ($prodHasSKU && trim($product_row['ordprodsku']) !== '') {
			$GLOBALS['ProductSku'] = isc_html_escape($product_row['ordprodsku']);
		}

		// If this is a digital download and the order is complete, append a download link to the name of the product
		if($product_row['ordprodtype'] == 'digital' && OrderIsComplete($order_status)) {
			$GLOBALS['ISC_CLASS_ACCOUNT'] = GetClass('ISC_ACCOUNT');
			$downloadEncrypted = $GLOBALS['ISC_CLASS_ACCOUNT']->EncryptDownloadKey($product_row['orderprodid'], $product_row['ordprodid'], $orderId, $order_row['ordtoken']);
			$downloadLink = $GLOBALS['ShopPathSSL'].'/account.php?action=download_item&amp;data=' . $downloadEncrypted;
			$GLOBALS['ProductName'] .= ' (<a href="'.$downloadLink.'">'.GetLang('DownloadLink').'</a>)';
		}

		$GLOBALS['CartProductFields'] = '';
		if(isset($fieldArray[$product_row['orderprodid']])) {
			$GLOBALS['CartProductFields'] = LoadEmailOrderProductFields($fieldArray[$product_row['orderprodid']]);
		}

		if(isset($product_row['ordprodwrapcost'])) {
			$WrapCost += $product_row['ordprodwrapcost'];
		}

		$GLOBALS['ExpectedReleaseDate'] = '';

		if ($product_row['prodpreorder']) {
			if ($product_row['prodreleasedate']) {
				$message = $product_row['prodpreordermessage'];
				if (!$message) {
					$message = GetConfig('DefaultPreOrderMessage');
				}
				$GLOBALS['ExpectedReleaseDate'] = '(' . str_replace('%%DATE%%', isc_date(GetConfig('DisplayDateFormat'), $product_row['prodreleasedate']), $message) . ')';
			} else {
				$GLOBALS['ExpectedReleaseDate'] = '(' . GetLang('PreOrderProduct') . ')';
			}
		}

		if ($prodHasSKU) {
			$GLOBALS['SNIPPETS']['CartItems'] .= $emailTemplate->GetSnippet("InvoiceCartItem");
		} else {
			$GLOBALS['SNIPPETS']['CartItems'] .= $emailTemplate->GetSnippet("InvoiceCartItemNoSKU");
		}
	}

	$totalRows = getOrderTotalRows($order_row);
	$GLOBALS['SNIPPETS']['TotalRows'] = '';
	foreach($totalRows as $row) {
		$emailTemplate->assign('label', isc_html_escape($row['label']));
		$emailTemplate->assign('value', formatPrice($row['value'], false, true, false, $defaultCurrency, true));
		$GLOBALS['SNIPPETS']['TotalRows'] .= $emailTemplate->getSnippet('InvoiceTotalRow');
	}

	// Set the shipping method
	if ($order_row['ordisdigital']) {
		$GLOBALS['ShippingMethod'] = GetLang('ImmediateDownload');
	} else {
		$GLOBALS['ShippingMethod'] = sprintf(GetLang('FreeShippingFromX'), $GLOBALS['StoreName']);
	}

	// What's the status of the order? If it's awaiting payment (7) then show the awaiting payment notice
	if ($order_status == 7) {
		// Get the awaiting payment snippet, for offline payment providers also show the "how to pay for your order" message"
		$checkout_provider = null;
		GetModuleById('checkout', $checkout_provider, $order_payment_module);
		if (is_object($checkout_provider) && $checkout_provider->getpaymenttype() == PAYMENT_PROVIDER_OFFLINE && method_exists($checkout_provider, 'GetOfflinePaymentMessage')) {
			$paymentData = array(
				'orders' => array($order_row['orderid'] => $order_row)
			);
			$checkout_provider->SetOrderData($paymentData);
			$GLOBALS['PaymentGatewayAmount'] = CurrencyConvertFormatPrice($order_row['total_inc_tax'], $order_row['ordcurrencyid'], $order_row['ordcurrencyexchangerate'], true);
			$GLOBALS['PaymentMessage'] = $checkout_provider->GetOfflinePaymentMessage();
			$GLOBALS['PendingPaymentDetails'] = $emailTemplate->GetSnippet("InvoicePendingPaymentDetails");
			$GLOBALS['PendingPaymentNotice'] = $emailTemplate->GetSnippet("InvoicePendingPaymentNotice");
		}
	}

	$GLOBALS['OrderCommentBlock'] = '';
	if($order_row['ordcustmessage'] != '') {
		$GLOBALS['OrderComments'] = isc_html_escape($order_row['ordcustmessage']);
		$GLOBALS['OrderCommentBlock'] = $emailTemplate->GetSnippet("InvoiceOrderComment");
	}

	$emailTemplate->SetTemplate("invoice_email");
	$message = $emailTemplate->ParseTemplate(true);

	// Create a new email API object to send the email
	$store_name = GetConfig('StoreName');

	$obj_email = GetEmailClass();
	$obj_email->From(GetConfig('OrderEmail'), $store_name);
	$obj_email->Set("Subject", sprintf(GetLang('YourOrderFrom'), $store_name));
	$obj_email->AddBody("html", $message);
	$obj_email->AddRecipient($email, "", "h");
	$email_result = $obj_email->Send();

	$forwardEmails = array();
	if($order_row['ordvendorid'] > 0) {
		$query = "
			SELECT vendororderemail
			FROM [|PREFIX|]vendors
			WHERE vendorid='".(int)$order_row['ordvendorid']."'
		";
		$vendorOrderEmails = $GLOBALS['ISC_CLASS_DB']->FetchOne($query);
		$forwardEmails = array_merge($forwardEmails, explode(',', $vendorOrderEmails));
	}

	// If there are any additional recipients (forward invoices to addresses), send them as well
	if(GetConfig('ForwardInvoiceEmails')) {
		$forwardEmails = array_merge($forwardEmails, explode(',', GetConfig('ForwardInvoiceEmails')));
	}

	$forwardEmails = array_unique($forwardEmails);
	foreach($forwardEmails as $address) {
		if(!trim($address)) {
			continue;
		}
		$emailClass = GetEmailClass();
		$emailClass->Set('CharSet', GetConfig('CharacterSet'));
		$emailClass->From(GetConfig('OrderEmail'), $store_name);
		$emailClass->Set("Subject", "Fwd: ".sprintf(GetLang('YourOrderFrom'), $store_name)." (#".$order_row['orderid'].")");
		$emailClass->AddBody("html", $message);
		$emailClass->AddRecipient($address, "", "h");
		$status = $emailClass->Send();
	}

	// If the email was sent ok, show a confirmation message
	if ($email_result['success']) {
		return true;
	}
	else {
		// Email error
		return false;
	}
}
Example #2
0
/**
 *	Email the invoice from an order to a customer
 *
 * @param int The ID of the order to email the invoice for.
 * @param int The optional ID of the order status. Will default to the already stored status ID of the order
 */
function EmailInvoiceToCustomer($orderId, $newStatusId = null)
{
    // Load the details for this order
    $is_digital_download = true;
    $order_row = GetOrder($orderId, true);
    if ($order_row === false) {
        return fase;
    }
    // All prices in the emailed invoices will be shown in the default currency of the store
    $defaultCurrency = GetDefaultCurrency();
    $GLOBALS['OrderNumber'] = $orderId;
    if (isId($newStatusId)) {
        $order_status = $newStatusId;
    } else {
        $order_status = $order_row['ordstatus'];
    }
    $order_payment_module = $order_row['orderpaymentmodule'];
    if ($order_row['ordcustid'] > 0) {
        $GLOBALS['ViewOrderStatusMsg'] = GetLang('ASummaryIsShownBelow') . " <a href='" . $GLOBALS['ShopPath'] . "/orderstatus.php'>" . GetLang('ClickHere') . "</a>.";
    } else {
        $GLOBALS['ViewOrderStatusMsg'] = "";
    }
    $emailTemplate = FetchEmailTemplateParser();
    // Is there a shipping address, or is it a digital download?
    if ($order_row['ordshipfirstname'] == "") {
        $GLOBALS['ShippingAddress'] = GetLang('NA');
    } else {
        $GLOBALS['ShipFullName'] = isc_html_escape($order_row['ordshipfirstname'] . ' ' . $order_row['ordshiplastname']);
        $GLOBALS['ShipCompany'] = '';
        if ($order_row['ordshipcompany']) {
            $GLOBALS['ShipCompany'] = '<br />' . isc_html_escape($order_row['ordshipcompany']);
        }
        $GLOBALS['ShipAddressLine1'] = isc_html_escape($order_row['ordshipstreet1']);
        if ($order_row['ordshipstreet2'] != "") {
            $GLOBALS['ShipAddressLine2'] = isc_html_escape($order_row['ordshipstreet2']);
        } else {
            $GLOBALS['ShipAddressLine2'] = '';
        }
        $GLOBALS['ShipSuburb'] = isc_html_escape($order_row['ordshipsuburb']);
        $GLOBALS['ShipState'] = isc_html_escape($order_row['ordshipstate']);
        $GLOBALS['ShipZip'] = isc_html_escape($order_row['ordshipzip']);
        $GLOBALS['ShipCountry'] = isc_html_escape($order_row['ordshipcountry']);
        $GLOBALS['ShipPhone'] = "";
        $GLOBALS['ShippingAddress'] = $emailTemplate->GetSnippet("AddressLabel");
    }
    // Format the billing address
    $GLOBALS['ShipFullName'] = isc_html_escape($order_row['ordbillfirstname'] . ' ' . $order_row['ordbilllastname']);
    $GLOBALS['ShipCompany'] = '';
    if ($order_row['ordbillcompany']) {
        $GLOBALS['ShipCompany'] = '<br />' . isc_html_escape($order_row['ordbillcompany']);
    }
    $GLOBALS['ShipAddressLine1'] = isc_html_escape($order_row['ordbillstreet1']);
    if ($order_row['ordbillstreet2'] != "") {
        $GLOBALS['ShipAddressLine2'] = isc_html_escape($order_row['ordbillstreet2']);
    } else {
        $GLOBALS['ShipAddressLine2'] = '';
    }
    $GLOBALS['ShipSuburb'] = isc_html_escape($order_row['ordbillsuburb']);
    $GLOBALS['ShipState'] = isc_html_escape($order_row['ordbillstate']);
    $GLOBALS['ShipZip'] = isc_html_escape($order_row['ordbillzip']);
    $GLOBALS['ShipCountry'] = isc_html_escape($order_row['ordbillcountry']);
    $GLOBALS['ShipPhone'] = "";
    $GLOBALS['BillingAddress'] = $emailTemplate->GetSnippet("AddressLabel");
    // Format the shipping provider's details
    $ship_method = $order_row['ordshipmethod'];
    $ship_cost = $order_row['ordshipcost'];
    $GLOBALS['ItemTotal'] = FormatPrice($order_row['ordsubtotal'], false, true, false, $defaultCurrency, true);
    if ($order_row['ordshipcost'] > 0) {
        $GLOBALS['ShippingCost'] = FormatPrice($order_row['ordshipcost'], false, true, false, $defaultCurrency, true);
        $GLOBALS['SNIPPETS']['InvoiceEmailShippingTotal'] = $emailTemplate->GetSnippet('InvoiceEmailShippingTotal');
    }
    if ($order_row['ordhandlingcost'] > 0) {
        $GLOBALS['HandlingCost'] = FormatPrice($order_row['ordhandlingcost'], false, true, false, $defaultCurrency, true);
        $GLOBALS['SNIPPETS']['InvoiceEmailHandlingTotal'] = $emailTemplate->GetSnippet('InvoiceEmailHandlingTotal');
    }
    if ($order_row['ordtaxtotal'] > 0) {
        if ($order_row['ordtaxname']) {
            $taxName = $order_row['ordtaxname'];
        } else {
            $taxName = GetLang('InvoiceSalesTax');
        }
        $GLOBALS['TaxCost'] = FormatPrice($order_row['ordtaxtotal'], false, true, false, $defaultCurrency, true);
        if ($order_row['ordtotalincludestax']) {
            $GLOBALS['TaxName'] = isc_html_escape(sprintf(GetLang('IncludedInvoiceTax'), $taxName));
            $GLOBALS['SNIPPETS']['InvoiceEmailTaxTotalIncluded'] = $emailTemplate->GetSnippet('InvoiceEmailTaxTotal');
            $GLOBALS['SNIPPETS']['InvoiceEmailTaxTotal'] = '';
        } else {
            $GLOBALS['TaxName'] = isc_html_escape($taxName);
            $GLOBALS['SNIPPETS']['InvoiceEmailTaxTotal'] = $emailTemplate->GetSnippet('InvoiceEmailTaxTotal');
            $GLOBALS['SNIPPETS']['InvoiceEmailTaxTotalIncluded'] = '';
        }
    }
    $GLOBALS['TotalCost'] = FormatPrice($order_row['ordtotalamount'], false, true, false, $defaultCurrency, true);
    $email = $order_row['ordbillemail'];
    if (!$order_row['ordbillemail']) {
        // Get the customer's email address
        $query = sprintf("select custconemail from [|PREFIX|]customers where customerid='%d'", $GLOBALS['ISC_CLASS_DB']->Quote($order_row['ordcustid']));
        $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
        if ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
            $email = $row['custconemail'];
        }
    }
    if (!$email) {
        return false;
    }
    $WrapCost = 0;
    $fieldArray = GetOrderProductFieldsData($orderId);
    $GLOBALS['SNIPPETS']['CartItems'] = '';
    foreach ($order_row['products'] as $product_row) {
        if ($product_row['ordprodtype'] == "physical") {
            $is_digital_download = false;
        }
        $pOptions = '';
        if ($product_row['ordprodoptions'] != '') {
            $options = @unserialize($product_row['ordprodoptions']);
            if (!empty($options)) {
                $pOptions = "<br /><small>(";
                $comma = '';
                foreach ($options as $name => $value) {
                    $pOptions .= $comma . isc_html_escape($name) . ": " . isc_html_escape($value);
                    $comma = ', ';
                }
                $pOptions .= ")</small>";
            }
        }
        $GLOBALS['ProductOptions'] = $pOptions;
        $GLOBALS['EventDate'] = '';
        if ($product_row['ordprodeventdate'] != null) {
            $GLOBALS['EventDate'] = '<br /><span style="padding-left : 10px; padding-bottom:10px; font-size:11px; font-style:italic">(' . $product_row['ordprodeventname'] . ': ' . isc_date('dS M Y', $product_row['ordprodeventdate']) . ')</span>';
        }
        $GLOBALS['ProductPrice'] = FormatPrice($product_row['ordprodcost'], false, true, false, $defaultCurrency, true);
        $GLOBALS['ProductTotal'] = FormatPrice($product_row['ordprodcost'] * $product_row['ordprodqty'], false, true, false, $defaultCurrency, true);
        $GLOBALS['ProductQuantity'] = $product_row['ordprodqty'];
        $GLOBALS['ProductName'] = isc_html_escape($product_row['ordprodname']);
        // If this is a digital download and the order is complete, append a download link to the name of the product
        if ($product_row['ordprodtype'] == 'digital' && OrderIsComplete($order_status)) {
            $GLOBALS['ISC_CLASS_ACCOUNT'] = GetClass('ISC_ACCOUNT');
            $downloadEncrypted = $GLOBALS['ISC_CLASS_ACCOUNT']->EncryptDownloadKey($product_row['orderprodid'], $product_row['ordprodid'], $orderId, $order_row['ordtoken']);
            $downloadLink = $GLOBALS['ShopPathSSL'] . '/account.php?action=download_item&amp;data=' . $downloadEncrypted;
            $GLOBALS['ProductName'] .= ' (<a href="' . $downloadLink . '">' . GetLang('DownloadLink') . '</a>)';
        }
        $GLOBALS['CartProductFields'] = '';
        if (isset($fieldArray[$product_row['orderprodid']])) {
            $GLOBALS['CartProductFields'] = LoadEmailOrderProductFields($fieldArray[$product_row['orderprodid']]);
        }
        if (isset($product_row['ordprodwrapcost'])) {
            $WrapCost += $product_row['ordprodwrapcost'];
        }
        $GLOBALS['SNIPPETS']['CartItems'] .= $emailTemplate->GetSnippet("InvoiceCartItem");
    }
    if ($WrapCost > 0) {
        $GLOBALS['GiftWrapCost'] = FormatPrice($WrapCost, false, true, false, $defaultCurrency, true);
        $GLOBALS['SNIPPETS']['InvoiceEmailGiftWrapTotal'] = $emailTemplate->GetSnippet('InvoiceEmailGiftWrapTotal');
    }
    // Set the shipping method
    if ($ship_method == "") {
        if ($is_digital_download) {
            $GLOBALS['ShippingMethod'] = GetLang('ImmediateDownload');
        } else {
            $GLOBALS['ShippingMethod'] = sprintf(GetLang('FreeShippingFromX'), $GLOBALS['StoreName']);
        }
    } else {
        $GLOBALS['ShippingMethod'] = sprintf("%s %s %s", isc_html_escape($order_row['ordshipmethod']), GetLang('For'), FormatPrice($ship_cost, false, true, false, $defaultCurrency, true));
    }
    // What's the status of the order? If it's awaiting payment (7) then show the awaiting payment notice
    if ($order_status == 7) {
        // Get the awaiting payment snippet, for offline payment providers also show the "how to pay for your order" message"
        $checkout_provider = null;
        GetModuleById('checkout', $checkout_provider, $order_payment_module);
        if (is_object($checkout_provider) && $checkout_provider->getpaymenttype() == PAYMENT_PROVIDER_OFFLINE && method_exists($checkout_provider, 'GetOfflinePaymentMessage')) {
            $paymentData = array('orders' => array($order_row['orderid'] => $order_row));
            $checkout_provider->SetOrderData($paymentData);
            $GLOBALS['PaymentGatewayAmount'] = CurrencyConvertFormatPrice($order_row['ordgatewayamount'], $order_row['ordcurrencyid'], $order_row['ordcurrencyexchangerate'], true);
            $GLOBALS['PaymentMessage'] = str_replace("\n", "<br />", $checkout_provider->GetOfflinePaymentMessage());
            $GLOBALS['PendingPaymentDetails'] = $emailTemplate->GetSnippet("InvoicePendingPaymentDetails");
            $GLOBALS['PendingPaymentNotice'] = $emailTemplate->GetSnippet("InvoicePendingPaymentNotice");
        }
    }
    if ($order_row['ordcustmessage'] != '') {
        $GLOBALS['OrderComments'] = "<h3 style='font-size:18px'>" . GetLang('OrderComments') . "</h3>" . isc_html_escape($order_row['ordcustmessage']);
    }
    $emailTemplate->SetTemplate("invoice_email");
    $message = $emailTemplate->ParseTemplate(true);
    // Create a new email API object to send the email
    $store_name = GetConfig('StoreName');
    $obj_email = GetEmailClass();
    $obj_email->From(GetConfig('OrderEmail'), $store_name);
    $obj_email->Set("Subject", sprintf(GetLang('YourOrderFrom'), $store_name));
    $obj_email->AddBody("html", $message);
    $obj_email->AddRecipient($email, "", "h");
    $email_result = $obj_email->Send();
    $forwardEmails = array();
    if ($order_row['ordvendorid'] > 0) {
        $query = "\n\t\t\tSELECT vendororderemail\n\t\t\tFROM [|PREFIX|]vendors\n\t\t\tWHERE vendorid='" . (int) $order_row['ordvendorid'] . "'\n\t\t";
        $vendorOrderEmails = $GLOBALS['ISC_CLASS_DB']->FetchOne($query);
        $forwardEmails = array_merge($forwardEmails, explode(',', $vendorOrderEmails));
    }
    // If there are any additional recipients (forward invoices to addresses), send them as well
    if (GetConfig('ForwardInvoiceEmails')) {
        $forwardEmails = array_merge($forwardEmails, explode(',', GetConfig('ForwardInvoiceEmails')));
    }
    $forwardEmails = array_unique($forwardEmails);
    foreach ($forwardEmails as $address) {
        if (!trim($address)) {
            continue;
        }
        $emailClass = GetEmailClass();
        $emailClass->Set('CharSet', GetConfig('CharacterSet'));
        $emailClass->From(GetConfig('OrderEmail'), $store_name);
        $emailClass->Set("Subject", "Fwd: " . sprintf(GetLang('YourOrderFrom'), $store_name) . " (#" . $order_row['orderid'] . ")");
        $emailClass->AddBody("html", $message);
        $emailClass->AddRecipient($address, "", "h");
        $status = $emailClass->Send();
    }
    // If the email was sent ok, show a confirmation message
    if ($email_result['success']) {
        return true;
    } else {
        // Email error
        return false;
    }
}