예제 #1
0
 /**
  * Actually create a customer account in the database.
  *
  * @param array An array of details about the customer.
  * @param boolean True if a welcome email should be sent out to the customer.
  * @param boolean True if this account is being created invisibily for the customer via the checkout.
  * @return int The customer ID if successful.
  */
 public function CreateCustomerAccount($Customer, $Email = true, $checkoutAccount = false)
 {
     /**
      * If we are successful then save all the non-private custom fields. Only if we
      * are NOT a single page checkout account
      */
     if (!isset($_SESSION['CHECKOUT']['CREATE_ACCOUNT']) || GetConfig('CheckoutType') !== 'single') {
         $accountFormSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT);
         if (isId($accountFormSessionId)) {
             $Customer['custformsessionid'] = $accountFormSessionId;
         }
         if (isset($Customer['shipping_address'])) {
             $shippingFormSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ADDRESS);
             if (isId($shippingFormSessionId)) {
                 $Customer['shipping_address']['shipformsessionid'] = $shippingFormSessionId;
             }
         }
     }
     $entity = new ISC_ENTITY_CUSTOMER();
     $customerId = $entity->add($Customer);
     if (!isId($customerId)) {
         return;
     }
     // Do we want to email this custome a copy of their registration details?
     if ($Email == true) {
         $emailTemplate = FetchEmailTemplateParser();
         $GLOBALS['FirstName'] = isc_html_escape($Customer['firstname']);
         $GLOBALS['Email'] = isc_html_escape($Customer['email']);
         $GLOBALS['Password'] = isc_html_escape($Customer['password']);
         if ($checkoutAccount) {
             $GLOBALS['ISC_LANG']['ThanksForRegisteringAtIntro'] = sprintf(GetLang('CheckoutAccountCreatedIntro'), $GLOBALS['StoreName']);
             $subject = GetLang('CheckoutAccountCreatedSubject');
             $GLOBALS['ISC_LANG']['THanksForRegisteringAt'] = GetLang('CheckoutAccountCreatedSubject');
         } else {
             $GLOBALS['ISC_LANG']['ThanksForRegisteringAtIntro'] = sprintf(GetLang('ThanksForRegisteringAtIntro'), $GLOBALS['StoreName']);
             $subject = GetLang('ThanksForRegisteringAt');
         }
         $GLOBALS['ISC_LANG']['ThanksForRegisteringEmailLogin'] = sprintf(GetLang('ThanksForRegisteringEmailLogin'), $GLOBALS['ShopPathSSL'] . "/account.php", $GLOBALS['ShopPathSSL'] . "/account.php", $GLOBALS['ShopPathSSL'] . "/account.php");
         $emailTemplate->SetTemplate("createaccount_email");
         $message = $emailTemplate->ParseTemplate(true);
         // Create a new email API object to send the email
         $store_name = GetConfig('StoreName');
         require_once ISC_BASE_PATH . "/lib/email.php";
         $obj_email = GetEmailClass();
         $obj_email->Set('CharSet', GetConfig('CharacterSet'));
         $obj_email->From(GetConfig('OrderEmail'), $store_name);
         $obj_email->Set("Subject", $subject . $store_name);
         $obj_email->AddBody("html", $message);
         $obj_email->AddRecipient($Customer['email'], "", "h");
         $email_result = $obj_email->Send();
     }
     return $customerId;
 }
예제 #2
0
	public function __construct($customerId = null)
	{
		// use the same settings as orders by default
		$this->setDoubleOptIn(GetConfig('EmailIntegrationOrderDoubleOptin'));
		$this->setSendWelcome(GetConfig('EmailIntegrationOrderSendWelcome'));

		if (!$customerId) {
			return;
		}

		$entity = new ISC_ENTITY_CUSTOMER();

		$data = $entity->get($customerId);
		if (!$data) {
			throw new Interspire_EmailIntegration_Subscription_Exception();
		}

		unset($data['custpassword']);

		$this->_data = $data;
		unset($data);

		$this->setSubscriptionIP($this->_data['custregipaddress']);

		// customer custom form fields

		/** @var ISC_FORM */
		$form = $GLOBALS["ISC_CLASS_FORM"];

		// populate empty form fields as a starting point -- this makes exports of imported customers work OK because they may not have a custformsessionid, or this ensures that export data is current with configured form fields even if the stored form fields are out of date
		$formFields = $form->getFormFields(FORMFIELDS_FORM_ACCOUNT);
		foreach ($formFields as /** @var ISC_FORMFIELD_BASE */$formField) {
			if ($formField->getFieldPrivateId()) {
				continue;
			}
			$this->_data[$formField->getFieldId()] = '';
		}

		// load saved data for this customer
		if (isId($this->_data['custformsessionid'])) {
			$customFields = $form->getSavedSessionData($this->_data['custformsessionid']);
			foreach ($customFields as $fieldId => $value) {
				$this->_data['FormField_' . $fieldId] = $value;
			}
		}

		// for email integration purposes, money values must be stored in an array as both numeric and formatted to allow for translation to both number fields and text fields, while maintaining currency information
		SetupCurrency();
		$moneyFields = array('custstorecredit');
		foreach ($moneyFields as $moneyFieldId) {
			$this->_data[$moneyFieldId] = array(
				'numeric' => $this->_data[$moneyFieldId],
				'formatted' => FormatPriceInCurrency($this->_data[$moneyFieldId]),
			);
		}

		unset($this->_data['addresses']); // the addresses provided by entity class are mixed billing/shipping addresses, can't be sure so discard them
		// find last used _billing_ address for this customer by non-deleted orders
		$order = $GLOBALS['ISC_CLASS_DB']->FetchRow("SELECT ordformsessionid, ordbillstreet1, ordbillstreet2, ordbillsuburb, ordbillstate, ordbillzip, ordbillcountryid FROM `[|PREFIX|]orders` WHERE ordcustid = " . (int)$customerId . " AND deleted = 0 ORDER BY orddate DESC LIMIT 1");
		if (is_array($order)) {
			// create fields specifically for email integration based on customer data

			if (isId($order['ordformsessionid'])) {
				$customFields = $form->getSavedSessionData($order['ordformsessionid']);
				foreach ($customFields as $fieldId => $value) {
					$this->_data['CustomerSubscription_Address_FormField_' . $fieldId] = $value;
				}
			}

			$this->_data['CustomerSubscription_Address'] = array(
				'addr1' => $order['ordbillstreet1'],
				'addr2' => $order['ordbillstreet2'],
				'city' => $order['ordbillsuburb'],
				'state' => $order['ordbillstate'],
				'zip' => $order['ordbillzip'],
				'country' => GetCountryById($order['ordbillcountryid']),
				'countryiso2' => GetCountryISO2ById($order['ordbillcountryid']),
				'countryiso3' => GetCountryISO3ById($order['ordbillcountryid']),
			);

			$this->_data['CustomerSubscription_Address_address1'] = $this->_data['CustomerSubscription_Address']['addr1'];
			$this->_data['CustomerSubscription_Address_address2'] = $this->_data['CustomerSubscription_Address']['addr2'];
			$this->_data['CustomerSubscription_Address_city'] = $this->_data['CustomerSubscription_Address']['city'];
			$this->_data['CustomerSubscription_Address_state'] = $this->_data['CustomerSubscription_Address']['state'];
			$this->_data['CustomerSubscription_Address_zip'] = $this->_data['CustomerSubscription_Address']['zip'];
			$this->_data['CustomerSubscription_Address_country'] = $this->_data['CustomerSubscription_Address']['country'];
			$this->_data['CustomerSubscription_Address_countryiso2'] = $this->_data['CustomerSubscription_Address']['countryiso2'];
			$this->_data['CustomerSubscription_Address_countryiso3'] = $this->_data['CustomerSubscription_Address']['countryiso3'];
		}

		// transform customer group data if available
		if ($this->_data['customergroup']) {
			$this->_data['customergroupid'] = $this->_data['customergroup']['customergroupid'];
			$this->_data['groupname'] = $this->_data['customergroup']['groupname'];
		}
		else
		{
			$this->_data['customergroupid'] = '';
			$this->_data['groupname'] = '';
		}
		unset($this->_data['customergroup']);
	}
예제 #3
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'];
 }
 /**
  * Imports an actual product record in to the database.
  *
  * @param array Array of record data
  */
 protected function _ImportRecord($record)
 {
     if (!$record['custconemail']) {
         $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record']) . " " . GetLang('ImportCustomersMissingEmail');
         return;
     }
     if (!is_email_address($record['custconemail'])) {
         $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record']) . " " . GetLang('ImportCustomersInvalidEmail');
         return;
     }
     $fillin = array('custconcompany', 'custconfirstname', 'custconlastname', 'custconphone');
     foreach ($fillin as $fillkey) {
         if (!isset($record[$fillkey])) {
             $record[$fillkey] = '';
         }
     }
     // Is there an existing customer with the same email?
     $customerId = 0;
     $existingFormSessionId = 0;
     $query = sprintf("select customerid from [|PREFIX|]customers where lower(custconemail)='%s'", $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($record['custconemail'])));
     $result = $GLOBALS["ISC_CLASS_DB"]->Query($query);
     if ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($result)) {
         // Overriding existing products, set the product id
         if (isset($this->ImportSession['OverrideDuplicates']) && $this->ImportSession['OverrideDuplicates'] == 1) {
             $customerId = $row['customerid'];
             $this->ImportSession['Results']['Updates'][] = $record['custconfirstname'] . " " . $record['custconlastname'] . " (" . $record['custconemail'] . ")";
         } else {
             $this->ImportSession['Results']['Duplicates'][] = $record['custconfirstname'] . " " . $record['custconlastname'] . " (" . $record['custconemail'] . ")";
             return;
         }
         if (isId($row['custformsessionid'])) {
             $existingFormSessionId = $row['custformsessionid'];
         }
     }
     $customerData = array('company' => $record['custconcompany'], 'firstname' => $record['custconfirstname'], 'lastname' => $record['custconlastname'], 'email' => $record['custconemail'], 'phone' => $record['custconphone']);
     if (isset($record['custpassword']) && $record['custpassword'] !== '') {
         $customerData['password'] = $record['custpassword'];
     }
     if (isset($record['custstorecredit'])) {
         $customerData['storecredit'] = DefaultPriceFormat($record['custstorecredit']);
     }
     if (isId($customerId)) {
         $customerData['customerid'] = $customerId;
     }
     // Are we placing the customer in a customer group?
     $groupId = 0;
     if (!empty($record['custgroup'])) {
         static $customerGroups;
         $groupName = strtolower($record['custgroup']);
         if (isset($customerGroups[$groupName])) {
             $groupId = $customerGroups[$groupName];
         } else {
             $query = "\n\t\t\t\t\tSELECT customergroupid\n\t\t\t\t\tFROM [|PREFIX|]customer_groups\n\t\t\t\t\tWHERE LOWER(groupname)='" . $GLOBALS['ISC_CLASS_DB']->Quote($groupName) . "'\n\t\t\t\t";
             $groupId = $GLOBALS['ISC_CLASS_DB']->FetchOne($query, 'customergroupid');
             // Customer group doesn't exist, create it
             if (!$groupId) {
                 $newGroup = array('name' => $record['custgroup'], 'discount' => 0, 'isdefault' => 0, 'categoryaccesstype' => 'all');
                 $entity = new ISC_ENTITY_CUSTOMERGROUP();
                 $groupId = $entity->add($newGroup);
             }
             if ($groupId) {
                 $customerGroups[$groupName] = $groupId;
             }
         }
     }
     $customerData['customergroupid'] = $groupId;
     // Do we have a shipping address?
     $shippingData = array();
     if (isset($record['shipfullname']) || isset($record['shipfirstname']) || isset($record['shipaddress1']) || isset($record['shipaddress2']) || isset($record['shipcity']) || isset($record['shipstate']) || isset($record['shipzip']) || isset($record['shipcountry'])) {
         $fillin = array('shipaddress1', 'shipaddress2', 'shipcity', 'shipstate', 'shipzip', 'shipcountry');
         foreach ($fillin as $fillkey) {
             if (!isset($record[$fillkey])) {
                 $record[$fillkey] = '';
             }
         }
         $shippingData['shipfirstname'] = '';
         $shippingData['shiplastname'] = '';
         $shippingData['shipaddress1'] = $record['shipaddress1'];
         $shippingData['shipaddress2'] = $record['shipaddress2'];
         $shippingData['shipcity'] = $record['shipcity'];
         $shippingData['shipstate'] = $record['shipstate'];
         $shippingData['shipzip'] = $record['shipzip'];
         $shippingData['shipcountry'] = $record['shipcountry'];
         $shippingData['shipstateid'] = 0;
         $shippingData['shipcountryid'] = 0;
         $shippingData['shipdestination'] = '';
         // Find the country and state
         $shippingData['shipcountryid'] = (int) GetCountryByName($record['shipcountry']);
         if (!$shippingData['shipcountryid']) {
             $shippingData['shipcountryid'] = (int) GetCountryIdByISO2($record['shipcountry']);
         }
         // Still nothing? 0 for the shipping country ID
         if (!$shippingData['shipcountryid']) {
             $shippingData['shipcountryid'] = 0;
         }
         if (isset($record['shipstate'])) {
             $shippingData['shipstateid'] = GetStateByName($record['shipstate'], $shippingData['shipcountryid']);
         }
         // Still nothing? 0 for the shipping state ID
         if (!$shippingData['shipstateid']) {
             $shippingData['shipstateid'] = 0;
         }
         if (!isset($record['shipfullname']) || $record['shipfullname'] == "") {
             if (isset($record['shipfirstname']) && $record['shipfirstname'] != '') {
                 $shippingData['shipfirstname'] = $record['shipfirstname'];
             } else {
                 $shippingData['shipfirstname'] = $customerData['firstname'];
             }
             if (isset($record['shiplastname']) && $record['shiplastname'] != '') {
                 $shippingData['shiplastname'] = $record['shiplastname'];
             } else {
                 $shippingData['shiplastname'] = $customerData['lastname'];
             }
         }
         if (!isset($record['shipphone']) && isset($record['custconphone'])) {
             $shippingData['shipphone'] = $record['custconphone'];
         } else {
             $shippingData['shipphone'] = $record['shipphone'];
         }
         /**
          * Handle any of the address custom fields that we might have
          */
         if (!empty($this->customFields) && array_key_exists('custom', $record)) {
             $shippingData['shipformsessionid'] = $this->_importCustomFormfields(FORMFIELDS_FORM_ADDRESS, $record['custom']);
             if (!isId($shippingData['shipformsessionid'])) {
                 unset($shippingData['shipformsessionid']);
             }
         }
     }
     /**
      * Handle any of the customer custom fields that we might have
      */
     if (!empty($this->customFields) && array_key_exists('custom', $record)) {
         $formSessionId = $this->_importCustomFormfields(FORMFIELDS_FORM_ACCOUNT, $record['custom'], $existingFormSessionId);
         if (isId($formSessionId)) {
             $customerData['custformsessionid'] = $formSessionId;
         }
     }
     $customerData['is_import'] = true;
     $customerEntity = new ISC_ENTITY_CUSTOMER();
     // New customer, insert in to DB
     if ($customerId == 0) {
         // Set a temporary password, retrievable later via lost password function
         if (!isset($customerData['password']) || $customerData['password'] == '') {
             $customerData['password'] = isc_substr(uniqid(rand(), true), 0, 10);
         }
         $customerData['token'] = GenerateCustomerToken();
         $customerData['shipping_address'] = $shippingData;
         $rtn = $customerEntity->add($customerData);
         ++$this->ImportSession['Results']['SuccessCount'];
     } else {
         if (count($shippingData) > 0) {
             $query = sprintf("select shipid from [|PREFIX|]shipping_addresses where shipcustomerid='%d' and lower(shipaddress1)='%s' and lower(shipaddress2)='%s' and lower(shipcity)='%s' and lower(shipstate)='%s' and lower(shipcountry)='%s'", $GLOBALS['ISC_CLASS_DB']->Quote($customerId), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipaddress1']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipaddress2']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipcity']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipstate']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipcountry']));
             $Result = $GLOBALS['ISC_CLASS_DB']->Query($query);
             $row = $GLOBALS['ISC_CLASS_DB']->Fetch($Result);
             // Address doesn't exist, we insert it
             if (!$row['shipid']) {
                 $customerData['shipping_address'] = $shippingData;
             }
         }
         $rtn = $customerEntity->edit($customerData);
     }
 }
예제 #5
0
 /**
  * UpdateCustomerGroup
  * Update the custgroupid field which is the group that the customer belongs to
  *
  * @return Int 1 on success, 0 on failure
  */
 private function UpdateCustomerGroup()
 {
     if (isset($_REQUEST['customerId']) && isset($_REQUEST['groupId'])) {
         $entity = new ISC_ENTITY_CUSTOMER();
         if ($entity->editGroup($_REQUEST['customerId'], $_REQUEST['groupId'])) {
             print 1;
         } else {
             print 0;
         }
     }
 }
예제 #6
0
 /**
  * Set the default group on all the customers
  *
  * Method will reset the default group on all the customers in the accounting world
  *
  * @access private
  */
 private function setDefaultCustomerGroup($customergroupid)
 {
     if (!isId($customergroupid)) {
         return false;
     }
     /**
      * Ok, now we have to set this customergroup on all the customers that have the default customer group
      */
     $customer = new ISC_ENTITY_CUSTOMER();
     $result = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]customers WHERE custgroupid='0'");
     while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
         $input = $customer->get($row['customerid']);
         $this->createServiceRequest('customer', 'edit', $input, 'customer_edit');
     }
     return true;
 }
예제 #7
0
		protected function displayAddEditOrder($sessionId, $orderId = null)
		{
			$order = null;

			if ($orderId) {
				$order = new ISC_ENTITY_ORDER;
				$order = $order->get($orderId);
				if (!$order) {
					exit;
				}

				$forEditing = true;
				$this->template->assign('editingOrder', $orderId);
				$this->template->assign('addingOrder', false);

				// could be useful
				$this->template->assign('order', $order);
			} else {
				$forEditing = false;
				$this->template->assign('editingOrder', false);
				$this->template->assign('addingOrder', true);
			}

			/** @var ISC_QUOTE */
			$quote = $_SESSION['QUOTE_SESSIONS'][$sessionId];
			$this->template->assign('quote', $quote);

			if ($quote->getCustomerId()) {
				// verify the customer still exists
				$customer = new ISC_ENTITY_CUSTOMER;
				if (!$customer->get($quote->getCustomerId())) {
					FlashMessage(GetLang('OrderCustomerDoesNotExist'), MSG_ERROR);
					$quote->setCustomerId(0);
				}
			}

			$incTax = (getConfig('taxDefaultTaxDisplayCart') == TAX_PRICES_DISPLAY_INCLUSIVE);

			require ISC_BASE_PATH . '/lib/addressvalidation.php';

			$this->engine->printHeader();

			$this->template->assign('quoteSession', $sessionId);
			$this->template->assign('statusList', getOrderStatusList());

			$this->template->assign('subtotal', FormatPrice($quote->getSubTotal($incTax))); // would prefer this as {{ quote.subTotal|formatPrice }} but it relies on $incTax variable parameter

			$this->populateQuoteFormFields($quote);

			$shipItemsTo = 'billing';
			if ($forEditing) {
				if ($quote->getIsSplitShipping()) {
					$shipItemsTo = 'multiple';
				} else {
					$shipItemsTo = 'single';
				}
			}
			$this->template->assign('shipItemsTo', $shipItemsTo);

			$accountCustomerGroups = array();
			if(gzte11(ISC_MEDIUMPRINT)) {
				$query = "
					SELECT customergroupid, groupname
					FROM [|PREFIX|]customer_groups
					ORDER BY groupname
				";
				$result = $this->db->query($query);
				while($group = $this->db->fetch($result)) {
					$accountCustomerGroups[$group['customergroupid']] = $group['groupname'];
				}
				array_unshift($accountCustomerGroups, GetLang('CustomerGroupNotAssoc'));
			}
			$this->template->assign('accountCustomerGroups', $accountCustomerGroups);

			$this->template->assign('itemsTable', $this->generateEditOrderItemsTable($quote));

			if ($forEditing && $quote->getIsSplitShipping()) {
				$this->template->assign('multiShippingTable', $this->renderMultiShippingTable($quote));
			}

			$allowGiftCertificates = gzte11(ISC_LARGEPRINT);
			$this->template->assign('allowGiftCertificates', $allowGiftCertificates);

			$this->template->assign('paymentForm', $this->generateOrderPaymentForm($order));

			$this->template->display('order.form.tpl');
			$this->engine->printFooter();
		}
예제 #8
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'], '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'];
 }
예제 #9
0
 /**
  * Get the order record
  *
  * Method will return the order record
  *
  * @access public
  * @param int $orderId The order ID
  * @return array The order array on success, NULL if no record could be found, FALSE on error
  */
 public function get($orderId)
 {
     if (!isId($orderId)) {
         return false;
     }
     $entity = array();
     $result = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]orders WHERE orderid=" . (int) $orderId);
     if (!($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result))) {
         return null;
     }
     $entity = $row;
     $customer = new ISC_ENTITY_CUSTOMER();
     $entity['customer'] = $customer->get($entity['ordcustid']);
     $product = new ISC_ENTITY_PRODUCT();
     $entity['products'] = array();
     $result = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]order_products WHERE orderorderid=" . (int) $orderId);
     while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
         $entity['products'][] = $product->get($row['ordprodid']);
         $key = count($entity['products']) - 1;
         $entity['products'][$key]['prodorderquantity'] = $row['ordprodqty'];
         $entity['products'][$key]['prodorderamount'] = $row['ordprodcost'];
     }
     return $entity;
 }
예제 #10
0
/**
 * Amongst other things, this class and ACCOUNTING_QUICKBOOKS_SERVICE_ORDERSYNC are the ones used to write orders from the shopping cart into QuickBooks.
 * The ones for the opposite direction (QB->ISC) are service.orderadd.php and ACCOUNTING_QUICKBOOKS_SERVICE_ORDERSYNC.
 * 
 */
	public function buildXML()
	{
		if (isc_strtolower($this->spool["service"]) == "edit" && is_array($this->spoolReferenceData)) {
			$this->writeEscapedElement("TxnID", $this->spoolReferenceData["TxnID"]);
			$this->writeEscapedElement("EditSequence", $this->spoolReferenceData["EditSequence"]);
		}

		if (isId($this->spoolNodeData["ordcustid"])) {
			$customerRef = $this->accounting->getReference("customer", '', '', $this->spoolNodeData["ordcustid"], false);
		} else {
			$searchData = array(
								"OrderID" => $this->spool["nodeId"],
								"FirstName" => $this->spoolNodeData["ordbillfirstname"],
								"LastName" => $this->spoolNodeData["ordbilllastname"]
			);

			$customerRef = $this->accounting->getReference("customerguest", $searchData, '', '', false);
		}

		/**
		 * If this is an edit service and there is no reference EVEN though there is a customer ID in the order record, then the
		 * customer must have been deleted. If this is the case then don't construct the CustomerRef (we can't really)
		 */
		$noCustomerRef = false;
		if (isc_strtolower($this->spool["service"]) == "edit" && isId($this->spoolNodeData["ordcustid"])) {
			$customerAPI = new ISC_ENTITY_CUSTOMER();

			if (!$customerAPI->get($this->spoolNodeData["ordcustid"])) {
				$noCustomerRef = true;
			}
		}

		if (!$noCustomerRef && (!is_array($customerRef) || !isset($customerRef["accountingrefexternalid"]) || trim($customerRef["accountingrefexternalid"]) == '')) {
			throw new QBException("Unable to find customer ListID for order ID: " . $this->spool["nodeId"], $this->spool);
		}

		$this->xmlWriter->startElement("CustomerRef");
		$this->writeEscapedElement("ListID", $customerRef["accountingrefexternalid"]);
		$this->xmlWriter->endElement();

		if (array_key_exists("orddate", $this->spoolNodeData)) {
			$this->writeEscapedElement("TxnDate", date("Y-m-d", $this->spoolNodeData["orddate"]));
		}

		$this->writeEscapedElement("RefNumber", $this->accounting->orderID2QBOrderRefNum($this->spool["nodeId"]));

		/**
		 * The addresses
		 */
		foreach (array("Bill", "Ship") as $addressType) {
			$addressMap = array(
							"firstname" => "firstname",
							"lastname" => "lastname",
							"address1" => "street1",
							"address2" => "street2",
							"city" => "suburb",
							"state" => "state",
							"zip" => "zip",
							"country" => "country"
			);

			$address = array();
			$addressField = "ord" . isc_strtolower($addressType);

			foreach ($addressMap as $ourField => $ordField) {
				/**
				 * JMW - Bandaid that fixes the problem for now. Need to do a cleanup of the city/suburb names throughout the module.
				 */
				if (!array_key_exists($addressField . $ordField, $this->spoolNodeData)) {
					if ($addressField . $ordField != 'ordshipsuburb') {
						continue;
					}
				}
				if ($addressField . $ordField != 'ordshipsuburb') {
					$address["ship" . $ourField] = $this->spoolNodeData[$addressField . $ordField];
				} else {
					$address["ship" . $ourField] = $this->spoolNodeData[$addressField . 'city'];
				}
			}

			if (empty($address)) {
				continue;
			}

			$this->buildAddressBlock($addressType . "Address", $address);
		}

		if (trim($this->spoolNodeData["ordnotes"]) !== '') {
			$this->writeEscapedElement("Memo", $this->spoolNodeData["ordnotes"]);
		}

		/**
		 * Now for the products
		 */
		if (!array_key_exists("products", $this->spoolNodeData) || !is_array($this->spoolNodeData["products"])) {
			throw new QBException("Unable to find products for order ID: " . $this->spool["nodeId"], $this->spool);
		}

		foreach ($this->spoolNodeData["products"] as $product) {

			if (isset($product["prodordvariationid"]) && isId($product["prodordvariationid"])) {
				$prodType = "productvariation";
				$prodId = $product["prodordvariationid"];
			} else {
				$prodType = "product";
				$prodId = $product["productid"];
			}

			$productRef = $this->accounting->getReference($prodType, '', '', $prodId, false);

			if (!is_array($productRef) || !isset($productRef["accountingrefexternalid"]) || trim($productRef["accountingrefexternalid"]) == '') {
				throw new QBException("Unable to find product ListID for order ID: " . $this->spool["nodeId"], array("order" => $this->spool, "product" => $product));
			}

			if ($this->accounting->getValue("orderoption") == "order") {
				$tagName = "SalesOrderLine";
			} else {
				$tagName = "SalesReceiptLine";
			}

			if (isc_strtolower(trim($this->spool["service"])) == "edit") {
				$this->xmlWriter->startElement($tagName . "Mod");
			} else {
				$this->xmlWriter->startElement($tagName . "Add");
			}

			/**
			 * If this is an edit then we need to check for the TxnLineID as well
			 */
			if (isc_strtolower(trim($this->spool["service"])) == "edit") {

				$searchData = array(
									"ListID" => $productRef["accountingrefexternalid"],
									"OrderID" => $this->spool["nodeId"]
				);

				$orderItemRef = $this->accounting->getReference("orderitem", $searchData, '', '', false);

				/**
				 * If there is a reference then it is an existing item, else it is a new one
				 */
				if (is_array($orderItemRef) && isset($orderItemRef["accountingrefexternalid"])) {
					$this->writeEscapedElement("TxnLineID", $orderItemRef["accountingrefexternalid"]);
				} else {
					$this->writeEscapedElement("TxnLineID", "-1");
				}
			}

			$this->xmlWriter->startElement("ItemRef");
			$this->writeEscapedElement("ListID", $productRef["accountingrefexternalid"]);
			$this->xmlWriter->endElement();

			$this->writeEscapedElement("Desc", isc_substr($product["prodname"], 0, 4000));
			$this->writeEscapedElement("Quantity", $product["prodorderquantity"]);
			$this->writeEscapedElement("Amount", number_format($product["prodorderamount"] * $product["prodorderquantity"], 2, ".", ""));

			$this->xmlWriter->endElement();
		}

		/**
		 * Now add in the shipping cost and tax if we have any (add it in regardless)
		 */
		$otherProductMap = array(
								"shipping" => "shipping_cost_ex_tax",
								"tax" => "total_tax",
								"discount" => "coupon_discount",
		);

		foreach ($otherProductMap as $refType => $columnName) {
			if (!array_key_exists($columnName, $this->spoolNodeData) || trim($this->spoolNodeData[$columnName]) == '') {
				$otherProductTotal = 0;
			} else {
				$otherProductTotal = (float)$this->spoolNodeData[$columnName];
				if($refType == 'shipping'){
					$otherProductTotal += (float)$this->spoolNodeData['handling_cost_ex_tax'];
					$otherProductTotal += (float)$this->spoolNodeData['wrapping_cost_ex_tax'];
				}elseif($refType == 'discount'){
					$otherProductTotal -= (float)$this->spoolNodeData['orddiscountamount'];
					$otherProductTotal -= (float)$this->spoolNodeData['coupon_discount'];
					$otherProductTotal -= (float)$this->spoolNodeData['coupon_discount'];
				}
			}

			/**
			 * If casting it to a float cleared it
			 */
			if (trim($otherProductTotal) == '') {
				$otherProductTotal = 0;
			}

			$otherProductListID = $this->accounting->getOtherProductListId($refType);

			if (trim($otherProductListID) == '') {
				throw new QBException("Unable to find " . $refType . " ListID for order ID: " . $this->spool["nodeId"], $this->spool);
			}

			if ($this->accounting->getValue("orderoption") == "order") {
				$tagName = "SalesOrderLine";
			} else {
				$tagName = "SalesReceiptLine";
			}

			if (isc_strtolower(trim($this->spool["service"])) == "edit") {
				$this->xmlWriter->startElement($tagName . "Mod");
			} else {
				$this->xmlWriter->startElement($tagName . "Add");
			}

			/**
			 * Same deal with the products where we have to find the TxnLineID aswell
			 */
			if (isc_strtolower(trim($this->spool["service"])) == "edit") {

				$searchData = array(
									"ListID" => $otherProductListID,
									"OrderID" => $this->spool["nodeId"],
									"Type" => $refType
				);

				$otherProductRef = $this->accounting->getReference("orderitem", $searchData, '', '', false);

				/**
				 * Is there a reference for it?
				 */
				if (is_array($otherProductRef) && isset($otherProductRef["accountingrefexternalid"])) {
					$this->writeEscapedElement("TxnLineID", $otherProductRef["accountingrefexternalid"]);
				} else {
					$this->writeEscapedElement("TxnLineID", "-1");
				}
			}

			$this->xmlWriter->startElement("ItemRef");
			$this->writeEscapedElement("ListID", $otherProductListID);
			$this->xmlWriter->endElement();

			$this->writeEscapedElement("Desc", isc_substr($otherProductRef["accountingrefvalue"]["Name"], 0, 4000));
			$this->writeEscapedElement("Quantity", 1);
			$this->writeEscapedElement("Amount", number_format($otherProductTotal, 2, ".", ""));

			$this->xmlWriter->endElement();
		}

		return $this->buildOutput();
	}
예제 #11
0
 /**
  * Create the pending order in the database with the customers selected payment details, etc.
  *
  * @return array An array containing information about what needs to be done next.
  */
 public function SavePendingOrder()
 {
     $provider = null;
     $verifyPaymentProvider = true;
     $redirectToFinishOrder = false;
     $providerId = '';
     $pendingOrderResult = array();
     if (!isset($_SESSION['CHECKOUT']['PENDING_DATA'])) {
         return false;
     }
     // Did they agree to signup to any mailing lists?
     if (isset($_POST['join_mailing_list'])) {
         ISC_SetCookie("JOIN_MAILING_LIST", 1, time() + 3600 * 24 * 7);
     }
     if (isset($_POST['join_order_list'])) {
         ISC_SetCookie("JOIN_ORDER_LIST", 1, time() + 3600 * 24 * 7);
     }
     $orderTotal = $_SESSION['CHECKOUT']['PENDING_DATA']['ORDER_TOTAL'];
     $giftCertificateAmount = $_SESSION['CHECKOUT']['PENDING_DATA']['GIFTCERTIFICATE_AMOUNT'];
     $gatewayAmount = $_SESSION['CHECKOUT']['PENDING_DATA']['GATEWAY_AMOUNT'];
     $creditUsed = 0;
     $giftCertificates = array();
     // Find out what currency we are using. We'll need this later to display their previous orders in the currency that they have selected
     $selectedCurrency = GetCurrencyById($GLOBALS['CurrentCurrency']);
     if (isset($_SESSION['OFFERCART']['GIFTCERTIFICATES']) && is_array($_SESSION['OFFERCART']['GIFTCERTIFICATES'])) {
         $giftCertificates = $_SESSION['OFFERCART']['GIFTCERTIFICATES'];
         // Now we check that the gift certificates can actually be applied to the order
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
         $badCertificates = array();
         $remainingBalance = 0;
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->GiftCertificatesApplicableToOrder($orderTotal, $giftCertificates, $remainingBalance, $badCertificates);
         // One or more gift certificates were invalid so this order is now invalid
         if (count($badCertificates) > 0) {
             $badCertificatesList = '<strong>' . GetLang('BadGiftCertificates') . '</strong><ul>';
             foreach ($badCertificates as $code => $reason) {
                 if (is_array($reason) && $reason[0] == "expired") {
                     $reason = sprintf(GetLang('BadGiftCertificateExpired'), CDate($reason[1]));
                 } else {
                     $reason = GetLang('BadGiftCertificate' . ucfirst($reason));
                 }
                 $badCertificatesList .= sprintf("<li>%s - %s", isc_html_escape($code), $reason);
             }
             $badCertificatesList .= "</ul>";
             $pendingOrderResult = array('error' => GetLang('OrderContainedInvalidGiftCertificates'), 'errorDetails' => $badCertificatesList);
             return $pendingOrderResult;
         } else {
             if ($orderTotal == $giftCertificateAmount && $remainingBalance > 0) {
                 $pendingOrderResult = array('error' => GetLang('OrderTotalStillRemainingCertificates'));
                 return $pendingOrderResult;
             } else {
                 if ($orderTotal == $giftCertificateAmount) {
                     $providerId = 'giftcertificate';
                     $verifyPaymentProvider = false;
                     $redirectToFinishOrder = true;
                 }
             }
         }
     }
     // If the order total is 0, then we just forward the user on to the "Thank You" page and set the payment provider to ''
     if ($orderTotal == 0) {
         $providerId = '';
         $verifyPaymentProvider = false;
         $redirectToFinishOrder = true;
     }
     if ($verifyPaymentProvider) {
         if (isset($_POST['credit_checkout_provider']) && $_POST['credit_checkout_provider'] != "") {
             $_POST['checkout_provider'] = $_POST['credit_checkout_provider'];
         }
         $selected_provider = "";
         $providers = GetCheckoutModulesThatCustomerHasAccessTo(true);
         // If there's more than one, use the value they've chosen
         if (count($providers) > 1 && isset($_POST['checkout_provider']) || isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
             $selected_provider = $_POST['checkout_provider'];
         } else {
             if (count($providers) == 1) {
                 $selected_provider = $providers[0]['object']->GetId();
                 $_POST['checkout_provider'] = $selected_provider;
             } else {
                 $selected_provider = '';
             }
         }
         if (!isset($_POST['checkout_provider'])) {
             $_POST['checkout_provider'] = '';
         }
         // Are we using our store credit?
         $GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
         $customer = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerDataByToken();
         if (isset($_POST['store_credit']) && $_POST['store_credit'] == 1 && $customer['custstorecredit'] > 0) {
             // User has not chosen a payment provider and can't afford this order using only store credit, throw back as error
             if (!$_POST['checkout_provider'] && $customer['custstorecredit'] < $orderTotal) {
                 return false;
             } else {
                 $onlyCredit = false;
                 $updateExtra = '';
                 // If we're only using store credit
                 $creditToUse = $orderTotal - $giftCertificateAmount;
                 if ($customer['custstorecredit'] >= $creditToUse) {
                     // Set the checkout provider
                     $providerId = 'storecredit';
                     $verifyPaymentProvider = false;
                     $redirectToFinishOrder = true;
                     $creditUsed = $creditToUse;
                     $onlyCredit = true;
                 } else {
                     // Using all of our store credit to pay for this order and we owe more.
                     $creditUsed = $customer['custstorecredit'];
                     $gatewayAmount -= $creditUsed;
                 }
             }
         }
     }
     // Now with round 2, do we still need to verify the payment provider?
     if ($verifyPaymentProvider) {
         // If there's more than one provider and one wasn't selected on the order confirmation screen then there's a problem
         if ((count($providers) == 0 || count($providers) > 1 && !isset($_POST['checkout_provider'])) && !isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
             return false;
         }
         // Is the payment provider selected actually valid?
         if (!GetModuleById('checkout', $provider, $selected_provider)) {
             return false;
         }
         $providerId = $provider->GetId();
     }
     // Load up all of the data for the items in the cart
     $GLOBALS['ISC_CLASS_MAKEAOFFER'] = GetClass('ISC_MAKEAOFFER');
     $cartItems = $GLOBALS['ISC_CLASS_MAKEAOFFER']->api->GetProductsInCart();
     // OK, we're successful down to here - do they want to create an account?
     if (isset($_SESSION['CHECKOUT']['CREATE_ACCOUNT'])) {
         $accountDetails = $_SESSION['CHECKOUT']['ACCOUNT_DETAILS'];
         $token = GenerateCustomerToken();
         $customerData = array('email' => trim($accountDetails['email']), 'password' => $accountDetails['password'], 'firstname' => $accountDetails['firstname'], 'lastname' => $accountDetails['lastname'], 'company' => $accountDetails['company'], 'phone' => $accountDetails['phone'], 'token' => $token);
         //alandy modify.2011-5-20.
         /*$sql="select customerid from [|PREFIX|]customers where custconemail='".$accountDetails['email']."'";
         		$query=$GLOBALS['ISC_CLASS_DB']->Query($sql);
         		while($rs=$GLOBALS['ISC_CLASS_DB']->Fetch($query)){
         		    $GLOBALS['Hasemailflag']="yes";
         		      return array(
         				    'error' => GetLang('AccountInternalError')
         			    );
         			    
         	        }*/
         $cusquery = "SELECT customerid\n\t\t\t\tFROM [|PREFIX|]customers\n\t\t\t\tWHERE isguest = 1 AND LOWER(custconemail)='" . $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($customerData['email'])) . "'";
         $cusresult = $GLOBALS['ISC_CLASS_DB']->Query($cusquery);
         $cusrow = $GLOBALS['ISC_CLASS_DB']->Fetch($cusresult);
         $custId = $cusrow['customerid'];
         if ($custId == '') {
             // 20110613 johnny add ---- add flag for guest user email don't exist
             if ($_SESSION['CHECKOUT']['PENDING_DATA']['GUEST_CHECKOUT']) {
                 $customerData['isguest'] = 1;
             }
             $customerId = $GLOBALS['ISC_CLASS_CUSTOMER']->CreateCustomerAccount($customerData, false, $accountDetails['autoAccount']);
         } else {
             if (!$_SESSION['CHECKOUT']['PENDING_DATA']['GUEST_CHECKOUT']) {
                 $customerId = $GLOBALS['ISC_CLASS_CUSTOMER']->CreateCustomerAccount($customerData, true, $accountDetails['autoAccount']);
                 /* delet already exist guest account
                 			$entity = new ISC_ENTITY_CUSTOMER();
                 			$entity->delete($custId);
                 			*/
             } else {
                 $customerId = $custId;
                 // update guest account in customer table for guest user email exist
                 $GLOBALS['ISC_CLASS_DB']->Query("UPDATE [|PREFIX|]customers SET custconfirstname = '" . $customerData['firstname'] . "', custconlastname = '" . $customerData['lastname'] . "' WHERE customerid = {$customerId}");
             }
         }
         if (!$customerId) {
             return array('error' => GetLang('AccountInternalError'));
         }
         if (!$_SESSION['CHECKOUT']['PENDING_DATA']['GUEST_CHECKOUT']) {
             $GLOBALS['ISC_CLASS_CUSTOMER']->LoginCustomerById($customerId, true);
         }
         unset($_SESSION['CHECKOUT']['CREATE_ACCOUNT']);
         unset($_SESSION['CHECKOUT']['ACCOUNT_DETAILS']);
         // Log the customer in
         @ob_end_clean();
     }
     if (isset($_COOKIE['SHOP_TOKEN'])) {
         $customerToken = $_COOKIE['SHOP_TOKEN'];
     } else {
         $customerToken = '';
     }
     $orderComments = '';
     if (isset($_REQUEST['ordercomments'])) {
         $orderComments = $_REQUEST['ordercomments'];
     }
     $checkoutSession = $_SESSION['CHECKOUT'];
     $pendingData = $checkoutSession['PENDING_DATA'];
     // Get a list of the vendors for all of the items in the cart, and loop through them
     // to build all of the pending orders
     $cartContent = $this->BreakdownCartByAddressVendorforshipping();
     //Changed to merging function by Simha
     $vendorOrderInfo = array();
     foreach ($cartContent as $vendorId => $addresses) {
         foreach ($addresses as $addressId => $products) {
             $allDigital = 1;
             $productArray = array();
             foreach ($products as $cartItemId => $product) {
                 // A physical product, mark as so
                 if ($product['data']['prodtype'] == PT_PHYSICAL) {
                     $allDigital = 0;
                 }
                 // Mark the quantity of this item
                 $productArray[$cartItemId] = $product['quantity'];
             }
             $vendorInfo = $pendingData['VENDORS'][$vendorId . '_' . $addressId];
             $vendorData = array('itemtotal' => $vendorInfo['ITEM_TOTAL'], 'taxcost' => $vendorInfo['TAX_COST'], 'taxname' => $vendorInfo['TAX_NAME'], 'taxrate' => $vendorInfo['TAX_RATE'], 'totalcost' => $vendorInfo['ORDER_TOTAL'], 'shippingcost' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['COST'], 'handlingcost' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['HANDLING'], 'shippingprovider' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['PROVIDER'], 'shippingmodule' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['MODULE'], 'isdigitalorder' => $allDigital, 'products' => $productArray);
             if ($addressId == 0) {
                 $addresses = $this->GetOrderShippingAddresses();
                 $vendorData['shippingaddress'] = $addresses[$addressId];
             } else {
                 $vendorData['shippingaddressid'] = $addressId;
             }
             // Shipping zones can be configured per vendor, so we need to be sure
             // to pass this along correctly too
             if (isset($vendorInfo['SHIPPING_ZONE'])) {
                 $shippingZone = GetShippingZoneById($vendorInfo['SHIPPING_ZONE']);
                 if (is_array($shippingZone)) {
                     $vendorData['ordshippingzoneid'] = $shippingZone['zoneid'];
                     $vendorData['ordshippingzone'] = $shippingZone['zonename'];
                 }
             }
             $vendorOrderInfo[$vendorId . '_' . $addressId] = $vendorData;
         }
     }
     // Set some defaults about the rest of the order
     $pendingOrder = array("customertoken" => $customerToken, 'paymentmethod' => $providerId, "storecreditamount" => $creditUsed, "giftcertificateamount" => $giftCertificateAmount, "giftcertificates" => $giftCertificates, "gatewayamount" => $gatewayAmount, 'totalincludestax' => $pendingData['TAX_INCLUDED'], "currencyid" => $selectedCurrency['currencyid'], "currencyexchangerate" => $selectedCurrency['currencyexchangerate'], 'ordercomments' => $orderComments, 'ipaddress' => GetIP(), 'vendorinfo' => $vendorOrderInfo);
     if (isset($customerId)) {
         $pendingOrder['customerid'] = $customerId;
     }
     // Determine the address ID we're using for billing
     if (is_array($_SESSION['CHECKOUT']['BILLING_ADDRESS'])) {
         $pendingOrder['billingaddress'] = $_SESSION['CHECKOUT']['BILLING_ADDRESS'];
     } else {
         $pendingOrder['billingaddressid'] = (int) $_SESSION['CHECKOUT']['BILLING_ADDRESS'];
     }
     if (isset($_POST['ordermessage'])) {
         $pendingOrder['ordermessage'] = $_POST['ordermessage'];
     } else {
         $pendingOrder['ordermessage'] = '';
     }
     /**
      * Save our custom fields. If we are creating a new account then split this up so the
      * account fields will go in the customers table and the rest will go in the orders table
      */
     if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['customer']) && isset($customerId) && isId($customerId)) {
         $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['customer']);
         if (isId($formSessionId)) {
             $updateData = array('customerid' => $customerId, 'email' => $customerData['email'], 'firstname' => $customerData['firstname'], 'lastname' => $customerData['lastname'], 'company' => $customerData['company'], 'phone' => $customerData['phone'], 'custformsessionid' => $formSessionId);
             $entity = new ISC_ENTITY_CUSTOMER();
             $entity->edit($updateData);
         }
     }
     /**
      * OK, now to store the custom address fields. Check here to see if we are not split
      * shipping (single order)
      */
     if (!isset($_SESSION['CHECKOUT']['IS_SPLIT_SHIPPING']) || !$_SESSION['CHECKOUT']['IS_SPLIT_SHIPPING']) {
         $pendingOrder['ordformsessionid'] = '';
         if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']) && is_array($_SESSION['CHECKOUT']['CUSTOM_FIELDS'])) {
             /**
              * Save the billing
              */
             if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']) && isset($pendingOrder['billingaddress']['saveAddress']) && $pendingOrder['billingaddress']['saveAddress']) {
                 $pendingOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']);
             }
             /**
              * Now for the shipping. Only save this once for all the shipping addresses
              */
             if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping'])) {
                 $shippSessId = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping']);
                 foreach ($pendingOrder['vendorinfo'] as $vendorId => $vendorData) {
                     if (isset($vendorData['shippingaddress']['saveAddress']) && $vendorData['shippingaddress']['saveAddress']) {
                         $pendingOrder['vendorinfo'][$vendorId]['shippingaddress']['shipformsessionid'] = $shippSessId;
                     }
                 }
             }
             /**
              * Now the orders. This part is tricky because the billing and shipping information
              * have the same keys (same fields used in the frontend). We need to split them up
              * into separate billing and shipping information and then save it
              */
             if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']) && is_array($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'])) {
                 /**
                  * We create a map first so we can map the shipping information to its proper field
                  * ID
                  */
                 $billingKeys = array_keys($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']);
                 $fieldAddressMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_BILLING, $billingKeys);
                 /**
                  * OK, we have the map, now to split up the custom fields
                  */
                 $orderSessData = array();
                 foreach ($fieldAddressMap as $fieldId => $newShippingFieldId) {
                     $orderSessData[$fieldId] = $_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'][$fieldId];
                     if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping'][$fieldId])) {
                         $orderSessData[$newShippingFieldId] = $_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping'][$fieldId];
                     }
                 }
                 $pendingOrder['ordformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($orderSessData);
             }
         }
         /**
          * This is for split shipping. Loop through each address to get their default custom
          * field data, combine it with the billing custom field data, create the form session
          * record and then save that ID for each address
          */
     } else {
         $shippingAddresses = $this->GetOrderShippingAddresses();
         $origFormSessionData = array();
         if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']) && is_array($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'])) {
             $origFormSessionData = $_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'];
         }
         foreach ($pendingOrder['vendorinfo'] as $vendorId => $vendorData) {
             $address = null;
             $orderSessData = array();
             if (array_key_exists($vendorData['shippingaddressid'], $shippingAddresses)) {
                 $address = $shippingAddresses[$vendorData['shippingaddressid']];
             }
             if (isset($address['shipformsessionid']) && isId($address['shipformsessionid'])) {
                 $shippingSessionData = $GLOBALS['ISC_CLASS_FORM']->getSavedSessionData($address['shipformsessionid']);
                 if (is_array($shippingSessionData)) {
                     /**
                      * Same deal with this save session data because the billing and shipping data
                      * use the same fields and therefore have the same keys
                      */
                     $billingKeys = array_keys($origFormSessionData);
                     $fieldAddressMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_BILLING, $billingKeys);
                     /**
                      * OK, we have the map, now to split up the custom fields
                      */
                     $orderSessData = array();
                     foreach ($fieldAddressMap as $fieldId => $newShippingFieldId) {
                         $orderSessData[$fieldId] = $origFormSessionData[$fieldId];
                         $orderSessData[$newShippingFieldId] = $shippingSessionData[$fieldId];
                     }
                 }
             }
             $newFormSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($orderSessData);
             if (isId($newFormSessionId)) {
                 $pendingOrder['vendorinfo'][$vendorId]['ordformsessionid'] = $newFormSessionId;
             }
         }
     }
     $pendingToken = CreateOrder($pendingOrder, $cartItems);
     // Try to add the record and if we can't then take them back to the shopping cart
     if (!$pendingToken) {
         return false;
     }
     // Persist the pending order token as a cookie for 24 hours
     ISC_SetCookie("SHOP_ORDER_TOKEN", $pendingToken, time() + 3600 * 24, true);
     $_COOKIE['SHOP_ORDER_TOKEN'] = $pendingToken;
     // Redirecting to finish order page?
     if ($redirectToFinishOrder) {
         return array('redirectToFinishOrder' => true);
     }
     $orderData = LoadPendingOrdersByToken($pendingToken);
     // Otherwise, the gateway want's to do something
     $provider->SetOrderData($orderData);
     // Is this an online payment provider? It would like to do something
     if ($provider->GetPaymentType() == PAYMENT_PROVIDER_ONLINE || method_exists($provider, "ShowPaymentForm")) {
         // Call the checkout process for the selected provider
         if (method_exists($provider, "ShowPaymentForm")) {
             return array('provider' => $provider, 'showPaymentForm' => true);
         } else {
             return array('provider' => $provider);
         }
     } else {
         return array('provider' => $provider);
     }
 }
예제 #12
0
		/**
		 * Save the new password for the customer's account (via link in reset password email)
		 */
		private function SaveNewPassword()
		{

			if (isset($_GET['c']) && isset($_GET['t'])) {

				$customerId = (int)isc_html_escape($_GET['c']);
				$customerHash = isc_html_escape($_GET['t']);

				$query = "SELECT *
							FROM [|PREFIX|]customers
							WHERE customerid=" . $customerId;
				$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
				$customer = $GLOBALS['ISC_CLASS_DB']->Fetch($result);

				// Can't find them in the database
				if (!isId($customerId) || !$customer) {
					return $this->ResetPassword("invalid_link", 1);
				}

				// Also check to see if our salted string matches this customer
				if (!$this->checkCustomerHash($customerHash, $customer['customerpasswordresettoken'], $customerId)) {
					return $this->ResetPassword("invalid_link", 1);
				}

				// OK, all the arguments are cool. Now we generate a password for them
				$password = Interspire_String::generateReadablePassword();
				$updateData = array(
					'customerpasswordresettoken' => '',
					'customerpasswordresetemail' => '',
				);

				if ($GLOBALS['ISC_CLASS_DB']->UpdateQuery('customers', $updateData, 'customerid=' . $customerId) === false) {
					return $this->ResetPassword("internal_error", 1);
				}

				$entity = new ISC_ENTITY_CUSTOMER();
				$entity->updatePassword($customerId, $password);

				// Send the email
				$store_name = GetConfig('StoreName');
				$email_message = sprintf(GetLang('ForgotPasswordEmailConfirmed'), $store_name, $password);

				// Create a new email API object to send the email
				require_once(ISC_BASE_PATH . "/lib/email.php");
				$obj_email = GetEmailClass();
				$obj_email->Set('CharSet', GetConfig('CharacterSet'));
				$obj_email->From(GetConfig('OrderEmail'), $store_name);
				$obj_email->Set("Subject", sprintf(GetLang('ForgotPasswordEmailConfirmedSubject'), $store_name));
				$obj_email->AddBody("html", $email_message);
				$obj_email->AddRecipient($customer['customerpasswordresetemail'], "", "h");
				$email_result = $obj_email->Send();

				if ($email_result['success']) {
					return $this->ShowLoginPage(sprintf(GetLang('ForgotPasswordChanged'), $customer['customerpasswordresetemail']), 0, true);
				} else {
					return $this->ResetPassword("internal_error", 1);
				}
			} else {
				$this->ShowLoginPage();
			}
		}
예제 #13
0
 function UploadImage()
 {
     $GLOBALS['ISC_CLASS_CAPTCHA'] = GetClass('ISC_CAPTCHA');
     $this->checkUpload();
     if ($_POST['uploadsubmit']) {
         //upload image
         $uploadfiles = $this->pic_save($_FILES['attach'], $_POST['pic_desc'], $_POST['uploadFirstName'], $_POST['uploadLastName'], $_POST['address1'], $_POST['address2']);
         if ($uploadfiles == 'ok') {
             $customerEntity = new ISC_ENTITY_CUSTOMER();
             $customerEntity->increaseImageLastUpload($GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerId());
             $uploadStat = 1;
         } else {
             $uploadStat = $uploadfiles;
         }
         echo "<script>";
         echo "parent.uploadStat = '{$uploadStat}';";
         echo "parent.upload();";
         echo "</script>";
         exit;
     }
     $this->displayPage();
     $GLOBALS['ISC_CLASS_TEMPLATE']->SetPageTitle(GetConfig('StoreName') . " - " . GetLang('Uploadimage'));
     $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("account_uploadimage");
     $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
 }