Example #1
0
 /**
  * Actually save a new order or an updated existing order in the database
  * after it's been validated.
  *
  * @param array An array of details about the order to save.
  * @param int The ID of the existing order if we're updating an order.
  * @return boolean True if successful, false if not.
  */
 private function CommitOrder($data, $orderId = 0)
 {
     $GLOBALS['ISC_CLASS_DB']->StartTransaction();
     /**
      * We need to find our billing/shipping details from the form fields first as it is
      * also used in creating the customer
      */
     $billingDetails = array();
     $shippingDetails = array();
     $billingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_BILLING, true);
     $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
     $fields = $billingFields + $shippingFields;
     $addressMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'CompanyName' => 'company', 'AddressLine1' => 'address1', 'AddressLine2' => 'address2', 'City' => 'city', 'State' => 'state', 'Zip' => 'zip', 'State' => 'state', 'Country' => 'country', 'Phone' => 'phone');
     foreach (array_keys($fields) as $fieldId) {
         $privateName = $fields[$fieldId]->record['formfieldprivateid'];
         if ($privateName == '' || !array_key_exists($privateName, $addressMap)) {
             continue;
         }
         if ($fields[$fieldId]->record['formfieldformid'] == FORMFIELDS_FORM_BILLING) {
             $detailsVar =& $billingDetails;
         } else {
             $detailsVar =& $shippingDetails;
         }
         /**
          * Find the country
          */
         if (isc_strtolower($privateName) == 'country') {
             $detailsVar['shipcountry'] = $fields[$fieldId]->getValue();
             $detailsVar['shipcountryid'] = GetCountryByName($fields[$fieldId]->getValue());
             if (!isId($detailsVar['shipcountryid'])) {
                 $detailsVar['shipcountryid'] = 0;
             }
             /**
              * Else find the state
              */
         } else {
             if (isc_strtolower($privateName) == 'state') {
                 $detailsVar['shipstate'] = $fields[$fieldId]->getValue();
                 $stateInfo = GetStateInfoByName($detailsVar['shipstate']);
                 if ($stateInfo && isId($stateInfo['stateid'])) {
                     $detailsVar['shipstateid'] = $stateInfo['stateid'];
                 } else {
                     $detailsVar['shipstateid'] = 0;
                 }
                 /**
                  * Else the rest
                  */
             } else {
                 $detailsVar['ship' . $addressMap[$privateName]] = $fields[$fieldId]->getValue();
             }
         }
     }
     // If we're creating an account for this customer, create it now
     if ($data['ordcustid'] == 0 && $data['customerType'] == 'new') {
         $customerData = array('email' => $data['custconemail'], 'password' => $data['custpassword'], 'firstname' => $billingDetails['shipfirstname'], 'lastname' => $billingDetails['shiplastname'], 'company' => $billingDetails['shipcompany'], 'phone' => $billingDetails['shipphone'], 'token' => GenerateCustomerToken(), 'customergroupid' => $data['custgroupid']);
         $GLOBALS['CusFirstname'] = $billingDetails['shipfirstname'];
         # Baskaran
         /* Added the store credit as seperate as it may be disabled while add/edit order - vikas  */
         if (isset($data['custstorecredit'])) {
             $customerData['storecredit'] = DefaultPriceFormat($data['custstorecredit']);
         }
         /**
          * Save the customer custom fields
          */
         if (gzte11(ISC_MEDIUMPRINT)) {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT);
             if (isId($formSessionId)) {
                 $customerData['custformsessionid'] = $formSessionId;
             }
         }
         $entity = new ISC_ENTITY_CUSTOMER();
         $data['ordcustid'] = $entity->add($customerData);
         if (!$data['ordcustid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     //2010-11-08 Ronnie add When calculating the ship infomation corresponding to no
     $GLOBALS['BCK_shipcountryid'] = $detailsVar['shipcountry'];
     $GLOBALS['BCK_shipstateid'] = $detailsVar['shipstate'];
     if ($GLOBALS['BCK_shipstateid'] == '') {
         $GLOBALS['BCK_shipcountryid'] = $billingDetails['shipcountry'];
         $GLOBALS['BCK_shipstateid'] = $billingDetails['shipstate'];
     }
     foreach ($this->GetCartApi()->GetProductsInCart() as $rowId => $product) {
         if (!isset($product['exists_order_coupon']) && isset($product['discount'])) {
             // Now workout the discount amount
             if ($product['coupontype'] == 0) {
                 // It's a dollar discount
                 $newPrice = $product['product_price'] - $product['discount'];
             } else {
                 // It's a percentage discount
                 $discount = $product['product_price'] / 100 * $product['discount'];
                 if ($discount == $product['product_price']) {
                     $newPrice = 0;
                 } else {
                     $newPrice = $product['product_price'] - $discount;
                 }
             }
             if ($newPrice < 0) {
                 $newPrice = 0;
             }
             $this->GetCartApi()->SetItemValue($rowId, 'discount_price', $newPrice);
         } elseif (isset($product['exists_order_coupon']) && isset($product['discount'])) {
             $this->GetCartApi()->SetItemValue($rowId, 'discount_price', $product['product_price']);
             $newPrice = 0;
             if ($product['coupontype'] == 0) {
                 // It's a dollar discount
                 $newPrice = $product['product_price'] + $product['discount'];
             } else {
                 // It's a percentage discount
                 $newPrice = $product['product_price'] / (1 - $product['discount'] / 100);
             }
             $this->GetCartApi()->SetItemValue($rowId, 'product_price', $newPrice);
         }
     }
     $orderSummary = $this->CalculateOrderSummary();
     //ronnie
     //$orderSummary['taxCost'];
     $defaultCurrency = GetDefaultCurrency();
     $email = '';
     if (isset($data['custconemail']) && $data['customerType'] == 'new') {
         $email = $data['custconemail'];
     } else {
         if (isset($data['anonymousemail']) && $data['customerType'] == 'anonymous') {
             $email = $data['anonymousemail'];
         }
     }
     /**********************************************************
     				Code added by Mayank Jaitly for getting the logged user
     				for adding his/her id as order owner.
     			************************************************************/
     $loggeduser = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetUser();
     //////////  End of alteration
     $custid = $data['ordcustid'];
     $ordstatus = '';
     $query = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]customers c, [|PREFIX|]customer_groups cg WHERE c.customerid = '{$custid}' AND cg.customergroupid = c.custgroupid AND cg.groupname = 'Walk In' ");
     if ($GLOBALS['ISC_CLASS_DB']->CountResult($query) > 0) {
         $ordstatus = '10';
     } else {
         $ordstatus = $data['ordstatus'];
     }
     $billemail = $email;
     $shipemail = $email;
     if ($data['customerType'] == 'anonymous') {
         if (isset($data['anonymousemail']) && !empty($data['anonymousemail'])) {
             $billemail = $email;
             $shipemail = $email;
         } else {
             $billemail = $_POST['ordbillemail'];
             $shipemail = $_POST['ordshipemail'];
         }
     }
     $newOrder = array('paymentmethod' => $data['orderpaymentmodule'], 'customerid' => $data['ordcustid'], 'billingaddress' => $billingDetails, 'ordbillemail' => $billemail, 'ordshipemail' => $shipemail, 'ordbillphone' => $billingDetails['shipphone'], 'geoipcountry' => $billingDetails['shipcountry'], 'geoipcountrycode' => GetCountryISO2ByName($billingDetails['shipcountry']), 'vendorid' => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(), 'giftcertificates' => $this->GetCartApi()->GetGiftCertificates(), 'shippingcost' => $orderSummary['shippingCost'], 'handlingcost' => $orderSummary['handlingCost'], 'pending_token' => GenerateOrderToken(), 'itemtotal' => $orderSummary['subtotal'], 'taxcost' => $orderSummary['taxCost'], 'taxrate' => $orderSummary['taxRate'], 'taxname' => $orderSummary['taxName'], 'giftcertificateamount' => $orderSummary['giftCertificateTotal'], 'companygiftcertificateamount' => $orderSummary['companyGiftCertificateTotal'], 'gatewayamount' => $orderSummary['adjustedTotalCost'], 'totalincludestax' => $orderSummary['taxIncluded'], 'shippingprovider' => $orderSummary['shippingMethod'], 'shippingmodule' => $orderSummary['shippingModule'], 'totalcost' => $orderSummary['total'], 'ordstatus' => 0, 'isdigitalorder' => (int) $this->GetCartApi()->AllProductsInCartAreIntangible(), 'currencyid' => $defaultCurrency['currencyid'], 'currencyexchangerate' => 0, 'ordercomments' => @$data['ordcustmessage'], 'ordnotes' => @$data['ordnotes'], 'products' => $this->GetCartApi()->GetProductsInCart(), 'ordtrackingno' => $data['ordtrackingno'], 'orderowner' => $loggeduser['pk_userid']);
     if (isset($data['ordbillsaveAddress'])) {
         $newOrder['billingaddress']['saveAddress'] = 1;
         if (gzte11(ISC_MEDIUMPRINT)) {
             $newOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_BILLING);
         }
     }
     if ($newOrder['paymentmethod'] == 'manual') {
         $newOrder['paymentmethodname'] = GetLang('ManualPayment');
     } else {
         if ($newOrder['paymentmethod'] == 'giftcertificate') {
             $newOrder['giftcertificateamount'] = $orderSummary['total'];
         } else {
             if ($newOrder['paymentmethod'] == 'storecredit') {
                 $newOrder['storecreditamount'] = $orderSummary['total'];
             } else {
                 if ($newOrder['paymentmethod'] == 'custom') {
                     $newOrder['paymentmethodname'] = $data['paymentField']['custom']['name'];
                 } else {
                     if ($newOrder['paymentmethod'] == 'paypal_admin') {
                         // added new condition for paypal payment option - vikas
                         $newOrder['paymentmethodname'] = GetLang('PaypalPayment');
                     } else {
                         if ($newOrder['paymentmethod'] == 'googlecheckout_admin') {
                             $newOrder['paymentmethodname'] = GetLang('GooglePayment');
                         } else {
                             if ($newOrder['paymentmethod'] == 'creditcard') {
                                 $newOrder['paymentmethodname'] = GetLang('CreditCardPayment');
                             } else {
                                 if ($newOrder['paymentmethod'] == 'cash') {
                                     $newOrder['paymentmethodname'] = GetLang('CashPayment');
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if (!$this->GetCartApi()->AllProductsInCartAreIntangible()) {
         if (isset($data['shippingUseBilling']) && $data['shippingUseBilling'] == 1) {
             $newOrder['shippingaddress'] = $newOrder['billingaddress'];
         } else {
             $newOrder['shippingaddress'] = $shippingDetails;
             if (isset($data['ordshipsaveAddress']) && gzte11(ISC_MEDIUMPRINT)) {
                 /**
                  * This is a bit tricky. We need to convert these shipping fields to use the billing
                  * field IDs when saving in the shipping_addresses table as they all use the billing
                  * fields on the frontend
                  */
                 $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
                 $shippingKeys = array_keys($shippingFields);
                 $shippingMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, $shippingKeys);
                 $shippingSessData = array();
                 foreach ($shippingMap as $fieldId => $newBillingId) {
                     if ($shippingFields[$fieldId]->record['formfieldprivateid'] !== '') {
                         continue;
                     }
                     $shippingSessData[$newBillingId] = $shippingFields[$fieldId]->getValue();
                 }
                 $newOrder['shippingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($shippingSessData);
             }
         }
         if (isset($data['ordshipsaveAddress'])) {
             $newOrder['shippingaddress']['saveAddress'] = 1;
         }
     }
     if ($orderId > 0) {
         $existingOrder = GetOrder($orderId);
         $newOrder['vendorid'] = $existingOrder['ordvendorid'];
         $newOrder['extraInfo'] = @unserialize($existingOrder['extrainfo']);
         //Alandy_2011-14-20 debug credit amount error! recalculate the gatewayamount,fetch the gatewayamount from profer order is wrong!
         //$newOrder['gatewayamount'] = $existingOrder['ordgatewayamount'];
         $newOrder['storecreditamount'] = $existingOrder['ordstorecreditamount'];
         $newOrder['currencyid'] = $existingOrder['ordcurrencyid'];
         $newOrder['currencyexchangerate'] = $existingOrder['ordcurrencyexchangerate'];
         $newOrder['orderid'] = $orderId;
         $newOrder['orddate'] = $existingOrder['orddate'];
         $newOrder['ordipaddress'] = $existingOrder['ordipaddress'];
     }
     /**
      * Save the billing/shipping custom fields for the order
      */
     if (gzte11(ISC_MEDIUMPRINT)) {
         if (isId($orderId) && isset($existingOrder['ordformsessionid']) && isId($existingOrder['ordformsessionid'])) {
             $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING), true, $existingOrder['ordformsessionid']);
         } else {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING));
             if (isId($formSessionId)) {
                 $newOrder['ordformsessionid'] = $formSessionId;
             }
         }
     }
     // dada.wang 20120406 save cgc change
     $cgces = $this->GetCartApi()->Get('COMPANYGIFTCERTIFICATES');
     if (is_array($cgces) && !empty($cgces)) {
         $newOrder['companygiftcertificates'] = $cgces;
     }
     $entity = new ISC_ENTITY_ORDER();
     if (isset($existingOrder)) {
         $newOrder['adminflag'] = 1;
         //dada.wang 2012-04-10 if has gc or cgc was remove then use this function to remove it
         $this->RemoveGCAndCGC($newOrder);
         if (!$entity->edit($newOrder)) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     } else {
         $newOrder['adminflag'] = 1;
         $data['orderid'] = $entity->add($newOrder);
         if (!$data['orderid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
         $newOrder['orderid'] = $data['orderid'];
     }
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['giftcertificateamount'] > 0 && isset($newOrder['giftcertificates']) && !empty($newOrder['giftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['giftcertificates'], $usedCertificates);
     }
     // Add by NI_20100827_Jack
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['companygiftcertificateamount'] > 0 && isset($newOrder['companygiftcertificates']) && !empty($newOrder['companygiftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_COMPANY_GIFT_CERTIFICATES'] = GetClass('ISC_COMPANYGIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_COMPANY_GIFT_CERTIFICATES']->ApplyCompanyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['companygiftcertificates'], $usedCertificates);
     }
     $GLOBALS['ISC_CLASS_DB']->CommitTransaction();
     // Did the payment method have any info it needs to save? Save it
     $provider = null;
     GetModuleById('checkout', $provider, $data['orderpaymentmodule']);
     if (is_object($provider) && method_exists($provider, 'SaveManualPaymentFields')) {
         $fields = $data['paymentField'][$data['orderpaymentmodule']];
         $provider->SaveManualPaymentFields(GetOrder($data['orderid'], false, false), $fields);
     }
     if ($data['ordstatus'] != $newOrder['ordstatus']) {
         UpdateOrderStatus($data['orderid'], $data['ordstatus'], false);
     }
     // If we're emailing the customer about their order, send it now
     if (isset($data['emailinvoice']) && $data['emailinvoice'] == 1) {
         EmailInvoiceToCustomer($data['orderid']);
     }
     unset($_SESSION['ORDER_MANAGER'][$data['orderSession']]);
     /*************************************************************
     					Alterations done by Mayank Jaitly on 28 June 2010
     			**************************************************************/
     /*	
     // commented the below code as this is not needed.
     	$customerYMMdata=array(
     						   	'year' => $data['searchyear'],
     							'make' => $data['searchmake'],
     							'model' => MakeURLNormal($data['searchmodel']),
     							'bed_size' =>$data['bedsize'],
     							'cab_size' =>$data['cabsize']
     							
     						   );
     							   
     	$clarion_entity = new ISC_ADMIN_CLARION();
     	$ymmID=$clarion_entity->fnSaveUserYMM($customerYMMdata,$data['ordcustid'],$_REQUEST['customerType'],$data['orderid']);
     */
     /***********************	End of Alteration		*********/
     /***************************************************************
     				Code Added by Mayank Jaitly on 29 June 2010
     			****************************************************************/
     // commented the below code as this is not needed.
     //	$clarion_entity->fnUpdateOrderYMM($data['orderid'],$ymmID);
     /********************* End of code   **************************/
     return $data['orderid'];
 }
 /**
  * Actually save a new order or an updated existing order in the database
  * after it's been validated.
  *
  * @param array An array of details about the order to save.
  * @param int The ID of the existing order if we're updating an order.
  * @return boolean True if successful, false if not.
  */
 private function CommitOrder($data, $orderId = 0)
 {
     $GLOBALS['ISC_CLASS_DB']->StartTransaction();
     /**
      * We need to find our billing/shipping details from the form fields first as it is
      * also used in creating the customer
      */
     $billingDetails = array();
     $shippingDetails = array();
     $billingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_BILLING, true);
     $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
     $fields = $billingFields + $shippingFields;
     $addressMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'CompanyName' => 'company', 'AddressLine1' => 'address1', 'AddressLine2' => 'address2', 'City' => 'city', 'State' => 'state', 'Zip' => 'zip', 'State' => 'state', 'Country' => 'country', 'Phone' => 'phone');
     foreach (array_keys($fields) as $fieldId) {
         $privateName = $fields[$fieldId]->record['formfieldprivateid'];
         if ($privateName == '' || !array_key_exists($privateName, $addressMap)) {
             continue;
         }
         if ($fields[$fieldId]->record['formfieldformid'] == FORMFIELDS_FORM_BILLING) {
             $detailsVar =& $billingDetails;
         } else {
             $detailsVar =& $shippingDetails;
         }
         /**
          * Find the country
          */
         if (isc_strtolower($privateName) == 'country') {
             $detailsVar['shipcountry'] = $fields[$fieldId]->getValue();
             $detailsVar['shipcountryid'] = GetCountryByName($fields[$fieldId]->getValue());
             if (!isId($detailsVar['shipcountryid'])) {
                 $detailsVar['shipcountryid'] = 0;
             }
             /**
              * Else find the state
              */
         } else {
             if (isc_strtolower($privateName) == 'state') {
                 $detailsVar['shipstate'] = $fields[$fieldId]->getValue();
                 $stateInfo = GetStateInfoByName($detailsVar['shipstate']);
                 if ($stateInfo && isId($stateInfo['stateid'])) {
                     $detailsVar['shipstateid'] = $stateInfo['stateid'];
                 } else {
                     $detailsVar['shipstateid'] = 0;
                 }
                 /**
                  * Else the rest
                  */
             } else {
                 $detailsVar['ship' . $addressMap[$privateName]] = $fields[$fieldId]->getValue();
             }
         }
     }
     // If we're creating an account for this customer, create it now
     if ($data['ordcustid'] == 0 && $data['customerType'] == 'new') {
         $customerData = array('email' => $data['custconemail'], 'password' => $data['custpassword'], 'firstname' => $billingDetails['shipfirstname'], 'lastname' => $billingDetails['shiplastname'], 'company' => $billingDetails['shipcompany'], 'phone' => $billingDetails['shipphone'], 'token' => GenerateCustomerToken(), 'customergroupid' => $data['custgroupid'], 'storecredit' => DefaultPriceFormat($data['custstorecredit']));
         /**
          * Save the customer custom fields
          */
         if (gzte11(ISC_MEDIUMPRINT)) {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT);
             if (isId($formSessionId)) {
                 $customerData['custformsessionid'] = $formSessionId;
             }
         }
         $entity = new ISC_ENTITY_CUSTOMER();
         $data['ordcustid'] = $entity->add($customerData);
         if (!$data['ordcustid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     $orderSummary = $this->CalculateOrderSummary();
     $defaultCurrency = GetDefaultCurrency();
     $email = '';
     if (isset($data['custconemail']) && $data['customerType'] == 'new') {
         $email = $data['custconemail'];
     } else {
         if (isset($data['anonymousemail']) && $data['customerType'] == 'anonymous') {
             $email = $data['anonymousemail'];
         }
     }
     $newOrder = array('paymentmethod' => $data['orderpaymentmodule'], 'customerid' => $data['ordcustid'], 'billingaddress' => $billingDetails, 'ordbillemail' => $email, 'ordbillphone' => $billingDetails['shipphone'], 'geoipcountry' => $billingDetails['shipcountry'], 'geoipcountrycode' => GetCountryISO2ByName($billingDetails['shipcountry']), 'vendorid' => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(), 'giftcertificates' => $this->GetCartApi()->GetGiftCertificates(), 'shippingcost' => $orderSummary['shippingCost'], 'handlingcost' => $orderSummary['handlingCost'], 'pending_token' => GenerateOrderToken(), 'itemtotal' => $orderSummary['subtotal'], 'taxcost' => $orderSummary['taxCost'], 'taxrate' => $orderSummary['taxRate'], 'taxname' => $orderSummary['taxName'], 'giftcertificateamount' => $orderSummary['giftCertificateTotal'], 'gatewayamount' => $orderSummary['adjustedTotalCost'], 'totalincludestax' => $orderSummary['taxIncluded'], 'shippingprovider' => $orderSummary['shippingMethod'], 'shippingmodule' => $orderSummary['shippingModule'], 'totalcost' => $orderSummary['total'], 'ordstatus' => 0, 'isdigitalorder' => (int) $this->GetCartApi()->AllProductsInCartAreIntangible(), 'currencyid' => $defaultCurrency['currencyid'], 'currencyexchangerate' => 0, 'ordercomments' => @$data['ordcustmessage'], 'ordnotes' => @$data['ordnotes'], 'products' => $this->GetCartApi()->GetProductsInCart(), 'ordtrackingno' => $data['ordtrackingno']);
     if (isset($data['ordbillsaveAddress'])) {
         $newOrder['billingaddress']['saveAddress'] = 1;
         if (gzte11(ISC_MEDIUMPRINT)) {
             $newOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_BILLING);
         }
     }
     if ($newOrder['paymentmethod'] == 'manual') {
         $newOrder['paymentmethodname'] = GetLang('ManualPayment');
     } else {
         if ($newOrder['paymentmethod'] == 'giftcertificate') {
             $newOrder['giftcertificateamount'] = $orderSummary['total'];
         } else {
             if ($newOrder['paymentmethod'] == 'storecredit') {
                 $newOrder['storecreditamount'] = $orderSummary['total'];
             } else {
                 if ($newOrder['paymentmethod'] == 'custom') {
                     $newOrder['paymentmethodname'] = $data['paymentField']['custom']['name'];
                 }
             }
         }
     }
     if (!$this->GetCartApi()->AllProductsInCartAreIntangible()) {
         if (isset($data['shippingUseBilling']) && $data['shippingUseBilling'] == 1) {
             $newOrder['shippingaddress'] = $newOrder['billingaddress'];
         } else {
             $newOrder['shippingaddress'] = $shippingDetails;
             if (isset($data['ordshipsaveAddress']) && gzte11(ISC_MEDIUMPRINT)) {
                 /**
                  * This is a bit tricky. We need to convert these shipping fields to use the billing
                  * field IDs when saving in the shipping_addresses table as they all use the billing
                  * fields on the frontend
                  */
                 $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true);
                 $shippingKeys = array_keys($shippingFields);
                 $shippingMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, $shippingKeys);
                 $shippingSessData = array();
                 foreach ($shippingMap as $fieldId => $newBillingId) {
                     if ($shippingFields[$fieldId]->record['formfieldprivateid'] !== '') {
                         continue;
                     }
                     $shippingSessData[$newBillingId] = $shippingFields[$fieldId]->getValue();
                 }
                 $newOrder['shippingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($shippingSessData);
             }
         }
         if (isset($data['ordshipsaveAddress'])) {
             $newOrder['shippingaddress']['saveAddress'] = 1;
         }
     }
     if ($orderId > 0) {
         $existingOrder = GetOrder($orderId);
         $newOrder['vendorid'] = $existingOrder['ordvendorid'];
         $newOrder['extraInfo'] = @unserialize($existingOrder['extrainfo']);
         $newOrder['gatewayamount'] = $existingOrder['ordgatewayamount'];
         $newOrder['storecreditamount'] = $existingOrder['ordstorecreditamount'];
         $newOrder['currencyid'] = $existingOrder['ordcurrencyid'];
         $newOrder['currencyexchangerate'] = $existingOrder['ordcurrencyexchangerate'];
         $newOrder['orderid'] = $orderId;
         $newOrder['orddate'] = $existingOrder['orddate'];
         $newOrder['ordipaddress'] = $existingOrder['ordipaddress'];
     }
     /**
      * Save the billing/shipping custom fields for the order
      */
     if (gzte11(ISC_MEDIUMPRINT)) {
         if (isId($orderId) && isset($existingOrder['ordformsessionid']) && isId($existingOrder['ordformsessionid'])) {
             $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING), true, $existingOrder['ordformsessionid']);
         } else {
             $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING));
             if (isId($formSessionId)) {
                 $newOrder['ordformsessionid'] = $formSessionId;
             }
         }
     }
     $entity = new ISC_ENTITY_ORDER();
     if (isset($existingOrder)) {
         if (!$entity->edit($newOrder)) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     } else {
         $data['orderid'] = $entity->add($newOrder);
         if (!$data['orderid']) {
             $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
             return false;
         }
     }
     // If one or more gift certificates were used we need to apply them to this order
     if ($newOrder['giftcertificateamount'] > 0 && isset($newOrder['giftcertificates']) && !empty($newOrder['giftcertificates'])) {
         $usedCertificates = array();
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['giftcertificates'], $usedCertificates);
     }
     $GLOBALS['ISC_CLASS_DB']->CommitTransaction();
     // Did the payment method have any info it needs to save? Save it
     $provider = null;
     GetModuleById('checkout', $provider, $data['orderpaymentmodule']);
     if (is_object($provider) && method_exists($provider, 'SaveManualPaymentFields')) {
         $fields = $data['paymentField'][$data['orderpaymentmodule']];
         $provider->SaveManualPaymentFields(GetOrder($data['orderid'], false, false), $fields);
     }
     if ($data['ordstatus'] != $newOrder['ordstatus']) {
         UpdateOrderStatus($data['orderid'], $data['ordstatus'], false);
     }
     // If we're emailing the customer about their order, send it now
     if (isset($data['emailinvoice']) && $data['emailinvoice'] == 1) {
         EmailInvoiceToCustomer($data['orderid']);
     }
     unset($_SESSION['ORDER_MANAGER'][$data['orderSession']]);
     return $data['orderid'];
 }
Example #3
0
		private function restoreOrderActionHandler ($orderId)
		{
			if (!$this->auth->HasPermission(AUTH_Undelete_Orders)) {
				return array(
					'success' => false,
				);
			}

			$orderId = (int)$orderId;
			if (!$orderId) {
				return array(
					'success' => false,
				);
			}

			$order = GetOrder($orderId, false, false, true);
			if (!$order) {
				return array(
					'success' => false,
				);
			}

			$entity = new ISC_ENTITY_ORDER;
			if (!$entity->undelete($orderId)) {
				return array(
					'success' => false,
				);
			}

			FlashMessage(GetLang('iphoneRestoreOrderSuccess', array(
				'orderId' => $orderId,
			)), MSG_SUCCESS);

			return array(
				'success' => true,
			);
		}
Example #4
0
/**
 * Create an actual order.
 *
 * @param array An array of information about the order.
 * @param array An array of items in the order.
 * @return string The token of the pending order.
 */
function CreateOrder($orderData, $orderProducts)
{
	$entity = new ISC_ENTITY_ORDER();

	// Delete the old configurable product files uploaded by the customers.
	DeleteOldConfigProductFiles();

	$pendingToken = GenerateOrderToken();
	$orderData['ordtoken'] = $pendingToken;
	$vendorInfo = $orderData['vendorinfo'];
	unset($orderData['vendorinfo']);
	foreach($vendorInfo as $vendorId => $vendorData) {
		$products = array();
		foreach($vendorData['products'] as $productId => $quantity) {
			$productInfo = $orderProducts[$productId];
			$productInfo['quantity'] = $quantity;
			$products[] = $productInfo;
		}
		list($vendorId,) = explode('_', $vendorId, 2);
		$vendorOrder = array_merge($orderData, $vendorData);
		$vendorOrder['products'] = $products;
		$vendorOrder['vendorid'] = $vendorId;
		// If we failed to add the order, stop
		if(!$entity->add($vendorOrder)) {
			return false;
		}
	}
	return $pendingToken;
}
Example #5
0
		/**
		 * This method marks orders as deleted using ISC_ENTITY_ORDER::delete
		 *
		 * @return void
		 */
		protected function DeleteOrders ()
		{
			// final permission checks
			$canManage = $this->auth->HasPermission(AUTH_Manage_Orders);
			$canDelete = $this->auth->HasPermission(AUTH_Delete_Orders);

			if (!$canDelete) {
				if ($canManage) {
					$this->ManageOrders(GetLang('Unauthorized'), MSG_ERROR);
					return;
				}
				$this->engine->DoHomePage(GetLang('Unauthorized'), MSG_ERROR);
				return;
			}

			// input validation
			$orderIds = array();
			if (isset($_POST['orders']) && is_array($_POST['orders']) && !empty($_POST['orders'])) {
				$orderIds = array_map('intval', $_POST['orders']);
			}

			if (empty($orderIds)) {
				if ($canManage) {
					$this->ManageOrders();
					return;
				}
				$this->engine->DoHomePage();
				return;
			}

			// do the order delete
			$GLOBALS['ISC_CLASS_LOG']->LogAdminAction(count($orderIds));

			// determine which delete method to use based on store settings
			$deleteMethod = 'delete';
			if (GetConfig('DeletedOrdersAction') == 'purge') {
				$deleteMethod = 'purge';
			}

			$entity = new ISC_ENTITY_ORDER;
			foreach ($orderIds as $orderId) {
				if (!$entity->$deleteMethod($orderId)) {
					if ($canManage) {
						$this->ManageOrders($entity->getError(), MSG_ERROR);
						return;
					}
					$this->engine->DoHomePage($entity->getError(), MSG_ERROR);
					return;
				}
			}

			$message = GetLang('OrdersDeletedSuccessfully');

			if ($canManage) {
				$this->ManageOrders($message, MSG_SUCCESS);
				return;
			}
			$this->engine->DoHomePage($message, MSG_SUCCESS);
		}
Example #6
0
	/**
	 * Create a new order in ISC based on a new-order-notification from google
	 *
	 * @return void
	 **/
	private function CreateOrder()
	{
		if(!$this->LoadCart($this->module->cartid))
		{
			// Todo: What is the correct way to fail here?
			return;
		}

		// Ensure split shipping is disabled
		$this->quote->setIsSplitShipping(false);

		// Set the billing address for the order
		$billingAddress =
			$this->GetAddressFromResponse($this->response->data[$this->response->root]['buyer-billing-address']);
		$this->quote->getBillingAddress()
			->setAddressByArray($billingAddress);

		if(!$this->quote->isDigital()) {
			// Set the shipping address for the order
			$shippingAddress =
				$this->GetAddressFromResponse($this->response->data[$this->response->root]['buyer-shipping-address']);
			$this->quote->getShippingAddress()
				->setAddressByArray($shippingAddress);

			// Attempt to find shipping costs in the response from Google
			if (isset($this->response->data[$this->response->root]['order-adjustment']['shipping']['merchant-calculated-shipping-adjustment'])) {
				$shipping = $this->response->data[$this->response->root]['order-adjustment']['shipping']['merchant-calculated-shipping-adjustment'];
			} else {
				$shipping = array (
					'shipping-cost' => array (
						'VALUE' => 0
					),
					'shipping-name' => array (
						'VALUE' => ''
					),
				);
			}

			$this->quote->getShippingAddress()
				->setShippingMethod(
					$shipping['shipping-cost']['VALUE'],
					$shipping['shipping-name']['VALUE'],
					$this->getShippingProviderModuleByName($shipping['shipping-name']['VALUE'])
				);
		}

		$this->handleNewOrderNotificationCouponAdjustment();
		$this->handleNewOrderNotificationGiftCertificateAdjustment();

		$selectedCurrency = getCurrencyById($GLOBALS['CurrentCurrency']);
		$newOrder = array(
			'orderpaymentmodule' => 'checkout_googlecheckout',
			'ordcurrencyid' => $selectedCurrency['currencyid'],
			'ordcurrencyexchangerate' => $selectedCurrency['currencyexchangerate'],
			'ordipaddress' => '',
			'extraInfo' => array(),

			'quote' => $this->quote,
		);

		$entity = new ISC_ENTITY_ORDER();
		$orderId = $entity->add($newOrder);

		// Failed to create the order
		if(!$orderId) {
			$GLOBALS['ISC_CLASS_LOG']->LogSystemError($this->logtype, sprintf(GetLang('GoogleCheckoutMissingCart'), isc_html_escape($this->module->cartid)));
			return;
		}

		$order = getOrder($orderId);

		$googleid = $this->response->data['new-order-notification']['google-order-number']['VALUE'];
		$this->SendGoogleNewOrderId($googleid, $order['orderid']);
		$updatedOrder = array(
			'ordpayproviderid' => $googleid,
		);

		$orderIds = array($order['orderid']);

		// Update the orders in the database
		$GLOBALS['ISC_CLASS_DB']->UpdateQuery('orders', $updatedOrder, "orderid IN (".implode(',', $orderIds).")");

		$completed = CompletePendingOrder($order['ordtoken'], ORDER_STATUS_PENDING, false);

		if ($this->response->data['new-order-notification']['buyer-marketing-preferences']['email-allowed']['VALUE'] == 'true') {
			$this->SubscribeCustomerToLists($order['orderid']);
		}

		if (!$completed) {
			$GLOBALS['ISC_CLASS_LOG']->LogSystemError($this->logtype, sprintf(GetLang('GoogleCheckoutCantCompleteOrder'), isc_html_escape($pendingToken), isc_html_escape(var_export($completed, true))));
			return;
		}

		EmptyCartAndKillCheckout();
		$GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderCreated'), (int) $order['orderid'], isc_html_escape($googleid)));
	}
Example #7
0
/**
 * Create an actual order.
 *
 * @param array An array of information about the order.
 * @param array An array of items in the order.
 * @return string The token of the pending order.
 */
function CreateOrder($orderData, $orderProducts)
{
    $entity = new ISC_ENTITY_ORDER();
    // Delete any orders that are incomplete and were placed more than a week ago. This helps keep the database clean
    $entity->DeleteOldOrders();
    // Delete the old configurable product files uploaded by the customers.
    DeleteOldConfigProductFiles();
    $pendingToken = GenerateOrderToken();
    $orderData['pending_token'] = $pendingToken;
    $vendorInfo = $orderData['vendorinfo'];
    unset($orderData['vendorinfo']);
    foreach ($vendorInfo as $vendorId => $vendorData) {
        $products = array();
        foreach ($vendorData['products'] as $productId => $quantity) {
            $productInfo = $orderProducts[$productId];
            $productInfo['quantity'] = $quantity;
            $products[] = $productInfo;
        }
        list($vendorId, ) = explode('_', $vendorId, 2);
        $vendorOrder = array_merge($orderData, $vendorData);
        $vendorOrder['products'] = $products;
        $vendorOrder['vendorid'] = $vendorId;
        // If we failed to add the order, stop
        //if(!$entity->add($vendorOrder)) {
        //return false;
        //}
        if ($_SESSION['makeaoffer'] == "Yes") {
            if (!$entity->offeradd($vendorOrder)) {
                return false;
            }
        } else {
            if (!$entity->add($vendorOrder)) {
                return false;
            }
        }
    }
    return $pendingToken;
}
Example #8
0
	/**
	 * Build the contents for the order confirmation page. This function sets up everything to be used by
	 * the order confirmation on the express checkout page as well as the ConfirmOrder page when using a
	 * multi step checkout.
	 */
	public function BuildOrderConfirmation()
	{
		$GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
		if(!GetConfig('ShowMailingListInvite')) {
			$GLOBALS['HideMailingListInvite'] = 'none';
		}

		// Do we need to show the special offers & discounts checkbox and should they
		// either of the newsletter checkboxes be ticked by default?
		if (GetConfig('MailAutomaticallyTickNewsletterBox')) {
			$GLOBALS['NewsletterBoxIsTicked'] = 'checked="checked"';
		}

		if (ISC_EMAILINTEGRATION::doOrderAddRulesExist()) {
			if (GetConfig('MailAutomaticallyTickOrderBox')) {
				$GLOBALS['OrderBoxIsTicked'] = 'checked="checked"';
			}
		}
		else {
			$GLOBALS['HideOrderCheckBox'] = "none";
		}

		if(isset($_REQUEST['ordercomments'])) {
			$GLOBALS['OrderComments'] = $_REQUEST['ordercomments'];
		}

		// Now we check if we have an incoming coupon or gift certificate code to apply
		if (isset($_REQUEST['couponcode']) && $_REQUEST['couponcode'] != '') {
			$code = trim($_REQUEST['couponcode']);

			// Were we passed a gift certificate code?
			if (self::isCertificateCode($code)) {
				try {
					$this->getQuote()->applyGiftCertificate($code);

					// If successful show a message
					$GLOBALS['CheckoutSuccessMsg'] = GetLang('GiftCertificateAppliedToCart');
				}
				catch(ISC_QUOTE_EXCEPTION $e) {
					$GLOBALS['CheckoutErrorMsg'] = $e->getMessage();
				}
			}
			// Otherwise, it must be a coupon code
			else {
				try {
					$this->getQuote()->applyCoupon($code);

					// Coupon code applied successfully
					$GLOBALS['CheckoutSuccessMsg'] = GetLang('CouponAppliedToCart');
				}
				catch(ISC_QUOTE_EXCEPTION $e) {
					$GLOBALS['CheckoutErrorMsg'] = $e->getMessage();
				}
			}
		}

		$GLOBALS['ISC_CLASS_ACCOUNT'] = GetClass('ISC_ACCOUNT');

		// Determine what we'll be showing for the redeem gift certificate/coupon code box
		if (gzte11(ISC_LARGEPRINT)) {
			$GLOBALS['RedeemTitle'] = GetLang('RedeemGiftCertificateOrCoupon');
			$GLOBALS['RedeemIntro'] = GetLang('RedeemGiftCertificateorCouponIntro');
		}
		else {
			$GLOBALS['RedeemTitle'] = GetLang('RedeemCouponCode');
			$GLOBALS['RedeemIntro'] = GetLang('RedeemCouponCodeIntro');
		}

		$GLOBALS['HideCheckoutError'] = "none";
		$GLOBALS['HidePaymentOptions'] = "";
		$GLOBALS['HideUseCoupon'] = '';
		$checkoutProviders = array();

		// if the provider list html is set in session then use it as the payment provider options.
		// it's normally set in payment modules when it's required.
		if(isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
			$GLOBALS['HidePaymentProviderList'] = "";
			$GLOBALS['HidePaymentOptions'] = "";
			$GLOBALS['PaymentProviders'] = $_SESSION['CHECKOUT']['ProviderListHTML'];
			$GLOBALS['StoreCreditPaymentProviders'] = $_SESSION['CHECKOUT']['ProviderListHTML'];
			$GLOBALS['CheckoutWith'] = "";
		} else {
			// Get a list of checkout providers
			$checkoutProviders = GetCheckoutModulesThatCustomerHasAccessTo(true);


			// If no checkout providers are set up, send an email to the store owner and show an error message
			if (empty($checkoutProviders)) {
				$GLOBALS['HideConfirmOrderPage'] = "none";
				$GLOBALS['HideCheckoutError'] = '';
				$GLOBALS['HideTopPaymentButton'] = "none";
				$GLOBALS['HidePaymentProviderList'] = "none";
				$GLOBALS['CheckoutErrorMsg'] = GetLang('NoCheckoutProviders');
				$GLOBALS['NoCheckoutProvidersError'] = sprintf(GetLang("NoCheckoutProvidersErrorLong"), $GLOBALS['ShopPath']);

				$GLOBALS['EmailHeader'] = GetLang("NoCheckoutProvidersSubject");
				$GLOBALS['EmailMessage'] = sprintf(GetLang("NoCheckoutProvidersErrorLong"), $GLOBALS['ShopPath']);

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

				require_once(ISC_BASE_PATH . "/lib/email.php");
				$obj_email = GetEmailClass();
				$obj_email->Set('CharSet', GetConfig('CharacterSet'));
				$obj_email->From(GetConfig('OrderEmail'), GetConfig('StoreName'));
				$obj_email->Set("Subject", GetLang("NoCheckoutProvidersSubject"));
				$obj_email->AddBody("html", $message);
				$obj_email->AddRecipient(GetConfig('AdminEmail'), "", "h");
				$email_result = $obj_email->Send();
			}

			// We have more than one payment provider, hide the top button and build a list
			else if (count($checkoutProviders) > 1) {
				$GLOBALS['HideTopPaymentButton'] = "none";
				$GLOBALS['HideCheckoutError'] = "none";
			}

			// There's only one payment provider - hide the list
			else {
				$GLOBALS['HidePaymentProviderList'] = "none";
				$GLOBALS['HideCheckoutError'] = "none";
				$GLOBALS['HidePaymentOptions'] = "none";
				list(,$provider) = each($checkoutProviders);
				if(method_exists($provider['object'], 'ShowPaymentForm') && !isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
					$GLOBALS['ExpressCheckoutLoadPaymentForm'] = 'ExpressCheckout.ShowSingleMethodPaymentForm();';
				}
				if ($provider['object']->GetPaymentType() == PAYMENT_PROVIDER_OFFLINE) {
					$GLOBALS['PaymentButtonSwitch'] = "ShowContinueButton();";
				}
				$GLOBALS['CheckoutWith'] = $provider['object']->GetDisplayName();
			}

			// Build the list of payment provider options
			$GLOBALS['PaymentProviders'] = $GLOBALS['StoreCreditPaymentProviders'] =  "";
			foreach ($checkoutProviders as $provider) {
				$GLOBALS['ProviderChecked'] = '';
				if(count($checkoutProviders) == 1) {
					$GLOBALS['ProviderChecked'] = 'checked="checked"';
				}
				$GLOBALS['ProviderId'] = $provider['object']->GetId();
				$GLOBALS['ProviderName'] = isc_html_escape($provider['object']->GetDisplayName());
				$GLOBALS['ProviderType'] = $provider['object']->GetPaymentType("text");
				if(method_exists($provider['object'], 'ShowPaymentForm')) {
					$GLOBALS['ProviderPaymentFormClass'] = 'ProviderHasPaymentForm';
				}
				else {
					$GLOBALS['ProviderPaymentFormClass'] = '';
				}
				$GLOBALS['PaymentFieldPrefix'] = '';
				$GLOBALS['PaymentProviders'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CheckoutProviderOption");
				$GLOBALS['PaymentFieldPrefix'] = 'credit_';
				$GLOBALS['StoreCreditPaymentProviders'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CheckoutProviderOption");
			}

		}

		// Are we coming back to this page for a particular reason?
		if (isset($_SESSION['REDIRECT_TO_CONFIRMATION_MSG'])) {
			$GLOBALS['HideCheckoutError'] = '';
			$GLOBALS['CheckoutErrorMsg'] = $_SESSION['REDIRECT_TO_CONFIRMATION_MSG'];
			unset($_SESSION['REDIRECT_TO_CONFIRMATION_MSG']);
		}

		$displayIncludingTax = false;
		if(getConfig('taxDefaultTaxDisplayCart') != TAX_PRICES_DISPLAY_EXCLUSIVE) {
			$displayIncludingTax = true;
		}

		$items = $this->getQuote()->getItems();

		// Start building the summary of all of the items in the order
		$GLOBALS['SNIPPETS']['CartItems'] = '';
		foreach ($items as $item) {
			$GLOBALS['ProductQuantity'] = $item->getQuantity();

			$price = $item->getPrice($displayIncludingTax);
			$total = $item->getTotal($displayIncludingTax);
			$GLOBALS['ProductPrice'] = currencyConvertFormatPrice($price);
			$GLOBALS['ProductTotal'] = currencyConvertFormatPrice($total);

			if($item instanceof ISC_QUOTE_ITEM_GIFTCERTIFICATE) {
				$GLOBALS['GiftCertificateName'] = isc_html_escape($item->getName());
				$GLOBALS['GiftCertificateTo'] = isc_html_escape($item->getRecipientName());
				$GLOBALS['SNIPPETS']['CartItems'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CheckoutCartItemGiftCertificate");
				continue;
			}

			$GLOBALS['ProductAvailability'] = $item->getAvailability();
			$GLOBALS['ItemId'] = $item->getProductId();

			// Is this product a variation?
			$GLOBALS['ProductOptions'] = '';
			$options = $item->getVariationOptions();
			if(!empty($options)) {
				$GLOBALS['ProductOptions'] .= "<br /><small>(";
				$comma = '';
				foreach($options as $name => $value) {
					if(!trim($name) || !trim($value)) {
						continue;
					}
					$GLOBALS['ProductOptions'] .= $comma.isc_html_escape($name).": ".isc_html_escape($value);
					$comma = ', ';
				}
				$GLOBALS['ProductOptions'] .= ")</small>";
			}
			$GLOBALS['EventDate'] = '';
			$eventDate = $item->getEventDate(true);
			if(!empty($eventDate)) {
				$GLOBALS['EventDate'] = '
					<div style="font-style: italic; font-size:10px; color:gray">(' .
						$item->getEventName() . ': ' . isc_date('M jS Y', $eventDate) .
					')</div>';
			}

			$GLOBALS['HideGiftWrapping'] = 'display: none';
			$GLOBALS['GiftWrappingName'] = '';
			$GLOBALS['GiftMessagePreview'] = '';
			$GLOBALS['HideGiftMessagePreview'] = 'display: none';

			$wrapping = $item->getGiftWrapping();
			if($wrapping !== false) {
				$GLOBALS['HideGiftWrapping'] = '';
				$GLOBALS['GiftWrappingName'] = isc_html_escape($wrapping['wrapname']);
				if(!empty($wrapping['wrapmessage'])) {
					if(isc_strlen($wrapping['wrapmessage']) > 30) {
						$wrapping['wrapmessage'] = substr($wrapping['wrapmessage'], 0, 27).'...';
					}
					$GLOBALS['GiftMessagePreview'] = isc_html_escape($wrapping['wrapmessage']);
					$GLOBALS['HideGiftMessagePreview'] = '';
				}
			}

			//create configurable product fields on order confirmation page with the data posted from add to cart page
			$GLOBALS['CartProductFields'] = '';
			$configuration = $item->getConfiguration();
			if (!empty($configuration)) {
				require_once ISC_BASE_PATH.'/includes/display/CartContent.php';
				ISC_CARTCONTENT_PANEL::GetProductFieldDetails($configuration, $item->getId());
			}

			$GLOBALS['ProductName'] = isc_html_escape($item->getName());
			$GLOBALS['ProductImage'] = imageThumb($item->getThumbnail(), prodLink($item->getName()));

			$GLOBALS['HideExpectedReleaseDate'] = 'display: none;';
			if($item->isPreOrder()) {
				$GLOBALS['ProductExpectedReleaseDate'] = $item->getPreOrderMessage();
				$GLOBALS['HideExpectedReleaseDate'] = '';
			}

			$GLOBALS['SNIPPETS']['CartItems'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CheckoutCartItem");
		}

		// Do we have a shipping price to show?
		if(!$this->getQuote()->isDigital()) {
			$shippingAddresses = $this->getQuote()->getShippingAddresses();
			$numShippingAddresses = count($shippingAddresses);
			if($numShippingAddresses == 1) {
				$shippingAddress = $this->getQuote()->getShippingAddress();
				$GLOBALS['ShippingAddress'] = $GLOBALS['ISC_CLASS_ACCOUNT']->FormatShippingAddress($shippingAddress->getAsArray());
			}
			else {
				$GLOBALS['ShippingAddress'] = '<em>(Order will be shipped to multiple addresses)</em>';
			}

			// Show the shipping details
			$GLOBALS['HideShippingDetails'] = '';
		}
		// This is a digital order - no shipping applies
		else {
			$GLOBALS['HideShippingDetails'] = 'display: none';
			$GLOBALS['HideShoppingCartShippingCost'] = 'none';
			$GLOBALS['ShippingAddress'] = GetLang('NotRequiredForDigitalDownloads');
			$GLOBALS['ShippingMethod'] = GetLang('ShippingImmediateDownload');
		}

		$billingAddress = $this->getQuote()->getBillingAddress();
		$GLOBALS['BillingAddress'] = getClass('ISC_ACCOUNT')
			->formatShippingAddress($billingAddress->getAsArray());

		$totalRows = self::getQuoteTotalRows($this->getQuote());
		$templateTotalRows = '';
		foreach($totalRows as $id => $totalRow) {
			$GLOBALS['ISC_CLASS_TEMPLATE']->assign('label', $totalRow['label']);
			$GLOBALS['ISC_CLASS_TEMPLATE']->assign('classNameAppend', ucfirst($id));
			$value = currencyConvertFormatPrice($totalRow['value']);
			$GLOBALS['ISC_CLASS_TEMPLATE']->assign('value', $value);
			$templateTotalRows .= $GLOBALS['ISC_CLASS_TEMPLATE']->getSnippet('CheckoutCartTotal');
		}
		$GLOBALS['ISC_CLASS_TEMPLATE']->assign('totals', $templateTotalRows);

		$grandTotal = $this->getQuote()->getGrandTotal();
		$GLOBALS['GrandTotal'] = formatPrice($grandTotal);
		if($grandTotal == 0) {
			$GLOBALS['HidePaymentOptions'] = "none";
			$GLOBALS['HideUseCoupon'] = 'none';
			$GLOBALS['HidePaymentProviderList'] = "none";
			$GLOBALS['PaymentButtonSwitch'] = "ShowContinueButton(); ExpressCheckout.UncheckPaymentProvider();";
		}

		// Does the customer have any store credit they can use?
		$GLOBALS['HideUseStoreCredit'] = "none";
		$GLOBALS['HideRemainingStoreCredit'] = "none";
		$customer = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerDataByToken();
		if ($customer['custstorecredit'] > 0) {
			$GLOBALS['HidePaymentOptions'] = "";
			$GLOBALS['StoreCredit'] = CurrencyConvertFormatPrice($customer['custstorecredit']);
			$GLOBALS['HideUseStoreCredit'] = "";
			$GLOBALS['HidePaymentProviderList'] = "none";
			// The customer has enough store credit to pay for the entirity of this order
			if ($customer['custstorecredit'] >= $grandTotal) {
				$GLOBALS['PaymentButtonSwitch'] = "ShowContinueButton();";
				$GLOBALS['HideLimitedCreditWarning'] = "none";
				$GLOBALS['HideLimitedCreditPaymentOption'] = "none";
				$GLOBALS['HideCreditPaymentMethods'] = "none";
				$GLOBALS['RemainingCredit'] = $customer['custstorecredit'] - $grandTotal;
				if ($GLOBALS['RemainingCredit'] > 0) {
					$GLOBALS['HideRemainingStoreCredit'] = '';
					$GLOBALS['RemainingCredit'] = CurrencyConvertFormatPrice($GLOBALS['RemainingCredit']);
				}
			}
			// Customer doesn't have enough store credit to pay for the order
			else {
				$GLOBALS['Remaining'] = CurrencyConvertFormatPrice($grandTotal-$customer['custstorecredit']);

				if(count($checkoutProviders) == 1) {
					$GLOBALS['CheckoutStoreCreditWarning'] = sprintf(GetLang('CheckoutStoreCreditWarning2'), $GLOBALS['Remaining'], $GLOBALS['CheckoutWith']);
					$GLOBALS['HideLimitedCreditPaymentOption'] = "none";
				}
				else {
					$GLOBALS['CheckoutStoreCreditWarning'] = GetLang('CheckoutStoreCreditWarning');
				}
				$GLOBALS['ISC_LANG']['CreditPaymentMethod'] = sprintf(GetLang('CreditPaymentMethod'), $GLOBALS['Remaining']);
			}

			if (count($checkoutProviders) > 1) {
				$GLOBALS['CreditAlt'] = GetLang('CheckoutCreditAlt');
			}
			else if (count($checkoutProviders) <= 1 && isset($GLOBALS['CheckoutWith'])) {
				$GLOBALS['CreditAlt'] = sprintf(GetLang('CheckoutCreditAltOneMethod'), $GLOBALS['CheckoutWith']);
			}
			else {
				if ($customer['custstorecredit'] >= $grandTotal) {
					$GLOBALS['HideCreditAltOptionList'] = "none";
					$GLOBALS['HideConfirmOrderPage'] = "";
					$GLOBALS['HideTopPaymentButton'] = "none";
					$GLOBALS['HideCheckoutError'] = "none";
					$GLOBALS['CheckoutErrorMsg'] = '';
				}
			}
		}

		// Customer has hit this page before. Delete the existing pending order
		// The reason we do a delete is if they're hitting this page again, something
		// has changed with their order or something has become invalid with it along the way.
		if (isset($_COOKIE['SHOP_ORDER_TOKEN']) && IsValidPendingOrderToken($_COOKIE['SHOP_ORDER_TOKEN'])) {
			$query = "
				SELECT orderid
				FROM [|PREFIX|]orders
				WHERE ordtoken='".$GLOBALS['ISC_CLASS_DB']->Quote($_COOKIE['SHOP_ORDER_TOKEN'])."' AND ordstatus=0
			";
			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
			while($order = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
				$entity = new ISC_ENTITY_ORDER();
				/** @todo ISC-1141 check to see if this needs changing to ->purge() */
				/** @todo ISC-860 this is relying on another bugfix, I'm leaving this as ->delete() for now so that orders remain in the db somewhere at least -gwilym */
				if ($entity->delete($order['orderid'], true)) {
					$GLOBALS['ISC_CLASS_LOG']->LogSystemNotice('general', GetLang('OrderDeletedAutomatically', array('order' => $order['orderid'])));
				}
			}
		}

		// Are we showing an error message?
		if (isset($GLOBALS['CheckoutErrorMsg']) && $GLOBALS['CheckoutErrorMsg'] != '') {
			$GLOBALS['HideCheckoutError'] = '';
		}
		else {
			$GLOBALS['HideCheckoutError'] = "none";
		}

		// Is there a success message to show?
		if (isset($GLOBALS['CheckoutSuccessMsg']) && $GLOBALS['CheckoutSuccessMsg'] != '') {
			$GLOBALS['HideCheckoutSuccess'] = '';
		}
		else {
			$GLOBALS['HideCheckoutSuccess'] = "none";
		}

		if(GetConfig('EnableOrderComments') == 1) {
			$GLOBALS['HideOrderComments'] = "";
		} else {
			$GLOBALS['HideOrderComments'] = "none";
		}

		if(GetConfig('EnableOrderTermsAndConditions') == 1) {

			$GLOBALS['HideOrderTermsAndConditions'] = "";

			if(GetConfig('OrderTermsAndConditionsType') == "link") {
				$GLOBALS['AgreeTermsAndConditions'] = GetLang('YesIAgree');

				$GLOBALS['TermsAndConditionsLink'] = "<a href='".GetConfig('OrderTermsAndConditionsLink')."' target='_BLANK'>".strtolower(GetLang('TermsAndConditions'))."</a>.";

				$GLOBALS['HideTermsAndConditionsTextarea'] = "display:none;";

			} else {
				$GLOBALS['HideTermsAndConditionsTextarea']= '';
				$GLOBALS['OrderTermsAndConditions'] = GetConfig('OrderTermsAndConditions');
				$GLOBALS['AgreeTermsAndConditions'] = GetLang('AgreeTermsAndConditions');
				$GLOBALS['TermsAndConditionsLink'] = '';
			}
		} else {
			$GLOBALS['HideOrderTermsAndConditions'] = "display:none;";
		}

		// BCSIXBETA-372 - mail format preferences removed/disabled for now
		// %%SNIPPET_CheckoutMailFormatPreference%% references also need to be added back into the checkout panels/snippets to re-enable this if needed
//		$GLOBALS['MailFormatPreferenceOptions'] = $this->GenerateMailFormatPreferenceOptions();
//		$GLOBALS['SNIPPETS']['CheckoutMailFormatPreference'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('CheckoutMailFormatPreference');
	}
Example #9
0
	public function __construct($orderId = null)
	{
		$this->setDoubleOptIn(GetConfig('EmailIntegrationOrderDoubleOptin'));
		$this->setSendWelcome(GetConfig('EmailIntegrationOrderSendWelcome'));
		$this->setSubscriptionIP(GetIP());

		if (!$orderId) {
			return;
		}

		$entity = new ISC_ENTITY_ORDER;

		$data = $entity->get($orderId);
		if (!$data) {
			throw new Interspire_EmailIntegration_Subscription_Exception;
		}
		$this->_data = $data;
		unset($data);

		// copy any form fields associated with the order + associated customer and place into local subscription data

		if (isId($this->_data['ordformsessionid'])) {
			/** @var ISC_FORM */
			$form = $GLOBALS["ISC_CLASS_FORM"];

			$customFields = array();

			$formData = $form->getSavedSessionData($this->_data['customer']['custformsessionid']);
			if ($formData && !empty($formData)) {
				$customFields += $formData;
			}

			$formData = $form->getSavedSessionData($this->_data['ordformsessionid']);
			if ($formData && !empty($formData)) {
				$customFields += $formData;
			}

			foreach ($customFields as $fieldId => $value) {
				$this->_data['FormField_' . $fieldId] = $value;
			}
		}

		// generate fields specifically for email integration based on order data (ones that aren't covered by simple order data or by Form Fields)

		// get the first shipping address record because IEM had shipping method as mappable field
		$this->_data['shipping_method'] = '';
		$shippingMethod = $GLOBALS['ISC_CLASS_DB']->FetchOne("SELECT `method` FROM [|PREFIX|]order_shipping WHERE order_id = " . (int)$orderId . " LIMIT 1", 'method');
		if ($shippingMethod) {
			$this->_data['shipping_method'] = $shippingMethod;
		}

		// pre-formated 'full address' mappable field to pass to providers like mailchimp
		$this->_data['OrderSubscription_BillingAddress'] = array(
			'addr1' => $this->_data['ordbillstreet1'],
			'addr2' => $this->_data['ordbillstreet2'],
			'city' => $this->_data['ordbillsuburb'],
			'state' => $this->_data['ordbillstate'],
			'zip' => $this->_data['ordbillzip'],
			'country' => $this->_data['ordbillcountrycode'],
		);

		// country-code specific fields to pass to providers like MailChimp or IEM that support (or require in IEM's case) country codes
		$this->_data['OrderSubscription_BillingAddress_countryiso2'] = $this->_data['ordbillcountrycode'];
		$this->_data['OrderSubscription_BillingAddress_countryiso3'] = GetCountryISO3ById($this->_data['ordbillcountryid']);

		// for email integration, we prefer sending the value of an order as the total amount rather than the stored (charged) total - which could be less than the value due to store credit or gift certificates
		// so, generate some columns which are internal to this subscription data and map to those instead of total_ex and total_inc
		$this->_data['total_ex_tax'] = $this->_data['subtotal_ex_tax'] + $this->_data['shipping_cost_ex_tax'] + $this->_data['handling_cost_ex_tax'] + $this->_data['wrapping_cost_ex_tax'];
		$this->_data['total_inc_tax'] = $this->_data['subtotal_inc_tax'] + $this->_data['shipping_cost_inc_tax'] + $this->_data['handling_cost_inc_tax'] + $this->_data['wrapping_cost_inc_tax'];

		// generated fields: end

		// currency values must be stored in the subscription data as both numeric and formatted so that, when translated to the mail provider, it can be sent as either a number or string depending on the destination field
		$moneyFields = array(
			'subtotal_ex_tax',
			'subtotal_inc_tax',
			'subtotal_tax',
			'total_ex_tax',
			'total_inc_tax',
			'total_tax',
			'shipping_cost_ex_tax',
			'shipping_cost_inc_tax',
			'shipping_cost_tax',
			'handling_cost_ex_tax',
			'handling_cost_inc_tax',
			'handling_cost_tax',
			'wrapping_cost_ex_tax',
			'wrapping_cost_inc_tax',
			'wrapping_cost_tax',
			'ordrefundedamount',
			'ordstorecreditamount',
			'ordgiftcertificateamount',
			'orddiscountamount',
			'coupon_discount',
		);

		foreach ($moneyFields as $moneyFieldId) {
			$this->_data[$moneyFieldId] = array(
				'numeric' => $this->_data[$moneyFieldId],
				'formatted' => FormatPriceInCurrency($this->_data[$moneyFieldId], $this->_data['orddefaultcurrencyid']),
			);
		}

		$set = new ISC_NESTEDSET_CATEGORIES;

		// instead of storing full product information, just store the data pertinent to integration rules
		foreach ($this->_data['products'] as $product) {
			$this->_products[] = $product['productid'];
			$this->_brands[] = $product['prodbrandid'];

			if ($product['prodcatids']) {
				foreach (explode(',', $product['prodcatids']) as $categoryId) {
					$this->_categories[] = $categoryId;

					// also include parent categories to trigger rules related to them
					$parents = $set->getParentPath(array('categoryid'), (int)$categoryId);
					foreach ($parents as $parentCategory) {
						$this->_categories[] = $parentCategory['categoryid'];
					}
				}
			}
		}

		$this->_products = array_unique($this->_products);
		$this->_brands = array_unique($this->_brands);
		$this->_categories = array_unique($this->_categories);

		sort($this->_products);
		sort($this->_brands);
		sort($this->_categories);

		// for now, don't need to store these - may need to store products when this is changed to supply ecommerce info
		unset($this->_data['customer']);
		unset($this->_data['products']);
	}
 /**
  * Build the contents for the order confirmation page. This function sets up everything to be used by
  * the order confirmation on the express checkout page as well as the ConfirmOrder page when using a
  * multi step checkout.
  */
 public function BuildOrderConfirmation()
 {
     if (!GetConfig('ShowMailingListInvite')) {
         $GLOBALS['HideMailingListInvite'] = 'none';
     }
     // Do we need to show the special offers & discounts checkbox and should they
     // either of the newsletter checkboxes be ticked by default?
     if (GetConfig('MailAutomaticallyTickNewsletterBox')) {
         $GLOBALS['NewsletterBoxIsTicked'] = 'checked="checked"';
     }
     // Is Interspire Email Marketer integrated?
     if (GetConfig('MailXMLAPIValid') && GetConfig('UseMailerForOrders') && GetConfig('MailOrderList') > 0) {
         // Yes, should we tick the speical offers & discounts checkbox by default?
         if (GetConfig('MailAutomaticallyTickOrderBox')) {
             $GLOBALS['OrderBoxIsTicked'] = 'checked="checked"';
         }
     } else {
         $GLOBALS['HideOrderCheckBox'] = "none";
     }
     if (isset($_REQUEST['ordercomments'])) {
         $GLOBALS['OrderComments'] = $_REQUEST['ordercomments'];
     }
     // Now we check if we have an incoming coupon or gift certificate code to apply
     if (isset($_REQUEST['couponcode']) && $_REQUEST['couponcode'] != '') {
         $code = trim($_REQUEST['couponcode']);
         // Were we passed a gift certificate code?
         if (isc_strlen($code) == GIFT_CERTIFICATE_LENGTH && gzte11(ISC_LARGEPRINT)) {
             $cart = GetClass('ISC_CART');
             if ($cart->api->ApplyGiftCertificate($code)) {
                 // If successful show a message
                 $GLOBALS['CheckoutSuccessMsg'] = GetLang('GiftCertificateAppliedToCart');
             } else {
                 $GLOBALS['CheckoutErrorMsg'] = implode('<br />', $cart->api->GetErrors());
             }
         } else {
             $cart = GetClass('ISC_CART');
             if ($cart->api->ApplyCoupon($code)) {
                 $this->api->ReapplyCouponsFromCart();
                 //Added by Simha temp fix to avoid having multiple times coupon for same item
                 $GLOBALS['ISC_CLASS_CART']->api->UpdateCartInformation();
                 // Coupon code applied successfully
                 $GLOBALS['CheckoutSuccessMsg'] = GetLang('CouponAppliedToCart');
             } else {
                 $GLOBALS['CheckoutErrorMsg'] = implode('<br />', $cart->api->GetErrors());
             }
         }
     }
     $GLOBALS['ISC_CLASS_ACCOUNT'] = GetClass('ISC_ACCOUNT');
     // Determine what we'll be showing for the redeem gift certificate/coupon code box
     if (gzte11(ISC_LARGEPRINT)) {
         $GLOBALS['RedeemTitle'] = GetLang('RedeemGiftCertificateOrCoupon');
         $GLOBALS['RedeemIntro'] = GetLang('RedeemGiftCertificateorCouponIntro');
     } else {
         $GLOBALS['RedeemTitle'] = GetLang('RedeemCouponCode');
         $GLOBALS['RedeemIntro'] = GetLang('RedeemCouponCodeIntro');
     }
     $GLOBALS['HideCheckoutError'] = "none";
     $GLOBALS['HidePaymentOptions'] = "";
     $GLOBALS['HideUseCoupon'] = '';
     // if the provider list html is set in session then use it as the payment provider options.
     // it's normally set in payment modules when it's required.
     if (isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
         $GLOBALS['HidePaymentProviderList'] = "";
         $GLOBALS['HidePaymentOptions'] = "";
         $GLOBALS['PaymentProviders'] = $_SESSION['CHECKOUT']['ProviderListHTML'];
         $GLOBALS['StoreCreditPaymentProviders'] = $_SESSION['CHECKOUT']['ProviderListHTML'];
         $GLOBALS['CheckoutWith'] = "";
     } else {
         // Get a list of checkout providers
         $checkoutProviders = GetCheckoutModulesThatCustomerHasAccessTo(true);
         // If no checkout providers are set up, send an email to the store owner and show an error message
         if (empty($checkoutProviders)) {
             $GLOBALS['HideConfirmOrderPage'] = "none";
             $GLOBALS['HideCheckoutError'] = '';
             $GLOBALS['HideTopPaymentButton'] = "none";
             $GLOBALS['HidePaymentProviderList'] = "none";
             $GLOBALS['CheckoutErrorMsg'] = GetLang('NoCheckoutProviders');
             $GLOBALS['NoCheckoutProvidersError'] = sprintf(GetLang("NoCheckoutProvidersErrorLong"), $GLOBALS['ShopPath']);
             $GLOBALS['EmailHeader'] = GetLang("NoCheckoutProvidersSubject");
             $GLOBALS['EmailMessage'] = sprintf(GetLang("NoCheckoutProvidersErrorLong"), $GLOBALS['ShopPath']);
             $emailTemplate = FetchEmailTemplateParser();
             $emailTemplate->SetTemplate("general_email");
             $message = $emailTemplate->ParseTemplate(true);
             require_once ISC_BASE_PATH . "/lib/email.php";
             $obj_email = GetEmailClass();
             $obj_email->Set('CharSet', GetConfig('CharacterSet'));
             $obj_email->From(GetConfig('OrderEmail'), GetConfig('StoreName'));
             $obj_email->Set("Subject", GetLang("NoCheckoutProvidersSubject"));
             $obj_email->AddBody("html", $message);
             $obj_email->AddRecipient(GetConfig('AdminEmail'), "", "h");
             $email_result = $obj_email->Send();
         } else {
             if (count($checkoutProviders) > 1) {
                 $GLOBALS['HideTopPaymentButton'] = "none";
                 $GLOBALS['HideCheckoutError'] = "none";
             } else {
                 $GLOBALS['HidePaymentProviderList'] = "none";
                 $GLOBALS['HideCheckoutError'] = "none";
                 $GLOBALS['HidePaymentOptions'] = "none";
                 list(, $provider) = each($checkoutProviders);
                 if (method_exists($provider['object'], 'ShowPaymentForm') && !isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
                     $GLOBALS['ExpressCheckoutLoadPaymentForm'] = 'ExpressCheckout.ShowSingleMethodPaymentForm();';
                 }
                 if ($provider['object']->GetPaymentType() == PAYMENT_PROVIDER_OFFLINE) {
                     $GLOBALS['PaymentButtonSwitch'] = "ShowContinueButton();";
                 }
                 $GLOBALS['CheckoutWith'] = $provider['object']->GetDisplayName();
             }
         }
         // Build the list of payment provider options
         $GLOBALS['PaymentProviders'] = $GLOBALS['StoreCreditPaymentProviders'] = "";
         foreach ($checkoutProviders as $provider) {
             $GLOBALS['ProviderChecked'] = '';
             if (count($checkoutProviders) == 1) {
                 $GLOBALS['ProviderChecked'] = 'checked="checked"';
             }
             $GLOBALS['ProviderId'] = $provider['object']->GetId();
             $GLOBALS['ProviderName'] = isc_html_escape($provider['object']->GetDisplayName());
             $GLOBALS['ProviderType'] = $provider['object']->GetPaymentType("text");
             if (method_exists($provider['object'], 'ShowPaymentForm')) {
                 $GLOBALS['ProviderPaymentFormClass'] = 'ProviderHasPaymentForm';
             } else {
                 $GLOBALS['ProviderPaymentFormClass'] = '';
             }
             $GLOBALS['PaymentFieldPrefix'] = '';
             $GLOBALS['PaymentProviders'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CheckoutProviderOption");
             $GLOBALS['PaymentFieldPrefix'] = 'credit_';
             $GLOBALS['StoreCreditPaymentProviders'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CheckoutProviderOption");
         }
     }
     // Are we coming back to this page for a particular reason?
     if (isset($_SESSION['REDIRECT_TO_CONFIRMATION_MSG'])) {
         $GLOBALS['HideCheckoutError'] = '';
         $GLOBALS['CheckoutErrorMsg'] = $_SESSION['REDIRECT_TO_CONFIRMATION_MSG'];
         unset($_SESSION['REDIRECT_TO_CONFIRMATION_MSG']);
     }
     // Get a summary of the order
     $orderSummary = $this->CalculateOrderSummary();
     // Start building the summary of all of the items in the order
     $GLOBALS['SNIPPETS']['CartItems'] = '';
     foreach ($orderSummary['products'] as $cartKey => $product) {
         $GLOBALS['ProductQuantity'] = $product['quantity'];
         $GLOBALS['ProductPrice'] = CurrencyConvertFormatPrice($product['price']);
         $GLOBALS['ProductTotal'] = CurrencyConvertFormatPrice($product['total']);
         // If the item in the cart is a gift certificate, we need to show a special type of row
         if (isset($product['type']) && $product['type'] == "giftcertificate") {
             $GLOBALS['GiftCertificateName'] = isc_html_escape($product['data']['prodname']);
             $GLOBALS['GiftCertificateTo'] = isc_html_escape($product['certificate']['to_name']);
             $GLOBALS['SNIPPETS']['CartItems'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CheckoutCartItemGiftCertificate");
         } else {
             $GLOBALS['ProductAvailability'] = isc_html_escape($product['data']['prodavailability']);
             $GLOBALS['ItemId'] = $product['data']['productid'];
             // If this is a discounted price (from a coupon) override the product price to the was/now version
             if (isset($product['discount_price']) && $product['discount_price'] != $product['original_price']) {
                 $GLOBALS['ProductPrice'] = sprintf("<s class='CartStrike'>%s</s> %s", CurrencyConvertFormatPrice($product['original_price']), CurrencyConvertFormatPrice($product['price']));
             }
             // Is this product a variation?
             $GLOBALS['ProductOptions'] = '';
             if (isset($product['options']) && !empty($product['options'])) {
                 $GLOBALS['ProductOptions'] .= "<br /><small>(";
                 $comma = '';
                 foreach ($product['options'] as $name => $value) {
                     if (!trim($name) || !trim($value)) {
                         continue;
                     }
                     $GLOBALS['ProductOptions'] .= $comma . isc_html_escape($name) . ": " . isc_html_escape($value);
                     $comma = ', ';
                 }
                 $GLOBALS['ProductOptions'] .= ")</small>";
             }
             $GLOBALS['EventDate'] = '';
             if (isset($product['event_date'])) {
                 $GLOBALS['EventDate'] = '<div style="font-style: italic; font-size:11px; padding-left:10px">' . $product['event_name'] . ': ' . isc_date('M jS Y', $product['event_date']) . '</div>';
             }
             $GLOBALS['HideGiftWrapping'] = 'display: none';
             $GLOBALS['HideGiftMessagePreview'] = 'display: none';
             $GLOBALS['GiftWrappingName'] = '';
             $GLOBALS['GiftMessagePreview'] = '';
             if (isset($product['wrapping_name'])) {
                 $GLOBALS['HideGiftWrapping'] = '';
                 $GLOBALS['GiftWrappingName'] = isc_html_escape($product['wrapping_name']);
                 if (isset($product['wrapping_message'])) {
                     if (isc_strlen($product['wrapping_message']) > 30) {
                         $product['wrapping_message'] = substr($product['wrapping_message'], 0, 27) . '...';
                     }
                     $GLOBALS['GiftMessagePreview'] = isc_html_escape($product['wrapping_message']);
                     if ($product['wrapping_message']) {
                         $GLOBALS['HideGiftMessagePreview'] = '';
                     }
                 }
             }
             //create configurable product fields on order confirmation page with the data posted from add to cart page
             $GLOBALS['CartProductFields'] = '';
             if (isset($product['productFields'])) {
                 require_once ISC_BASE_PATH . '/includes/display/CartContent.php';
                 ISC_CARTCONTENT_PANEL::GetProductFieldDetails($product['productFields'], $cartKey);
             }
             $GLOBALS['ProductName'] = isc_html_escape($product['data']['prodname']);
             $GLOBALS['SNIPPETS']['CartItems'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CheckoutCartItem");
         }
     }
     // Do we have a shipping price to show?
     if ($orderSummary['digitalOrder'] == 0) {
         $GLOBALS['ShippingCost'] = CurrencyConvertFormatPrice($orderSummary['shippingCost']);
         $GLOBALS['ShippingMethod'] = sprintf("%s %s %s", isc_html_escape($orderSummary['shippingProvider']), GetLang('For'), $GLOBALS['ShippingCost']);
         $GLOBALS['HideShoppingCartShippingCost'] = '';
         $GLOBALS['ShippingProvider'] = isc_html_escape($orderSummary['shippingProvider']);
         if (count($orderSummary['shippingAddresses']) == 1) {
             $address = current($orderSummary['shippingAddresses']);
             $GLOBALS['ShippingAddress'] = $GLOBALS['ISC_CLASS_ACCOUNT']->FormatShippingAddress($address);
         } else {
             if (count($orderSummary['shippingAddresses']) > 1) {
                 $GLOBALS['ShippingAddress'] = '<em>(Order will be shipped to multiple addresses)</em>';
             } else {
                 $GLOBALS['ShippingAddress'] = GetLang('NA');
             }
         }
         // Show the shipping details
         $GLOBALS['HideShippingDetails'] = '';
     } else {
         $GLOBALS['HideShippingDetails'] = 'display: none';
         $GLOBALS['HideShoppingCartShippingCost'] = 'none';
         $GLOBALS['ShippingAddress'] = GetLang('NotRequiredForDigitalDownloads');
         $GLOBALS['ShippingMethod'] = GetLang('ShippingImmediateDownload');
     }
     if (isset($orderSummary['billingAddressId'])) {
         $GLOBALS['BillingAddress'] = $GLOBALS['ISC_CLASS_ACCOUNT']->GetAndFormatShippingAddressById($orderSummary['billingAddressId']);
     } else {
         $GLOBALS['BillingAddress'] = $GLOBALS['ISC_CLASS_ACCOUNT']->FormatShippingAddress($orderSummary['billingAddress']);
     }
     // Do we have a handling cost to show?
     if (isset($orderSummary['handlingCost']) && $orderSummary['handlingCost'] > 0) {
         $GLOBALS['HandlingCost'] = CurrencyConvertFormatPrice($orderSummary['handlingCost']);
     } else {
         $GLOBALS['HideShoppingCartHandlingCost'] = 'none';
     }
     // Format the item total
     $GLOBALS['ItemTotal'] = CurrencyConvertFormatPrice($orderSummary['itemTotal']);
     if ($orderSummary['wrappingCost'] > 0) {
         $GLOBALS['GiftWrappingTotal'] = CurrencyConvertFormatPrice($orderSummary['wrappingCost']);
     } else {
         $GLOBALS['HideGiftWrappingTotal'] = 'display: none';
     }
     // Hide everything related to tax by default
     $GLOBALS['HideShoppingCartTaxCost'] = "none";
     $GLOBALS['HideShoppingCartIncludedTaxCost'] = "none";
     // Do we have any tax we need to show?
     if ($orderSummary['taxCost'] > 0) {
         $taxLines = "";
         $taxLang = "";
         if ($orderSummary['taxIncluded']) {
             $taxLang = "Included";
         }
         // get the taxes from the addresses and merge them if they are from the same tax rate
         $taxes = array();
         foreach ($orderSummary['vendors'] as $vendorId => $addresses) {
             foreach ($addresses as $addressId => $addressInfo) {
                 $taxId = $addressInfo['taxId'];
                 if (isset($taxes[$taxId])) {
                     $taxes[$taxId]['taxCost'] += $addressInfo['taxCost'];
                 } else {
                     $taxes[$taxId] = array('taxName' => $addressInfo['taxName'], 'taxCost' => $addressInfo['taxCost'], 'taxRate' => $addressInfo['taxRate']);
                 }
             }
         }
         $GLOBALS['SNIPPETS']['TaxLines'] = "";
         // generate lines for each tax rate
         foreach ($taxes as $taxId => $tax) {
             $GLOBALS['TaxName'] = isc_html_escape(sprintf(GetLang($taxLang . 'TaxLine'), $tax['taxName'], $tax['taxRate'] / 1));
             $GLOBALS['TaxCost'] = CurrencyConvertFormatPrice($tax['taxCost']);
             $taxLines .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CheckoutTaxLine");
         }
         // if more than one tax rate is used, display a total line
         if (count($taxes) > 1) {
             $GLOBALS['TaxName'] = isc_html_escape(GetLang($taxLang . 'TotalTax'));
             $GLOBALS['TaxCost'] = CurrencyConvertFormatPrice($orderSummary['taxCost']);
             $taxLines .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CheckoutTaxLine");
         }
         $GLOBALS['SNIPPETS']['TaxLines'] = "";
         $GLOBALS['SNIPPETS']['IncludedTax'] = "";
         // are we displaying the tax before the total or after as included tax?
         if ($orderSummary['taxIncluded']) {
             $GLOBALS['SNIPPETS']['IncludedTax'] = $taxLines;
         } else {
             $GLOBALS['SNIPPETS']['TaxLines'] = $taxLines;
         }
     }
     // Format the grand total of the order
     $GLOBALS['TotalCost'] = CurrencyConvertFormatPrice($orderSummary['total']);
     $GLOBALS['HideAdjustedTotal'] = "none";
     $GLOBALS['SNIPPETS']['GiftCertificates'] = '';
     if ($orderSummary['adjustedTotal'] != $orderSummary['total']) {
         $GLOBALS['HideAdjustedTotal'] = '';
         $GLOBALS['AdjustedTotalCost'] = $orderSummary['adjustedTotal'];
     }
     $GLOBALS['SNIPPETS']['Coupons'] = '';
     if (count($orderSummary['coupons'])) {
         foreach ($orderSummary['coupons'] as $coupon) {
             $GLOBALS['CouponId'] = $coupon['couponid'];
             $GLOBALS['CouponCode'] = $coupon['couponcode'];
             // percent coupon
             if ($coupon['coupontype'] == 1) {
                 $discount = $coupon['discount'] . "%";
             } else {
                 $discount = CurrencyConvertFormatPrice($coupon['discount']);
             }
             $GLOBALS['CouponDiscount'] = $discount;
             $GLOBALS['SNIPPETS']['Coupons'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("ConfirmOrderCoupon");
         }
     }
     // If we have any gift certificates, list those too
     if (!empty($orderSummary['giftCertificates'])) {
         foreach ($orderSummary['giftCertificates'] as $certificate) {
             $GLOBALS['GiftCertificateCode'] = isc_html_escape($certificate['giftcertcode']);
             $GLOBALS['GiftCertificateId'] = $certificate['giftcertid'];
             $GLOBALS['GiftCertificateBalance'] = CurrencyConvertFormatPrice($certificate['giftcertbalance']);
             $GLOBALS['GiftCertificateRemaining'] = CurrencyConvertFormatPrice($certificate['balanceremaining']);
             $GLOBALS['CertificateAmountUsed'] = CurrencyConvertFormatPrice($certificate['amountused']);
             $GLOBALS['SNIPPETS']['GiftCertificates'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("ConfirmOrderGiftCertificate");
         }
     }
     // If the order total comes to $0.00, then we don't show the payment options and a lot of other things (because they have nothing to pay)
     if ($orderSummary['adjustedTotal'] == 0) {
         $GLOBALS['HidePaymentOptions'] = "none";
         $GLOBALS['HideUseCoupon'] = 'none';
         $GLOBALS['HidePaymentProviderList'] = "none";
         $GLOBALS['PaymentButtonSwitch'] = "ShowContinueButton(); ExpressCheckout.UncheckPaymentProvider();";
     }
     // Does the customer have any store credit they can use?
     $GLOBALS['HideUseStoreCredit'] = "none";
     $GLOBALS['HideRemainingStoreCredit'] = "none";
     $customer = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerDataByToken();
     if ($customer['custstorecredit'] > 0) {
         $GLOBALS['HidePaymentOptions'] = "";
         $GLOBALS['StoreCredit'] = CurrencyConvertFormatPrice($customer['custstorecredit']);
         $GLOBALS['HideUseStoreCredit'] = "";
         $GLOBALS['HidePaymentProviderList'] = "none";
         // The customer has enough store credit to pay for the entirity of this order
         if ($customer['custstorecredit'] >= $orderSummary['adjustedTotal']) {
             $GLOBALS['PaymentButtonSwitch'] = "ShowContinueButton();";
             $GLOBALS['HideLimitedCreditWarning'] = "none";
             $GLOBALS['HideLimitedCreditPaymentOption'] = "none";
             $GLOBALS['HideCreditPaymentMethods'] = "none";
             $GLOBALS['RemainingCredit'] = $customer['custstorecredit'] - $orderSummary['adjustedTotal'];
             if ($GLOBALS['RemainingCredit'] > 0) {
                 $GLOBALS['HideRemainingStoreCredit'] = '';
                 $GLOBALS['RemainingCredit'] = CurrencyConvertFormatPrice($GLOBALS['RemainingCredit']);
             }
         } else {
             $GLOBALS['Remaining'] = CurrencyConvertFormatPrice($orderSummary['adjustedTotal'] - $customer['custstorecredit']);
             if (count($checkoutProviders) == 1) {
                 $GLOBALS['CheckoutStoreCreditWarning'] = sprintf(GetLang('CheckoutStoreCreditWarning2'), $GLOBALS['Remaining'], $GLOBALS['CheckoutWith']);
                 $GLOBALS['HideLimitedCreditPaymentOption'] = "none";
             } else {
                 $GLOBALS['CheckoutStoreCreditWarning'] = GetLang('CheckoutStoreCreditWarning');
             }
             $GLOBALS['ISC_LANG']['CreditPaymentMethod'] = sprintf(GetLang('CreditPaymentMethod'), $GLOBALS['Remaining']);
         }
         if (count($checkoutProviders) > 1) {
             $GLOBALS['CreditAlt'] = GetLang('CheckoutCreditAlt');
         } else {
             if (count($checkoutProviders) <= 1 && isset($GLOBALS['CheckoutWith'])) {
                 $GLOBALS['CreditAlt'] = sprintf(GetLang('CheckoutCreditAltOneMethod'), $GLOBALS['CheckoutWith']);
             } else {
                 if ($customer['custstorecredit'] >= $orderSummary['adjustedTotal']) {
                     $GLOBALS['HideCreditAltOptionList'] = "none";
                     $GLOBALS['HideConfirmOrderPage'] = "";
                     $GLOBALS['HideTopPaymentButton'] = "none";
                     $GLOBALS['HideCheckoutError'] = "none";
                     $GLOBALS['CheckoutErrorMsg'] = '';
                 }
             }
         }
     }
     // Customer has hit this page before. Delete the existing pending order
     // The reason we do a delete is if they're hitting this page again, something
     // has changed with their order or something has become invalid with it along the way.
     if (isset($_COOKIE['SHOP_ORDER_TOKEN']) && IsValidPendingOrderToken($_COOKIE['SHOP_ORDER_TOKEN'])) {
         $query = "\n\t\t\t\tSELECT orderid\n\t\t\t\tFROM [|PREFIX|]orders\n\t\t\t\tWHERE ordtoken='" . $GLOBALS['ISC_CLASS_DB']->Quote($_COOKIE['SHOP_ORDER_TOKEN']) . "' AND ordstatus=0\n\t\t\t";
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         while ($order = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
             $entity = new ISC_ENTITY_ORDER();
             $entity->delete($order['orderid'], false, true);
         }
     }
     // Are we showing an error message?
     if (isset($GLOBALS['CheckoutErrorMsg']) && $GLOBALS['CheckoutErrorMsg'] != '') {
         $GLOBALS['HideCheckoutError'] = '';
     } else {
         $GLOBALS['HideCheckoutError'] = "none";
     }
     // Is there a success message to show?
     if (isset($GLOBALS['CheckoutSuccessMsg']) && $GLOBALS['CheckoutSuccessMsg'] != '') {
         $GLOBALS['HideCheckoutSuccess'] = '';
     } else {
         $GLOBALS['HideCheckoutSuccess'] = "none";
     }
     // Save the information about the pending order in the checkout session, we'll be using it when they visit the next page
     $_SESSION['CHECKOUT']['PENDING_DATA'] = array("ITEM_TOTAL" => $orderSummary['itemTotal'], "TAX_COST" => number_format($orderSummary['taxCost'], GetConfig('DecimalPlaces'), ".", ""), "TAX_INCLUDED" => $orderSummary['taxIncluded'], "ORDER_TOTAL" => number_format($orderSummary['total'] - $GLOBALS['ISC_CLASS_CART']->api->Get('SUBTOTAL_DISCOUNT'), GetConfig('DecimalPlaces'), ".", ""), "GATEWAY_AMOUNT" => number_format($orderSummary['adjustedTotal'], GetConfig('DecimalPlaces'), ".", ""), "GIFTCERTIFICATE_AMOUNT" => number_format($orderSummary['giftCertificateTotal'], GetConfig('DecimalPlaces'), ".", ""));
     // Store information about each vendor in the order
     foreach ($orderSummary['vendors'] as $vendorId => $addressInfo) {
         foreach ($addressInfo as $addressId => $vendorInfo) {
             $_SESSION['CHECKOUT']['PENDING_DATA']['VENDORS'][$vendorId . '_' . $addressId] = array('ITEM_TOTAL' => $vendorInfo['itemTotal'], 'TAX_COST' => number_format($vendorInfo['taxCost'], GetConfig('DecimalPlaces'), ".", ""), 'TAX_RATE' => number_format($vendorInfo['taxRate'], GetConfig('DecimalPlaces'), ".", ""), 'TAX_NAME' => $vendorInfo['taxName'], 'ORDER_TOTAL' => number_format($vendorInfo['total'] - $GLOBALS['ISC_CLASS_CART']->api->Get('SUBTOTAL_DISCOUNT'), GetConfig('DecimalPlaces'), ".", ""));
         }
     }
     // If this is an anonymous checkout, save that
     if (isset($_POST['anonymousCheckout'])) {
         $_SESSION['CHECKOUT']['PENDING_DATA']['GUEST_CHECKOUT'] = 1;
     } else {
         $_SESSION['CHECKOUT']['PENDING_DATA']['GUEST_CHECKOUT'] = 0;
     }
     // Checkout out as a new customer and wishing to create an account, we need to save those details
     if (!CustomerIsSignedIn()) {
         if (isset($_POST['createAccount']) || GetConfig('GuestCheckoutCreateAccounts')) {
             // If we're automatically creating accounts, assign the user a random password
             $autoAccount = 0;
             if (isset($_POST['billing_Password'])) {
                 $password = $_POST['billing_Password'];
             }
             if (!isset($_POST['createAccount']) && GetConfig('GuestCheckoutCreateAccounts')) {
                 $password = substr(md5(uniqid(true)), 0, 8);
                 $autoAccount = 1;
             }
             if (!isset($_SESSION['CHECKOUT']['CREATE_ACCOUNT']) && isset($_POST['billing_EmailAddress'])) {
                 $_SESSION['CHECKOUT']['CREATE_ACCOUNT'] = 1;
                 $_SESSION['CHECKOUT']['ACCOUNT_DETAILS'] = array('email' => $_POST['billing_EmailAddress'], 'password' => $password, 'firstname' => $_POST['billing_FirstName'], 'lastname' => $_POST['billing_LastName'], 'company' => $_POST['billing_CompanyName'], 'phone' => $_POST['billing_Phone'], 'autoAccount' => $autoAccount);
             }
         } else {
             unset($_SESSION['CHECKOUT']['CREATE_ACCOUNT']);
             unset($_SESSION['CHECKOUT']['ACCOUNT_DETAILS']);
         }
     } else {
         unset($_SESSION['CHECKOUT']['CREATE_ACCOUNT']);
         unset($_SESSION['CHECKOUT']['ACCOUNT_DETAILS']);
     }
     if (GetConfig('EnableOrderComments') == 1) {
         $GLOBALS['HideOrderComments'] = "";
     } else {
         $GLOBALS['HideOrderComments'] = "none";
     }
     if ($GLOBALS['ISC_CLASS_CART']->api->Get('SUBTOTAL_DISCOUNT') == 0) {
         $GLOBALS['HideOrderDiscount'] = "display : none";
     } else {
         $GLOBALS['OrderDiscount'] = CurrencyConvertFormatPrice($GLOBALS['ISC_CLASS_CART']->api->Get('SUBTOTAL_DISCOUNT'));
         $GLOBALS['HideOrderDiscount'] = "";
     }
     if (GetConfig('EnableOrderTermsAndConditions') == 1) {
         $GLOBALS['HideOrderTermsAndConditions'] = "";
         if (GetConfig('OrderTermsAndConditionsType') == "link") {
             $GLOBALS['AgreeTermsAndConditions'] = GetLang('YesIAgree');
             $GLOBALS['TermsAndConditionsLink'] = "<a href='" . GetConfig('OrderTermsAndConditionsLink') . "' target='_BLANK'>" . strtolower(GetLang('TermsAndConditions')) . "</a>.";
             $GLOBALS['HideTermsAndConditionsTextarea'] = "display:none;";
         } else {
             $GLOBALS['HideTermsAndConditionsTextarea'] = '';
             $GLOBALS['OrderTermsAndConditions'] = GetConfig('OrderTermsAndConditions');
             $GLOBALS['AgreeTermsAndConditions'] = GetLang('AgreeTermsAndConditions');
             $GLOBALS['TermsAndConditionsLink'] = '';
         }
     } else {
         $GLOBALS['HideOrderTermsAndConditions'] = "display:none;";
     }
     $GLOBALS['AdjustedTotalCost'] = CurrencyConvertFormatPrice($orderSummary['adjustedTotal']);
 }