protected function xmlrevert()
 {
     $this->xml2string($xml);
     $record = new StdClass();
     $record->name = (string) $xml->Name;
     $record->desc = (string) $xml->Desc;
     if (isset($xml->IsActive)) {
         $record->isactive = (int) $xml->IsActive;
     }
     if (isset($xml->IsTaxable)) {
         $record->istaxable = (int) $xml->IsTaxable;
     }
     if (isset($xml->ListID)) {
         $record->listid = (string) $xml->ListID;
         $record->edit_sequence = (string) $xml->EditSequence;
     }
     /**
      * We also need the sales tax code id (the misc id)
      */
     $record->salestaxcodeid = null;
     if ($xml->ListID !== '' && isId($salestaxcodeid = $this->quickbooks->getAccountingReference($ref, array('ListID' => (string) $xml->ListID), 'salestaxcode'))) {
         $record->salestaxcodeid = $salestaxcodeid;
     }
     return $record;
 }
Example #2
0
 public static function importFiles($folderStr, $mode = 0, $debug = 0)
 {
     self::$debug = $debug;
     self::$mode = $mode;
     // Get file root
     $fileRoot = Config::get('file_root');
     import('dao.Folder');
     $folder = new Folder();
     if ($folderStr == 0 || $folderStr == $fileRoot) {
         self::syncFolders(array('path' => $fileRoot, 'fd_id' => 0, 'locked' => 0));
         return;
     }
     // If folderStr is not integer (fd_id)
     // and not a sub-folder of file-root and not exist physically, exit.
     if (!isId($folderStr) && !is_dir($folderStr) || !isId($folderStr) && !strstr($fileRoot, $folderStr)) {
         echo 'Invalid folder!' . $enclose;
         return;
     }
     // Get the folder in DB, based on folderId or folderFullName from parameter
     $theFolder = $folder->getFolder($folderStr);
     // If the folder row is not empty, we need to update the folder, otherwise
     // we need to add a folder if the folderFullName is a sub-folder of file root
     if (is_null($theFolder)) {
         list($newFolderFullName, $newFolderParentId) = locateNewFolder($theFolder['path']);
         self::addForder($newFolderFullName, $newFolderParentId);
     } else {
         self::syncFolders($theFolder);
     }
 }
		private function getMoreDiscounts()
		{
			if(!isset($_POST["lastSortOrder"]) || !isId($_POST["lastSortOrder"])) {
				exit;
			}

			$items = "";
			$query = "SELECT SQL_CALC_FOUND_ROWS *
						FROM [|PREFIX|]discounts
						WHERE sortorder > " . (int)$_POST["lastSortOrder"] . "
						ORDER BY sortorder ASC
						LIMIT " . ISC_DISCOUNTS_PER_SHOW;

			$result = $GLOBALS["ISC_CLASS_DB"]->Query($query);
			$row = $GLOBALS["ISC_CLASS_DB"]->Fetch($result);
			$more = 0;

			if ($row) {
				if ($GLOBALS["ISC_CLASS_DB"]->FetchOne("SELECT FOUND_ROWS()") > ISC_DISCOUNTS_PER_SHOW) {
					$more = 1;
				}

				do {
					$items .= $GLOBALS["ISC_CLASS_ADMIN_DISCOUNTS"]->BuildDiscountGridRow($row);
				} while ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($result));
			}

			$tags[] = $this->MakeXMLTag("status", 1);
			$tags[] = $this->MakeXMLTag("items", $items, true);
			$tags[] = $this->MakeXMLTag("more", $more);
			$this->SendXMLHeader();
			$this->SendXMLResponse($tags);
			exit;
		}
Example #4
0
 public function deleteFolder($id)
 {
     if (!isId($id)) {
         ZDebug::my_echo('Param error in deleteFolder!');
         return FALSE;
     }
     $res = DB::$dbInstance->query("DELETE FROM folders WHERE fd_id = " . $id . "");
     $res = DB::$dbInstance->query("DELETE FROM folders WHERE parent_id = " . $id . "");
     $res = DB::$dbInstance->query("DELETE FROM files WHERE fd_id = " . $id . "");
     return $res;
 }
Example #5
0
 public function deleteFile($key)
 {
     if (isId($key)) {
         $field = 'fid';
     } else {
         $field = 'path';
     }
     $key = str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $key);
     $sql = 'DELETE FROM files WHERE ' . $field . ' = \'' . $key . '\'';
     return DB::$dbInstance->query($sql);
 }
 /**
  * Executed a spool
  *
  * Method will execute a spool and return the output
  *
  * @access private
  * @param int $spoolId The spool ID
  * @return string The spool XML string if the spool was executed successfully, FALSE otherwise
  */
 private function execSpoolImport($spoolId)
 {
     if (!isId($spoolId)) {
         return false;
     }
     $service = $this->quickbooks->getSpoolService($spoolId);
     if (!$service) {
         return false;
     }
     if ($this->service->exec($xml, $service, 'run', array('spoolId' => $spoolId))) {
         return $xml;
     }
     return false;
 }
Example #7
0
 public function add_country_regions()
 {
     $query = "CREATE TABLE `[|PREFIX|]country_regions` (\n\t\t `couregid` INT UNSIGNED NOT NULL AUTO_INCREMENT,\n\t\t `couregname` VARCHAR(255) NOT NULL DEFAULT '',\n\t\t `couregiso2` CHAR(2) NOT NULL DEFAULT '',\n\t\t `couregiso3` CHAR(3) NOT NULL DEFAULT '',\n\t\t PRIMARY KEY(`couregid`)\n\t\t)ENGINE=MyISAM DEFAULT CHARSET=utf8;\n\t\t";
     if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) {
         $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg());
         return false;
     }
     $data = array("couregname" => "European Union", "couregiso2" => "EU", "couregiso3" => "EUR");
     if (!isId($regionid = $GLOBALS['ISC_CLASS_DB']->InsertQuery("country_regions", $data))) {
         $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg());
         return false;
     }
     $query = "ALTER TABLE `[|PREFIX|]currencies` MODIFY `currencycountryid` INT(11) UNSIGNED DEFAULT NULL";
     if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) {
         $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg());
         return false;
     }
     $query = "ALTER TABLE `[|PREFIX|]currencies` ADD `currencycouregid` INT(11) UNSIGNED DEFAULT NULL AFTER `currencycountryid`";
     if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) {
         $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg());
         return false;
     }
     $query = "ALTER TABLE `[|PREFIX|]currencies` DROP KEY `u_currencies_currencycode_currencycountryid`";
     if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) {
         $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg());
         return false;
     }
     $query = "ALTER TABLE `[|PREFIX|]currencies` ADD UNIQUE KEY `u_currencies_currencycode_currencycountryid_currencycouregid` (`currencycode`,`currencycountryid`, `currencycouregid`)";
     if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) {
         $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg());
         return false;
     }
     $query = "ALTER TABLE `[|PREFIX|]countries` ADD `countrycouregid` INT(11) UNSIGNED DEFAULT NULL AFTER `countryid`";
     if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) {
         $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg());
         return false;
     }
     $query = "ALTER TABLE `[|PREFIX|]countries` ADD KEY `i_regions_countrycouregid` (`countrycouregid`)";
     if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) {
         $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg());
         return false;
     }
     $query = "\n\t\tUPDATE `[|PREFIX|]countries`\n\t\tSET `countrycouregid` = " . $regionid . "\n\t\tWHERE LOWER(countryname) IN ('austria', 'belgium', 'bulgaria', 'finland', 'france', 'germany', 'greece', 'ireland', 'italy', 'luxembourg', 'netherlands', 'portugal', 'spain')";
     if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) {
         $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg());
         return false;
     }
     return true;
 }
Example #8
0
	private function addAccessCategories($groupId, $categories)
	{
		$categories = @array_filter($categories, "isId");

		if (!isId($groupId) || !is_array($categories) || empty($categories)) {
			return false;
		}

		$GLOBALS["ISC_CLASS_DB"]->DeleteQuery("customer_group_categories", "WHERE customergroupid = " . (int)$groupId);

		foreach ($categories as $category) {
			$insert = array(
				"customergroupid" => $groupId,
				"categoryid" => $category
			);

			$GLOBALS["ISC_CLASS_DB"]->InsertQuery("customer_group_categories", $insert);
		}

		return true;
	}
Example #9
0
/**
 * Check to see if customer salt string matches
 *
 * Function will check to see if the unsalted customer hash string $customerString and the customer id $customerID match against the salted
 * customer hash string $saltedString
 *
 * @access public
 * @param string $saltedString The salted customer hash string to compare to
 * @param string $customerString The unsalted customer hash string
 * @param int $customerId The customer ID
 * @return bool TRUE if the salted and unsalted strings match, FALSE if no match or if any of the arguments are invalid/empty
 */
function CustomerHashCheck($saltedString, $customerString, $customerId)
{
    if ($saltedString == '' || $customerString == '' || !isId($customerId)) {
        return false;
    }
    $customerString = CustomerHashCreate($customerString, $customerId);
    if ($customerString === $saltedString) {
        return true;
    }
    return false;
}
Example #10
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']);
	}
Example #11
0
		public function SetPanelSettings()
		{
			$GLOBALS['ISC_CLASS_CATEGORY'] = GetClass('ISC_CATEGORY');

			// Should we hide the comparison button?
			if(GetConfig('EnableProductComparisons') == 0 || $GLOBALS['ISC_CLASS_CATEGORY']->GetNumProducts() < 2) {
				$GLOBALS['HideCompareItems'] = "none";
			}

			// Load the products into the reference array
			$GLOBALS['ISC_CLASS_CATEGORY']->GetProducts($products);
			$GLOBALS['CategoryProductListing'] = "";

			if(GetConfig('ShowProductRating') == 0) {
				$GLOBALS['HideProductRating'] = "display: none";
			}

			$display_mode = ucfirst(GetConfig("CategoryDisplayMode"));
			if ($display_mode == "Grid") {
				$display_mode = "";
			}
			$GLOBALS['DisplayMode'] = $display_mode;

			if ($display_mode == "List") {
				if (GetConfig('ShowAddToCartLink') && $GLOBALS['ISC_CLASS_CATEGORY']->GetNumProducts() > 0) {
					$GLOBALS['HideAddButton'] = '';
				} else {
					$GLOBALS['HideAddButton'] = 'none';
				}

				$GLOBALS['ListJS'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("ListCheckForm");
			}

			$GLOBALS['CompareButton'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CompareButton" . $display_mode);

			if ($display_mode == "List" && $GLOBALS['ISC_CLASS_CATEGORY']->GetNumPages() > 1) {
				$GLOBALS['CompareButtonTop'] = $GLOBALS['CompareButton'];
			}

			$GLOBALS['AlternateClass'] = '';
			foreach($products as $row) {
				$this->setProductGlobals($row);

				// for list style
				if ($display_mode == "List") {
					// get a small chunk of the product description
					$desc = isc_substr(strip_tags($row['proddesc']), 0, 225);
					if (isc_strlen($row['proddesc']) > 225) {
						// trim the description back to the last period or space so words aren't cut off
						$period_pos = isc_strrpos($desc, ".");
						$space_pos = isc_strrpos($desc, " ");
						// find the character that we should trim back to. -1 on space pos for a space that follows a period, so we dont end up with 4 periods
						if ($space_pos - 1 > $period_pos) {
							$pos = $space_pos;
						}
						else {
							$pos = $period_pos;
						}
						$desc = isc_substr($desc, 0, $pos);
						$desc .= "...";
					}

					$GLOBALS['ProductDescription'] = $desc;

					$GLOBALS['AddToCartQty'] = "";

					if (CanAddToCart($row) && GetConfig('ShowAddToCartLink')) {
						if (isId($row['prodvariationid']) || trim($row['prodconfigfields'])!='' || $row['prodeventdaterequired']) {
							$GLOBALS['AddToCartQty'] = '<a href="' . $GLOBALS["ProductURL"] . '">' . $GLOBALS['ProductAddText'] . "</a>";
						}
						else {
							$GLOBALS['CartItemId'] = $GLOBALS['ProductId'];
							// If we're using a cart quantity drop down, load that
							if (GetConfig('TagCartQuantityBoxes') == 'dropdown') {
								$GLOBALS['Quantity0'] = "selected=\"selected\"";
								$GLOBALS['QtyOptionZero'] = '<option %%GLOBAL_Quantity0%% value="0">Quantity</option>';
								$GLOBALS['QtySelectStyle'] = 'width: auto;';
								$GLOBALS['AddToCartQty'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CartItemQtySelect");
							// Otherwise, load the textbox
							} else {
								$GLOBALS['ProductQuantity'] = 0;
								$GLOBALS['AddToCartQty'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CartItemQtyText");
							}
						}
					}
				} // for grid style
				else {
					$GLOBALS["CompareOnSubmit"] = "onsubmit=\"return compareProducts(config.CompareLink)\"";
				}

				$GLOBALS['CategoryProductListing'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CategoryProductsItem" . $display_mode);
			}

			if($GLOBALS['ISC_CLASS_CATEGORY']->GetNumProducts() == 0) {
				// There are no products in this category
				$GLOBALS['CategoryProductListing'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CategoryNoProductsMessage");
				$GLOBALS['HideOtherProductsIn'] = 'none';

				$GLOBALS['ExtraCategoryClass'] = "Wide WideWithLeft";
				if($GLOBALS['SNIPPETS']['SubCategories'] != '') {
					$GLOBALS['CategoryProductListing'] = '';
				}
				$GLOBALS['HideRightColumn'] = "none";
			}
			else {
				$GLOBALS['HideOtherProductsIn'] = 'block';
				$GLOBALS['OtherProductsIn'] = sprintf(GetLang('OtherProductsIn'), $GLOBALS['ISC_CLASS_CATEGORY']->GetName());
			}
		}
 private function DelQValueAssociationImage($file)
 {
     if (isId($file)) {
         if (!($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($GLOBALS["ISC_CLASS_DB"]->Query("SELECT * FROM [|PREFIX|]qvalue_associations WHERE qvalueassocid='" . (int) $file . "'")))) {
             return false;
         }
         if ($row['hoverimage'] == '') {
             return true;
         } else {
             $file = $row['hoverimage'];
         }
     }
     $file = realpath(ISC_BASE_PATH . '/' . GetConfig('ImageDirectory') . '/' . $file);
     if ($file == '') {
         return false;
     }
     if (file_exists($file)) {
         @unlink($file);
         clearstatcache();
     }
     return !file_exists($file);
 }
Example #13
0
		public function MapFormFieldSection($formId)
		{
			if (!isId($formId)) {
				return false;
			}

			switch ($formId) {
				case FORMFIELDS_FORM_ACCOUNT:
					return GetLang('FormFieldsSectionAccount');
					break;

				case FORMFIELDS_FORM_ADDRESS:
					return GetLang('FormFieldsSectionAddress');
					break;
			}

			return false;
		}
 /**
  * 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);
     }
 }
Example #15
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'];
 }
 private function setDefaultCurrency($currencyId, &$message, $updatePrices = false)
 {
     $query = "SELECT * FROM [|PREFIX|]currencies WHERE currencyid='" . (int) $currencyId . "'";
     if (!isId($currencyId) || !($result = $GLOBALS['ISC_CLASS_DB']->Query($query)) || !($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result))) {
         $messages[] = GetLang('CurrencyNotSetToDefault');
         return false;
     }
     $query = "\n\t\t\t\tUPDATE [|PREFIX|]currencies\n\t\t\t\tSET currencyexchangerate = IF(currencyid <> " . $currencyId . ", (currencyexchangerate / " . (string) $row['currencyexchangerate'] . "), 1),\n\t\t\t\tcurrencyisdefault = IF(currencyid <> " . $currencyId . ", 0, 1), currencystatus = 1, currencylastupdated = UNIX_TIMESTAMP()\n\t\t\t";
     $GLOBALS['ISC_CLASS_DB']->Query($query);
     if ($GLOBALS['ISC_CLASS_DB']->Error() != "") {
         $message = $GLOBALS['ISC_CLASS_DB']->Error();
         return false;
     }
     $GLOBALS['ISC_CLASS_DB']->StartTransaction();
     if ($updatePrices == true) {
         // Now the delicate part of updating all the product prices
         $query = "\n\t\t\t\t\tUPDATE [|PREFIX|]products\n\t\t\t\t\tSET prodprice = (prodprice * " . (string) $row['currencyexchangerate'] . "), prodcostprice = (prodcostprice * " . (string) $row['currencyexchangerate'] . "),\n\t\t\t\t\tprodretailprice = (prodretailprice * " . (string) $row['currencyexchangerate'] . "), prodsaleprice = (prodsaleprice * " . (string) $row['currencyexchangerate'] . "),\n\t\t\t\t\tprodcalculatedprice = (prodcalculatedprice * " . (string) $row['currencyexchangerate'] . ")\n\t\t\t\t\t";
         $GLOBALS['ISC_CLASS_DB']->Query($query);
         if ($GLOBALS['ISC_CLASS_DB']->Error() != "") {
             $message = $GLOBALS['ISC_CLASS_DB']->Error();
             return false;
         }
         // Don't forget our product variations
         $query = "\n\t\t\t\t\tUPDATE [|PREFIX|]product_variation_combinations\n\t\t\t\t\tSET vcprice = (vcprice * " . (string) $row['currencyexchangerate'] . ")\n\t\t\t\t\t";
         $GLOBALS['ISC_CLASS_DB']->Query($query);
         if ($GLOBALS['ISC_CLASS_DB']->Error() != "") {
             $message = $GLOBALS['ISC_CLASS_DB']->Error();
             return false;
         }
         // Also any store credit for all customers
         $query = "\n\t\t\t\t\tUPDATE [|PREFIX|]customers\n\t\t\t\t\tSET custstorecredit = (custstorecredit * " . (string) $row['currencyexchangerate'] . ")\n\t\t\t\t\t";
         $GLOBALS['ISC_CLASS_DB']->Query($query);
         if ($GLOBALS['ISC_CLASS_DB']->Error() != "") {
             $message = $GLOBALS['ISC_CLASS_DB']->Error();
             return false;
         }
         // Plus any of the product discounts
         $query = "\n\t\t\t\t\tUPDATE [|PREFIX|]product_discounts\n\t\t\t\t\tSET discountamount = (discountamount * " . (string) $row['currencyexchangerate'] . ")\n\t\t\t\t\tWHERE discounttype = 'price' OR discounttype = 'fixed'\n\t\t\t\t\t";
         $GLOBALS['ISC_CLASS_DB']->Query($query);
         if ($GLOBALS['ISC_CLASS_DB']->Error() != "") {
             $message = $GLOBALS['ISC_CLASS_DB']->Error();
             return false;
         }
     }
     // Save our new currency settings
     $GLOBALS['ISC_NEW_CFG']['DefaultCurrencyID'] = (int) $row['currencyid'];
     $GLOBALS['ISC_NEW_CFG']['CurrencyToken'] = (string) $row['currencystring'];
     $GLOBALS['ISC_NEW_CFG']['CurrencyLocation'] = strtolower($row['currencystringposition']);
     $GLOBALS['ISC_NEW_CFG']['DecimalToken'] = (string) $row['currencydecimalstring'];
     $GLOBALS['ISC_NEW_CFG']['DecimalPlaces'] = (int) $row['currencydecimalplace'];
     $GLOBALS['ISC_NEW_CFG']['ThousandsToken'] = (string) $row['currencythousandstring'];
     if ($this->CommitSettings($messages)) {
         $GLOBALS['ISC_CLASS_DB']->CommitTransaction();
         return true;
     } else {
         $GLOBALS['ISC_CLASS_DB']->RollbackTransaction();
         return false;
     }
 }
 /**
  * Creates or updates a template from posted data
  *
  * @return int $id The ID of the new template
  */
 private function CommitTemplate($templateid = 0)
 {
     $vendorid = 0;
     $vendorid = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId();
     // which file types the user has selected
     $usedTypes = array("products");
     $mod_time = date("Y-m-d g:i:s");
     $array = array("importtemplatename" => $_POST["templateName"], "description" => $_POST["description"], "usedtypes" => "products", "vendorid" => $vendorid, "mod_time" => $mod_time, "myobincomeaccount" => $comma_separated = implode(",", $_POST['pre_category']));
     if ($templateid) {
         // update template
         $result = $GLOBALS['ISC_CLASS_DB']->UpdateQuery("import_templates", $array, "importtemplateid = '" . $GLOBALS['ISC_CLASS_DB']->Quote($templateid) . "'");
         if (!$result) {
             throw new Exception(sprintf(GetLang('TemplateNotUpdated'), isc_html_escape($_POST['templateName'])));
         }
     } else {
         // new template
         $templateid = $GLOBALS['ISC_CLASS_DB']->InsertQuery("import_templates", $array);
         if (!isId($templateid)) {
             throw new Exception(sprintf(GetLang('TemplateNotCreated'), isc_html_escape($_POST['templateName'])));
         }
     }
     return $templateid;
 }
Example #18
0
 public function convert_accounting_spool()
 {
     $query = "ALTER TABLE [|PREFIX|]accountingref MODIFY `accountingreftype` enum('customer','customergroup','product','order','salestaxcode','account','inventorylevel','orderlineitem') NOT NULL";
     if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) {
         $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg());
         return false;
     }
     if (!$this->TableExists('accountingspool')) {
         $query = "\n\t\t\t\tCREATE TABLE `[|PREFIX|]accountingspool` (\n\t\t\t\t  `accountingspoolid` int(10) unsigned NOT NULL auto_increment,\n\t\t\t\t  `accountingspoolparentid` int(10) unsigned NOT NULL default '0',\n\t\t\t\t  `accountingspoolmoduleid` varchar(100) NOT NULL default '',\n\t\t\t\t  `accountingspoolnodeid` int(10) unsigned NOT NULL default '0',\n\t\t\t\t  `accountingspoolserial` text,\n\t\t\t\t  `accountingspooltype` enum('customer','customergroup','product','order','salestaxcode','account','inventorylevel') NOT NULL,\n\t\t\t\t  `accountingspoolservice` enum('add','edit','query') NOT NULL,\n\t\t\t\t  `accountingspoollock` char(36) NOT NULL default '',\n\t\t\t\t  `accountingspoolstatus` tinyint(1) default '0',\n\t\t\t\t  `accountingspooldisabled` tinyint(1) NOT NULL default '0',\n\t\t\t\t  `accountingspoolerrmsg` tinytext,\n\t\t\t\t  `accountingspoolerrno` int(10) unsigned NOT NULL default '0',\n\t\t\t\t  `accountingspoolreturn` text,\n\t\t\t\t  PRIMARY KEY  (`accountingspoolid`),\n\t\t\t\t  KEY `i_accountingspool_accountingspoolparentid` (`accountingspoolparentid`),\n\t\t\t\t  KEY `i_accountingspool_accountingspoolmoduleid` (`accountingspoolmoduleid`),\n\t\t\t\t  KEY `i_accountingspool_accountingspoolnodeid` (`accountingspoolnodeid`),\n\t\t\t\t  KEY `i_accountingspool_accountingspooltype` (`accountingspooltype`)\n\t\t\t\t) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
         if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) {
             $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg());
             return false;
         }
         /**
          * If this table already exists and it has records in it then DO NOT import the spool files as order will double up and could potentially duplciate
          * products and customers
          */
     } else {
         $result = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]accountingspool");
         if ($result && $GLOBALS['ISC_CLASS_DB']->CountResult($result) > 0) {
             return true;
         }
     }
     /**
      * Now convert the existsing spool files into database accountingspool records. Force out the mandatory account spools just in case
      */
     $accounting = GetClass('ISC_ACCOUNTING');
     $initdata = array(array('type' => 'account', 'service' => 'add', 'data' => array('Name' => GetLang('QuickBooksIncomeAccountName'), 'AccountType' => 'Income')), array('type' => 'account', 'service' => 'add', 'data' => array('Name' => GetLang('QuickBooksCOGSAccountName'), 'AccountType' => 'CostOfGoodsSold')), array('type' => 'account', 'service' => 'add', 'data' => array('Name' => GetLang('QuickBooksAssetAccountName'), 'AccountType' => 'FixedAsset')));
     foreach ($initdata as $data) {
         $accounting->createServiceRequest($data['type'], $data['service'], $data['data']);
     }
     /**
      * Now for the rest. These will be in the spool cache file so you'll need to read the files from there
      */
     $files = scandir(ISC_BASE_PATH . '/cache/spool');
     foreach ($files as $file) {
         $realfile = ISC_BASE_PATH . '/cache/spool/' . $file;
         if (!is_file($realfile) || !is_readable($realfile) || substr($file, 0, 6) !== 'spool.') {
             continue;
         }
         $spooldata = null;
         @(include_once $realfile);
         if (!is_array($spooldata)) {
             continue;
         }
         /**
          * Find out if this entity exists. If not then do not import it
          */
         if (isId($spooldata['nodeid'])) {
             $className = "ISC_ENTITY_" . isc_strtoupper($spooldata['type']);
             $entity = new $className();
             if (!$entity->exists($spooldata['nodeid'])) {
                 continue;
             }
             /**
              * Save it using the data array instead of the nodeid as they might delete that entity before they import
              */
             $savedata = $entity->get($spooldata['nodeid']);
             if (!$savedata) {
                 continue;
             }
         } else {
             continue;
         }
         switch (isc_strtolower($spooldata['type'])) {
             case 'order':
                 /**
                  * We need to check if the customer and all of the products for this order still exist
                  */
                 $query = "SELECT IF(EXISTS(SELECT * FROM [|PREFIX|]customers c WHERE o.ordcustid=c.customerid), 1, 0) AS CustomerExists,\n\t\t\t\t\t\t\t\t\t(SELECT COUNT(*) FROM [|PREFIX|]order_products op1 WHERE op1.orderorderid=o.orderid) AS TotalProducts,\n\t\t\t\t\t\t\t\t\t(SELECT COUNT(*) FROM [|PREFIX|]order_products op2 JOIN [|PREFIX|]products p ON op2.ordprodid=p.productid WHERE op2.orderorderid=o.orderid) AS ValidProducts\n\t\t\t\t\t\t\t\tFROM [|PREFIX|]orders o\n\t\t\t\t\t\t\t\tWHERE o.orderid=" . (int) $spooldata['nodeid'];
                 $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
                 if (!$result) {
                     break;
                 }
                 $row = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
                 if (!$row) {
                     break;
                 }
                 if (!$row['CustomerExists'] || $row['TotalProducts'] !== $row['ValidProducts']) {
                     break;
                 }
                 $accounting->createServiceRequest('order', 'add', $savedata, 'order_create');
                 break;
             case 'product':
             case 'customer':
             case 'customergroup':
                 /**
                  * Find out if this is an add or mod. If query then skip
                  */
                 if (substr(isc_strtolower($spooldata['service']), -3) == 'add') {
                     $permission = 'create';
                     $service = 'add';
                 } else {
                     if (substr(isc_strtolower($spooldata['service']), -3) == 'mod') {
                         $permission = 'edit';
                         $service = 'edit';
                     } else {
                         break;
                     }
                 }
                 if (isc_strtolower($spooldata['type']) == 'product') {
                     $permission = 'product_' . $permission;
                 } else {
                     $permission = 'customer_' . $permission;
                 }
                 $accounting->createServiceRequest(isc_strtolower($spooldata['type']), $service, $savedata, $permission);
                 break;
             default:
                 break;
         }
     }
     return true;
 }
 public function _CopyDownloads($fromProdctId, $toProductId = 0, $toProductHash = '')
 {
     $total = 0;
     $imgDir = realpath(ISC_BASE_PATH . "/" . GetConfig('DownloadDirectory'));
     $result = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]product_downloads WHERE productid='" . $GLOBALS['ISC_CLASS_DB']->Quote($fromProdctId) . "'");
     while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
         if (($downfile = $this->_CopyImages($imgDir . '/' . $row['downfile'])) == '') {
             continue;
         }
         $newDownload = array("downfile" => $downfile, "downdateadded" => time(), "downmaxdownloads" => (int) $row['downmaxdownloads'], "downexpiresafter" => (int) $row['downexpiresafter'], "downname" => $row['downname'], "downfilesize" => (int) $row['downfilesize'], "downdescription" => $row['downdescription']);
         if (isId($toProductId)) {
             $newDownload['productid'] = $toProductId;
             $newDownload['prodhash'] = '';
         } else {
             $newDownload['productid'] = '0';
             $newDownload['prodhash'] = $toProductHash;
         }
         if ($GLOBALS['ISC_CLASS_DB']->InsertQuery("product_downloads", $newDownload)) {
             $total++;
         }
     }
     return $total;
 }
Example #20
0
	public function setPanelSettings()
	{
		if (!isset($GLOBALS['OrderId']) || !isId($GLOBALS['OrderId'])) {
			$this->DontDisplay = true;
			return;
		}

		$orderId = $GLOBALS['OrderId'];

		// Fetch the shipments for the order (not bothering to select address details here since we're viewing in the context of the order where addresses should already show)
		$shipments = array();
		$query = "
			SELECT shipmentid, shipdate, shiptrackno, shipping_module, shipmethod, shipcomments, shipshipcountryid
			FROM [|PREFIX|]shipments
			WHERE shiporderid = " . $orderId . "
			ORDER BY shipdate, shipmentid
		";
		$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
		while ($shipment = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
			$shipments[] = $shipment;
		}

		if (empty($shipments)) {
			$this->DontDisplay = true;
			return;
		}

		$GLOBALS['LNG_OrderShipments'] = GetLang('ShipmentsForOrder', array(
			'order' => $orderId,
		));

		$GLOBALS['SNIPPETS']['AccountOrderShipmentRow'] = '';

		foreach ($shipments as $shipment) {
			GetModuleById('shipping', /** @var ISC_SHIPPING */$module, $shipment['shipping_module']);

			$GLOBALS['DateShipped'] = isc_date(GetConfig('DisplayDateFormat'), $shipment['shipdate']);

			if ($module) {
				$GLOBALS['ShippingProvider'] = $module->GetName();
				$module->SetDestinationCountry($shipment['shipshipcountryid']);
			} else {
				$GLOBALS['ShippingProvider'] = $shipment['shipping_module'];
			}

			$GLOBALS['ShippingMethod'] = $shipment['shipmethod'];
			if (empty($GLOBALS['ShippingMethod']) || $GLOBALS['ShippingMethod'] == $GLOBALS['ShippingProvider']) {
				$GLOBALS['HideShippingMethod'] = 'display:none';
			} else {
				$GLOBALS['HideShippingMethod'] = '';
			}

			$GLOBALS['TrackingLink'] = isc_html_escape($shipment['shiptrackno']);
			if ($module) {
				$link = $module->GetTrackingLink($shipment['shiptrackno']);
				if ($link) {
					$GLOBALS['TrackingLink'] = '<a href="' . isc_html_escape($link) . '" target="_blank">' . $GLOBALS['TrackingLink'] . '</a>';
				}
			}

			$GLOBALS['SNIPPETS']['AccountOrderShipmentRow'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('AccountOrderShipmentRow');
		}
	}
Example #21
0
 /**
  * Get the next spool
  *
  * Method will either get the next available sibling spool, the available parent spool or FALSE based upon the spool ID $spoolId
  *
  * @access protected
  * @param string $moduleid The module ID
  * @param string $lock The accountingspoollock value
  * @param int $spoolId The spool ID to search from
  * @return array The next available spool if successful, FALSE if there is none
  */
 protected function getNextSpool($moduleid, $lock, $spoolId)
 {
     if ($moduleid == '' || $lock == '' || !isId($spoolId)) {
         return false;
     }
     $spool = self::getAccountingSpool($moduleid, $spoolId);
     if (!$spool) {
         return false;
     }
     /**
      * If we have no parent
      */
     if (!isId($spool['accountingspoolparentid'])) {
         $query = "SELECT accountingspoolid\n\t\t\t\t\tFROM [|PREFIX|]accountingspool\n\t\t\t\t\tWHERE accountingspoolparentid = 0 AND accountingspoolstatus = 0 AND accountingspoolmoduleid='" . $GLOBALS['ISC_CLASS_DB']->Quote($moduleid) . "'\n\t\t\t\t\t\tAND accountingspoollock='" . $GLOBALS['ISC_CLASS_DB']->Quote($lock) . "' AND accountingspoolid != " . $spoolId . "\n\t\t\t\t\tORDER BY accountingspoolid ASC\n\t\t\t\t\tLIMIT 1";
         /**
          * If we do
          */
     } else {
         $query = "(SELECT accountingspoolid\n\t\t\t\t\t\tFROM [|PREFIX|]accountingspool\n\t\t\t\t\t\tWHERE accountingspoolparentid = " . $spool['accountingspoolparentid'] . " AND accountingspoolstatus = 0\n\t\t\t\t\t\t\tAND accountingspoolmoduleid='" . $GLOBALS['ISC_CLASS_DB']->Quote($moduleid) . "' AND accountingspoollock='" . $GLOBALS['ISC_CLASS_DB']->Quote($lock) . "'\n\t\t\t\t\t\t\tAND accountingspoolid != " . $spoolId . "\n\t\t\t\t\t\tORDER BY accountingspoolid ASC\n\t\t\t\t\t\tLIMIT 1)\n\t\t\t\t\t\tUNION\n\t\t\t\t\t\t(SELECT " . $spool['accountingspoolparentid'] . ")";
     }
     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
     while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
         if (isId($row['accountingspoolid'])) {
             return self::getAccountingSpool($moduleid, $row['accountingspoolid']);
         }
     }
     return false;
 }
 private function DelCategoryHoverImage($file)
 {
     if (isId($file)) {
         if (!($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($GLOBALS["ISC_CLASS_DB"]->Query("SELECT * FROM [|PREFIX|]categories WHERE categoryid='" . (int) $file . "'")))) {
             return false;
         }
         if ($row['cathoverimagefile'] == '') {
             return true;
         } else {
             $file = $row['cathoverimagefile'];
         }
     }
     $file = realpath(ISC_BASE_PATH . '/' . 'category_images' . '/' . $file);
     if ($file == '') {
         return false;
     }
     if (file_exists($file)) {
         @unlink($file);
         clearstatcache();
     }
     return !file_exists($file);
 }
Example #23
0
 /**
  *	Save the new password for the customer's account
  */
 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 *\n\t\t\t\t\t\t\tFROM [|PREFIX|]customers\n\t\t\t\t\t\t\tWHERE 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 (!CustomerHashCheck($customerHash, $customer['customerpasswordresettoken'], $customerId)) {
             return $this->ResetPassword("invalid_link", 1);
         }
         // OK, all the arguments are cool. Now we generate a password for them
         $password = GenerateReadablePassword();
         $updateData = array('custpassword' => md5($password), 'customerpasswordresettoken' => '', 'customerpasswordresetemail' => '');
         if ($GLOBALS['ISC_CLASS_DB']->UpdateQuery('customers', $updateData, 'customerid=' . $customerId) === false) {
             return $this->ResetPassword("internal_error", 1);
         }
         // 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();
     }
 }
Example #24
0
	/**
	 * Handle the order errors
	 *
	 * Method will handle all the order errors. This is defined as adding and editing an order will most likely
	 * have the same errors and (long) solutions
	 *
	 * @access protected
	 * @return string The child service output if needed, else thow an exception on error
	 */
	protected function handleOrderError()
	{
		switch ($this->spool["errNo"]) {
			case 3000:

				/**
				 * Unfortunately QB doesn't set aside the failed ListID by itself so we'll need to compare
				 * it against the error message
				 */
				$customer = @$this->spool["nodeData"]["customer"];
				$products = @$this->spool["nodeData"]["products"];

				if (!is_array($customer) || empty($customer)) {
					throw new QBException("Missing/Invalid customer record in the order spool", $this->spool);
				}

				if (!is_array($products) || empty($products)) {
					throw new QBException("Missing/Invalid product record in the order spool", $this->spool);
				}

				$reference = $this->getReference("customer", '', '', $customer["customerid"], false);
				$pass = true;

				if (!is_array($reference)) {
					$pass = false;
				} else if (!isset($reference["accountingrefexternalid"]) || strpos($this->spool["errMsg"], $reference["accountingrefexternalid"]) !== -1) {
					$pass = false;
					$this->unsetReference("customer", $reference["accountingrefid"]);
				}

				/**
				 * Did the  customer pass?
				 */
				if (!$pass) {
					return $this->execChildService("customer", "add", $customer);
				}

				/**
				 * If it did then it must be in the products
				 */
				foreach ($products as $prodData) {
					if (isset($prodData["prodvariationid"]) && isId($prodData["prodvariationid"])) {
						$prodType = "productvariation";
						$prodId = $prodData["prodvariationid"];
					} else {
						$prodType = "product";
						$prodId = $prodData["productid"];
					}

					$reference = $this->getReference($prodType, '', '', $prodId, false);
					$pass = true;

					if (!is_array($reference)) {
						$pass = false;
					} else if (!isset($reference["accountingrefexternalid"]) || strpos($this->spool["errMsg"], $reference["accountingrefexternalid"]) !== -1) {
						$pass = false;
						$this->unsetReference($prodType, $reference["accountingrefid"]);
					}

					/**
					 * Did the product pass?
					 */
					if (!$pass) {
						return $this->execChildService($prodType, "add", $prodId);
					}
				}

				/**
				 * If we are here then I've NFI on what happened
				 */
				throw new QBException("Invalid order data. Either missing customer and products OR something else", $this->spool);
				break;
		}
	}
 /**
  * Handle response from a request
  *
  * Method will handle the response from a request
  *
  * @access protected
  * @return bool true if the response was successful and handled correctly, FALSE otherwise
  */
 protected function response()
 {
     /**
      * If we failed to insert this record, then check the response status code. If the code is 3100 'Name is not unique' then we execute the required
      * services to 'edit' this customer
      */
     if (($code = parent::handleResponse()) !== true) {
         if ($code == 3100) {
             /**
              * Just quickly check to see if we already have the ListID for this customer first. If we do then we just saved a 'customerquery' SOAP call
              */
             $reference = $this->getAccountingReference($this->spoolData['accountingspoolnodeid'], 'customer');
             if ($reference) {
                 /**
                  * Run our 'customermod' service with this information. Add this job as a child
                  */
                 $editSpoolId = $this->createChildSpool('customer', 'edit', $this->spoolData['accountingspoolnode']);
                 if (isId($editSpoolId)) {
                     return true;
                 }
                 throw new Exception('Cannot initiate an "CustomerMod" override service for the CustomerAdd spool ' . $this->spoolId);
             }
             /**
              * Ok, we didn't find a match. Run the "customerquery" service and associate it with this service
              */
             $querySpoolId = $this->createChildSpool('customer', 'query', $this->spoolData['accountingspoolnode']);
             if (isId($querySpoolId)) {
                 return true;
             }
             throw new Exception('Cannot initiate an "CustomerQuery" override service for the CustomerAdd spool ' . $this->spoolId);
         }
         throw new Exception('An error occured when trying to handle the response from the CustomerAdd spool ' . $this->spoolId);
     }
     /**
      * Customer was successfully added, now all we need to do is to store the association information for this customer
      */
     $listid = trim(@(string) $this->data->info->CustomerRet->ListID);
     $sequence = trim(@(string) $this->data->info->CustomerRet->EditSequence);
     if ($listid !== '' && $sequence !== '') {
         $reference = array('ListID' => $listid, 'EditSequence' => $sequence);
         $this->setAccountingReference($this->spoolData['accountingspoolnodeid'], 'customer', $reference);
         return true;
     }
     throw new Exception('Cannot insert the customer using the information in the CustomerAdd spool ' . $this->spoolId);
 }
Example #26
0
 /**
  * Set the panel settings.
  */
 public function SetPanelSettings()
 {
     $cVendor = GetClass('ISC_VENDORS');
     $vendor = $cVendor->GetVendor();
     $GLOBALS['VendorId'] = $vendor['vendorid'];
     $GLOBALS['VendorName'] = $vendor['vendorname'];
     // Set the field we're sorting results by
     if (isset($_REQUEST['sort'])) {
         $sort = $_REQUEST['sort'];
     } else {
         $sort = '';
     }
     switch ($sort) {
         case 'newest':
             $sortField = 'p.productid DESC';
             $GLOBALS['SortNewestSelected'] = 'selected="selected"';
             break;
         case 'bestselling':
             $sortField = 'p.prodnumsold DESC';
             $GLOBALS['SortBestSellingSelected'] = 'selected="selected"';
             break;
         case 'alphaasc':
             $sortField = 'p.prodname ASC';
             $GLOBALS['SortAlphaAsc'] = 'selected="selected"';
             break;
         case 'alphadesc':
             $sortField = 'p.prodname DESC';
             $GLOBALS['SortAlphaDesc'] = 'selected="selected"';
             break;
         case 'avgcustomerreview':
             $sortField = 'prodavgrating DESC';
             $GLOBALS['SortAvgReview'] = 'selected="selected"';
             break;
         case 'priceasc':
             $sortField = 'p.prodcalculatedprice ASC';
             $GLOBALS['SortPriceAsc'] = 'selected="selected"';
             break;
         case 'pricedesc':
             $sortField = 'p.prodcalculatedprice DESC';
             $GLOBALS['SortPriceDesc'] = 'selected="selected"';
             break;
         default:
             $sortField = 'p.prodvendorfeatured DESC';
             $sort = 'featured';
             $GLOBALS['SortFeaturedSelected'] = 'selected="selected"';
             break;
     }
     // If we're viewing a certain page, fetch our starting position
     if (isset($_REQUEST['page']) && IsId($_REQUEST['page'])) {
         $page = (int) $_REQUEST['page'];
         $start = $page * GetConfig('CategoryProductsPerPage') - GetConfig('CategoryProductsPerPage');
     } else {
         $page = 1;
         $start = 0;
     }
     // Count the number of products that belong in this vendor
     $query = "\n\t\t\tSELECT COUNT(p.productid) AS numproducts\n\t\t\tFROM [|PREFIX|]products p\n\t\t\t" . GetProdCustomerGroupPermissionsSQL() . "\n\t\t\tWHERE p.prodvisible='1' AND p.prodvendorid='" . (int) $vendor['vendorid'] . "'\n\t\t";
     $numProducts = $GLOBALS['ISC_CLASS_DB']->FetchOne($query);
     $numPages = ceil($numProducts / GetConfig('CategoryProductsPerPage'));
     // Now load the actual products for this vendor
     $query = "\n\t\t\t\tSELECT p.*, FLOOR(prodratingtotal/prodnumratings) AS prodavgrating, imageisthumb, imagefile, " . GetProdCustomerGroupPriceSQL() . "\n\t\t\t\tFROM [|PREFIX|]products p\n\t\t\t\tLEFT JOIN [|PREFIX|]product_images pi ON (p.productid=pi.imageprodid AND imageisthumb=1)\n\t\t\t\tWHERE prodvisible='1' AND p.prodvendorid='" . (int) $vendor['vendorid'] . "'\n\t\t\t\tORDER BY " . $sortField . ", prodname ASC\n\t\t\t";
     $query .= $GLOBALS['ISC_CLASS_DB']->AddLimit($start, GetConfig('CategoryProductsPerPage'));
     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
     $GLOBALS['SNIPPETS']['VendorProducts'] = '';
     if (GetConfig('EnableProductReviews') == 0) {
         $GLOBALS['HideProductRating'] = "display: none";
     }
     // Should we show the compare button?
     if (GetConfig('EnableProductComparisons') == 0 || $numProducts < 2) {
         $GLOBALS['HideCompareItems'] = "none";
     } else {
         $GLOBALS['CompareLink'] = CompareLink();
     }
     $GLOBALS['AlternateClass'] = '';
     while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
         if ($GLOBALS['AlternateClass'] == 'Odd') {
             $GLOBALS['AlternateClass'] = 'Even';
         } else {
             $GLOBALS['AlternateClass'] = 'Odd';
         }
         $GLOBALS['ProductCartQuantity'] = '';
         if (isset($GLOBALS['CartQuantity' . $row['productid']])) {
             $GLOBALS['ProductCartQuantity'] = (int) $GLOBALS['CartQuantity' . $row['productid']];
         }
         $GLOBALS['ProductId'] = (int) $row['productid'];
         $GLOBALS['ProductName'] = isc_html_escape($row['prodname']);
         $GLOBALS['ProductLink'] = ProdLink($row['prodname']);
         $GLOBALS['ProductRating'] = (int) $row['prodavgrating'];
         // Determine the price of this product
         $GLOBALS['ProductPrice'] = CalculateProductPrice($row);
         $GLOBALS['ProductThumb'] = ImageThumb($row['imagefile'], ProdLink($row['prodname']));
         if (isId($row['prodvariationid']) || trim($row['prodconfigfields']) != '' || $row['prodeventdaterequired'] == 1) {
             $GLOBALS['ProductURL'] = ProdLink($row['prodname']);
             $GLOBALS['ProductAddText'] = GetLang('ProductChooseOptionLink');
         } else {
             $GLOBALS['ProductURL'] = CartLink($row['productid']);
             $GLOBALS['ProductAddText'] = GetLang('ProductAddToCartLink');
         }
         if (CanAddToCart($row) && GetConfig('ShowAddToCartLink')) {
             $GLOBALS['HideActionAdd'] = '';
         } else {
             $GLOBALS['HideActionAdd'] = 'none';
         }
         $GLOBALS['HideProductVendorName'] = 'display: none';
         $GLOBALS['ProductVendor'] = '';
         if (GetConfig('ShowProductVendorNames') && $row['prodvendorid'] > 0) {
             $vendorCache = $GLOBALS['ISC_CLASS_DATA_STORE']->Read('Vendors');
             if (isset($vendorCache[$row['prodvendorid']])) {
                 $GLOBALS['ProductVendor'] = '<a href="' . VendorLink($vendorCache[$row['prodvendorid']]) . '">' . isc_html_escape($vendorCache[$row['prodvendorid']]['vendorname']) . '</a>';
                 $GLOBALS['HideProductVendorName'] = '';
             }
         }
         $GLOBALS['SNIPPETS']['VendorProducts'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("VendorProductsItem");
     }
     // Does paging need to be shown?
     if ($numProducts > GetConfig('CategoryProductsPerPage')) {
         $GLOBALS['SNIPPETS']['PagingData'] = "";
         $numEitherSide = 5;
         $start = max($page - $numEitherSide, 1);
         $end = min($page + $numEitherSide, $numPages);
         for ($i = $start; $i <= $end; $i++) {
             if ($i == $page) {
                 $snippet = "CategoryPagingItemCurrent";
             } else {
                 $snippet = "CategoryPagingItem";
             }
             $pageData = array('page' => $i, 'sort' => $sort);
             $GLOBALS['PageLink'] = VendorProductsLink($vendor, $pageData);
             $GLOBALS['PageNumber'] = $i;
             $GLOBALS['SNIPPETS']['PagingData'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet($snippet);
         }
         // Do we need to output a "Previous" link?
         if ($page > 1) {
             $pageData = array('page' => $page - 1, 'sort' => $sort);
             $GLOBALS['PrevLink'] = VendorProductsLink($vendor, $pageData);
             $GLOBALS['SNIPPETS']['CategoryPagingPrevious'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CategoryPagingPrevious");
         }
         // Do we need to output a "Next" link?
         if ($page < $numPages) {
             $pageData = array('page' => $page + 1, 'sort' => $sort);
             $GLOBALS['NextLink'] = VendorProductsLink($vendor, $pageData);
             $GLOBALS['SNIPPETS']['CategoryPagingNext'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CategoryPagingNext");
         }
         $output = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CategoryPaging");
         $output = $GLOBALS['ISC_CLASS_TEMPLATE']->ParseSnippets($output, $GLOBALS['SNIPPETS']);
         $GLOBALS['SNIPPETS']['ProductPaging'] = $output;
     }
     // Parse the sort select box snippet
     if ($numProducts > 1) {
         // Parse the sort select box snippet
         if ($GLOBALS['EnableSEOUrls'] == 1 && $vendor['vendorfriendlyname']) {
             $GLOBALS['URL'] = VendorProductsLink($vendor);
         } else {
             $GLOBALS['URL'] = $GLOBALS['ShopPath'] . "/vendors.php";
             $GLOBALS['HiddenSortField'] = "<input type=\"hidden\" name=\"vendorid\" value=\"" . (int) $vendor['vendorid'] . "\" />";
             $GLOBALS['HiddenSortField'] .= "<input type=\"hidden\" name=\"action\" value=\"products\" />";
         }
         $GLOBALS['SNIPPETS']['CategorySortBox'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CategorySortBox");
     }
 }
Example #27
0
		/**
		 * Save the submitted shipping address form data
		 *
		 * Method will map and save all the shipping address data
		 *
		 * @access private
		 * @param array $fields The form fields to save
		 * @param int $customerId The customerId
		 * @param int $shippingId The optional shipping ID. Default is 0 (new record)
		 * @return mixed The new shipping ID on successful new record, TRUE if record successfully
		 *               updated, FALSE on error
		 */
		private function saveAddressFields($fields, $customerId, $shippingId=0)
		{
			if (!is_array($fields) || empty($fields) || !isId($customerId)) {
				return false;
			}

			$savedata = array(
				'shipcustomerid' => $customerId
			);

			if (isId($shippingId)) {
				$savedata['shipid'] = $shippingId;
			}

			/**
			 * Map the private data
			 */
			$country = $state = '';

			foreach (array_keys($fields) as $fieldId) {
				$privateId = $fields[$fieldId]->record['formfieldprivateid'];

				if ($privateId == '' || !array_key_exists($privateId, $this->shippingMap)) {
					continue;
				}

				$savedata[$this->shippingMap[$privateId]] = $fields[$fieldId]->getValue();

				if (strtolower($privateId) == 'country') {
					$country = $fields[$fieldId]->getValue();
				} else if (strtolower($privateId) == 'state') {
					$state = $fields[$fieldId]->getValue();
				}
			}

			/**
			 * Find the country and state ID if we can
			 */
			$countryId = $stateId = 0;

			if ($country !== '') {
				$countryId = GetCountryByName($country);
			}

			if ($state !== '' && isId($countryId)) {
				$stateId = GetStateByName($state, $countryId);
			}

			$savedata['shipcountryid'] = (int)$countryId;
			$savedata['shipstateid'] = (int)$stateId;

			/**
			 * Save our custom (non private) fields if we are allowed
			 */
			if (gzte11(ISC_MEDIUMPRINT)) {

				/**
				 * Do we already have a form session ID for this address?
				 */
				$formSessionId = 0;
				if (isId($shippingId)) {
					$address = $this->shippingEntity->get($shippingId);
					if (is_array($address) && isset($address['shipformsessionid']) && isId($address['shipformsessionid'])) {
						$formSessionId = $address['shipformsessionid'];
					}
				}

				if (isId($formSessionId)) {
					$GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ADDRESS, true, $formSessionId);
				} else {
					$formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ADDRESS);
					if (isId($formSessionId)) {
						$savedata['shipformsessionid'] = $formSessionId;
					}
				}
			}

			if (isId($shippingId)) {
				return $this->shippingEntity->edit($savedata);
			} else {
				return $this->shippingEntity->add($savedata);
			}
		}
Example #28
0
		/**
		*	Save the edited account details back to the database
		*/
		public function SaveAccountDetails()
		{
			/**
			 * Customer Details
			 */
			$customerMap = array(
				'EmailAddress' => 'account_email',
				'Password' => 'account_password',
				'ConfirmPassword' => 'account_password_confirm'
			);

			$fields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_ACCOUNT, true);

			/**
			 * Validate the field input. Unset the password and confirm password fields first
			 */
			foreach (array_keys($fields) as $fieldId) {
				if (isc_strtolower($fields[$fieldId]->record['formfieldprivateid']) == 'password' || isc_strtolower($fields[$fieldId]->record['formfieldprivateid']) == 'confirmpassword') {
					$fields[$fieldId]->setRequired(false);
				}
			}

			$errmsg = '';
			if (!validateFieldData($fields, $errmsg)) {
				return $this->EditAccount($errmsg, MSG_ERROR);
			}

			foreach(array_keys($fields) as $fieldId) {
				if (!array_key_exists($fields[$fieldId]->record['formfieldprivateid'], $customerMap)) {
					continue;
				}

				$_POST[$customerMap[$fields[$fieldId]->record['formfieldprivateid']]] = $fields[$fieldId]->GetValue();
			}

			$customer_id = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerId();
			$email_taken = false;
			$phone_invalid = false;
			$password_invalid = false;

			if (isset($_POST['account_firstname']) &&
			   isset($_POST['account_lastname']) &&
			   isset($_POST['account_companyname']) &&
			   isset($_POST['account_email']) &&
			   isset($_POST['account_phone']) &&
			   isset($_POST['account_password']) &&
			   isset($_POST['account_password_confirm'])) {

					// Are they updating their email address? If so is the new email address available?
					if ($GLOBALS['ISC_CLASS_CUSTOMER']->AccountWithEmailAlreadyExists($_POST['account_email'], $customer_id)) {
						$email_taken = true;
					}

					if (!$GLOBALS['ISC_CLASS_CUSTOMER']->ValidatePhoneNumber($_POST['account_phone'])) {
						$phone_invalid = true;
					}

					$pass1 = $_POST['account_password'];
					$pass2 = $_POST['account_password_confirm'];

					if ($pass1 . $pass2 !== '' && $pass1 !== $pass2) {
						$password_invalid = true;
					}

					if (!$email_taken && !$phone_invalid && !$password_invalid) {

						$UpdatedAccount = array(
							"customerid" => $customer_id,
							"custconfirstname" => $_POST['account_firstname'],
							"custconlastname" => $_POST['account_lastname'],
							"custconcompany" => $_POST['account_companyname'],
							"custconemail" => $_POST['account_email'],
							"custconphone" => $_POST['account_phone']
						);

						// Do we need to update the password?
						if ($pass1 == $pass2 && $pass1 != "") {
							$UpdatedAccount['custpassword'] = $pass1;
						}

						$existingCustomer = $this->customerEntity->get($customer_id);

						/**
						 * Create/Update our form session data
						 */
						if (isId($existingCustomer['custformsessionid'])) {
							$GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT, true, $existingCustomer['custformsessionid']);
						} else {
							$UpdatedAccount['custformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT);
						}

						if ($this->customerEntity->edit($UpdatedAccount)) {
							$this->EditAccount(GetLang('AccountDetailsUpdatedSuccess'), MSG_SUCCESS);
						} else {
							$this->EditAccount(GetLang('AccountDetailsUpdatedFailed'), MSG_ERROR);
						}

					}
					else if ($email_taken) {
						// Email address is already taken
						$this->EditAccount(sprintf(GetLang('AccountUpdateEmailTaken'), $_POST['account_email']), MSG_ERROR);
					}
					else if ($phone_invalid) {
						// Phone number is invalid
						$this->EditAccount(sprintf(GetLang('AccountUpdateValidPhone'), $_POST['account_phone']), MSG_ERROR);
					}
					else if ($password_invalid) {
						$this->EditAccount(GetLang('AccountPasswordsDontMatch'), MSG_ERROR);
					}
			}
			else {
				ob_end_clean();
				header(sprintf("Location: %s/account.php", $GLOBALS['ShopPath']));
				die();
			}
		}
	public function SetPanelSettings()
	{
		if(!gzte11(ISC_HUGEPRINT) || $GLOBALS['ISC_CLASS_PRODUCT']->GetProductVendor() === false) {
			$this->DontDisplay = true;
			return false;
		}

		$vendor = $GLOBALS['ISC_CLASS_PRODUCT']->GetProductVendor();
		$GLOBALS['SNIPPETS']['VendorsOtherProducts'] = '';

		if(!getProductReviewsEnabled()) {
			$GLOBALS['HideProductRating'] = "display: none";
		}

		$query = $this->getProductQuery(
			'p.prodvendorid='.(int)$vendor['vendorid'].' AND p.productid!='.$GLOBALS['ISC_CLASS_PRODUCT']->getProductId(),
			'p.prodvendorfeatured DESC, RAND() DESC',
			10 // Select 1 more than will be shown to check if we need to show the "has more" link
		);
		$result = $GLOBALS['ISC_CLASS_DB']->Query($query);

		$productsDone = 0;
		$hasMore = false;
		$GLOBALS['AlternateClass'] = '';
		while($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
			++$productsDone;
			if($productsDone == 9) {
				$hasMore = true;
				break;
			}
			if($GLOBALS['AlternateClass'] == 'Odd') {
				$GLOBALS['AlternateClass'] = 'Even';
			}
			else {
				$GLOBALS['AlternateClass'] = 'Odd';
			}

			$GLOBALS['ProductCartQuantity'] = '';
			if(isset($GLOBALS['CartQuantity'.$row['productid']])) {
				$GLOBALS['ProductCartQuantity'] = (int)$GLOBALS['CartQuantity'.$row['productid']];
			}

			$GLOBALS['ProductId'] = (int) $row['productid'];
			$GLOBALS['ProductName'] = isc_html_escape($row['prodname']);
			$GLOBALS['ProductLink'] = ProdLink($row['prodname']);
			$GLOBALS['ProductRating'] = (int)$row['prodavgrating'];

			// Determine the price of this product
			$GLOBALS['ProductPrice'] = formatProductCatalogPrice($row);

			$GLOBALS['ProductThumb'] = ImageThumb($row, ProdLink($row['prodname']));

			if (isId($row['prodvariationid']) || trim($row['prodconfigfields'])!='' || $row['prodeventdaterequired'] == 1) {
				$GLOBALS['ProductURL'] = ProdLink($row['prodname']);
				$GLOBALS['ProductAddText'] = GetLang('ProductChooseOptionLink');
			} else {
				$GLOBALS['ProductURL'] = CartLink($row['productid']);
				$GLOBALS['ProductAddText'] = GetLang('ProductAddToCartLink');
			}

			if (CanAddToCart($row) && GetConfig('ShowAddToCartLink')) {
				$GLOBALS['HideActionAdd'] = '';
			} else {
				$GLOBALS['HideActionAdd'] = 'none';
			}

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

		if(!$GLOBALS['SNIPPETS']['VendorsOtherProducts']) {
			$this->DontDisplay = true;
		}

		$GLOBALS['VendorProductsLink'] = VendorProductsLink($vendor);
		if($hasMore == true) {
			$GLOBALS['HideViewAllLink'] = '';
		}
		else {
			$GLOBALS['HideViewAllLink'] = 'display: none';
		}
	}
<?php

function isId($array_variable, $id)
{
    # code...
    if ($id > 0 && $id <= 4) {
        return $array_variable[$id - 1]['user_name'];
    } else {
        return '存在しないユーザーです。';
    }
}
$userdata[] = array('id' => 1, 'user_name' => 'subaru', 'title' => 'title1', 'content' => 'content1');
$userdata[] = array('id' => 2, 'user_name' => 'tanaka', 'title' => 'title2', 'content' => 'content2');
$userdata[] = array('id' => 3, 'user_name' => 'ochi', 'title' => 'title3', 'content' => 'content3');
$userdata[] = array('id' => 4, 'user_name' => 'kuru', 'title' => 'title4', 'content' => 'content4');
// var_dump($userdata);
$name = isId($userdata, 1);
var_dump($name);
echo $name . "<br>";