Example #1
0
		public function FetchExchangeRate($fromCode, $toCode)
		{
			// Can make a SOAP request but a REST (POST or GET) request is quicker
			// The fields to post
			$postFields = "FromCurrency=" . urlencode(strtoupper($fromCode)) . "&ToCurrency=" . urlencode(strtoupper($toCode));

			$rtn = PostToRemoteFileAndGetResponse($this->GetTargetURL(), $postFields);

			// If we have failed then there is nothing really useful you can tell the client other than this service is temporarly unavailable
			if (!$rtn) {
				$this->SetError(GetLang("CurrencyProviderRequestUnavailable"));
				return false;
			}

			// Now we parse the return XML. Its not a big XML result and we only need one value out of it so we don't need anything heavy to read it.
			// If the parsing failed or if we didn't receive a value then we wern't given a valid XML due to the code(s) being incorrect
			$xml = @simplexml_load_string($rtn);
			if(!is_object($xml)) {
				$this->SetError(GetLang("CurrencyProviderRequestInvalidCode"));
				return false;
			}

			if (empty($xml)) {
				return (double)$xml;
			} else {
				return (double)$xml[0];
			}
		}
Example #2
0
	/**
	* Actually connect to the server and call the requested methods, parsing the result
	* You should never have to call this public function manually
	*
	* This is an override of the MCAPI callServer method to use ISC's network code. Since it's now using ISC, the error codes produced may not match MCAPI documents.
	*
	* @param string $method
	* @param array $params
	* @param int $timeout
	* @return string|bool resulting response body on success, or false on failure
	*/
	public function callServer($method, $params, $timeout = self::MCAPI_TIMEOUT)
	{
		$dc = "us1";
		if (strstr($this->api_key,"-")){
			list($key, $dc) = explode("-",$this->api_key,2);
			if (!$dc) $dc = "us1";
		}
		$host = $dc.".".$this->apiUrl["host"];
		$params["apikey"] = $this->api_key;

		$this->errorMessage = "";
		$this->errorCode = "";

		$url = 'http';
		if ($this->secure) {
			$url .= 's';
		}
		$url .= '://' . $host . $this->apiUrl['path'] . '?' . $this->apiUrl['query'] . '&method=' . $method;

		$requestOptions = new Interspire_Http_RequestOptions;
		$requestOptions->userAgent = 'MCAPI/' . $this->version . ' (BigCommerce)';

		$response = PostToRemoteFileAndGetResponse($url, http_build_query($params), $timeout, $errno, $requestOptions);

		if (!$response) {
			$this->errorMessage = "Could not connect (" . $errno . ": " . GetLang('ISC_REMOTEFILE_ERROR_' . $errno) . ")";
			$this->errorCode = $errno;
			Interspire_Event::trigger('Interspire_EmailIntegration_MailChimp/error', array(
				'method' => $method,
				'params' => $params,
				'api' => $this,
			));
			return false;
		}

		if (ini_get("magic_quotes_runtime")) {
			$response = stripslashes($response);
		}

		$serial = unserialize($response);
		if($response && $serial === false) {
			$response = array("error" => "Bad Response.  Got This: " . $response, "code" => "-99");
		} else {
			$response = $serial;
		}
		if(is_array($response) && isset($response["error"])) {
			$this->errorMessage = $response["error"];
			$this->errorCode = $response["code"];
			Interspire_Event::trigger('Interspire_EmailIntegration_MailChimp/error', array(
				'method' => $method,
				'params' => $params,
				'api' => $this,
			));
			return false;
		}

		return $response;
	}
	/**
	 * Generate the list of video walkthroughs.
	 */
	public function GetVideoWalkthroughs()
	{
		$expires = 86400; // 24 hr

		$cacheFile = ISC_BASE_PATH.'/cache/feeds/dashboard-videos.xml';
		if(file_exists($cacheFile) && filemtime($cacheFile) > time() - $expires) {
			$videoContents = file_get_contents($cacheFile);
			$modified = filemtime($cacheFile);
		}
		else {
			$videoContents = PostToRemoteFileAndGetResponse(GetConfig('VideoWalkthroughFeed'));
			if($videoContents) {
				@file_put_contents($cacheFile, $videoContents);
			}
			$modified = time();
		}

		if(!$videoContents) {
			exit;
		}

		$xml = @simplexml_load_string($videoContents);
		if(!is_object($xml)) {
			exit;
		}

		$output = '';
		$this->template->Assign('Width', (int)$xml->width);
		$this->template->Assign('Height', (int)$xml->height);
		foreach($xml->video as $video) {
			$this->template->Assign('Title', isc_html_escape($video->title));
			$this->template->Assign('URL', isc_html_escape($video->url));
			if($_SERVER['HTTPS'] == 'on') {
				$video->preview = str_replace('http://', 'https://', $video->preview);
			}
			$this->template->Assign('Preview', isc_html_escape($video->preview));
			$output .= $this->template->render('Snippets/DashboardVideoWalkthroughItem.html');
		}

		header("Last-Modified: " . gmdate("r", $modified));
		header("Pragma: public");
		header("Cache-control: public,maxage=" . $expires);
		header("Expires: " . gmdate("r", $modified + $expires));

		echo $output;
		exit;
	}
 /**
  * Get the list of hashes from the remote file
  *
  * @return void
  **/
 private function GetHashes()
 {
     if (!file_exists($this->cacheFile)) {
         $result = PostToRemoteFileAndGetResponse($this->hashUrl);
         if (strpos($result, 'init.php') === false) {
             return;
         }
         file_put_contents($this->cacheFile, $result);
         unset($result);
     }
     $lines = file($this->cacheFile);
     reset($lines);
     while (list($key, $line) = each($lines)) {
         list($hash, $file) = preg_split('#\\s+#', $line, 2, PREG_SPLIT_NO_EMPTY);
         $file = preg_replace('#^\\./#', ISC_BASE_PATH . '/', trim($file));
         $this->hashes[$file][] = $hash;
         unset($lines[$key]);
     }
 }
Example #5
0
 /**
  * Send the order notification SMS text message
  */
 public function SendNotification()
 {
     // Load up the variables for the SMS gateway
     $this->_username = $this->GetValue("username");
     $this->_password = $this->GetValue("password");
     $this->_cellnumber = $this->GetValue("cellnumber");
     $this->_message = $this->BuildSmsMessage();
     $sms_url = sprintf("http://www.smsglobal.com.au/http-api.php?action=sendsms&user=%s&password=%s&from=%s&to=%s&clientcharset=UTF-8&text=%s", $this->_username, $this->_password, $this->_cellnumber, $this->_cellnumber, urlencode($this->_message));
     // Let's try to send the message
     $result = PostToRemoteFileAndGetResponse($sms_url);
     if (is_numeric(isc_strpos($result, "OK"))) {
         $result = array("outcome" => "success", "message" => sprintf(GetLang('SMSNotificationSentNumber'), $this->_cellnumber));
     } else {
         // The message couldn't be sent. Do they have enough credit?
         $low_balance = false;
         $bal_url = sprintf("http://www.smsglobal.com.au/http-api.php?action=balancesms&user=%s&password=%s", $this->_username, $this->_password);
         $bal_result = PostToRemoteFileAndGetResponse($bal_url);
         // SMSGlobal returns the balance in the format: BALANCE: 0.0999999; USER: johndoe
         $bal_data = explode(";", $bal_result);
         if (is_array($bal_data) && count($bal_data) > 1) {
             $bal_data_1 = explode(":", $bal_data[0]);
             if (is_array($bal_data_1)) {
                 $balance = floor((int) trim($bal_data_1[1]));
                 if ($balance == 0) {
                     $low_balance = true;
                 }
             }
         }
         if ($low_balance) {
             $error_message = GetLang('SMSZeroBalance');
         } else {
             $error_message = $bal_result;
         }
         $result = array("outcome" => "fail", "message" => $error_message);
     }
     return $result;
 }
Example #6
0
 private function GetQuote()
 {
     // The following array will be returned to the calling function.
     // It will contain at least one ISC_SHIPPING_QUOTE object if
     // the shipping quote was successful.
     $fx_quote = array();
     // Connect to FedEx to retrieve a live shipping quote
     $items = "";
     $result = "";
     $valid_quote = false;
     $fx_url = "https://gateway.fedex.com/GatewayDC";
     $weight = number_format(max(ConvertWeight($this->_weight, 'lbs'), 0.1), 1);
     // If we're shipping from US or Canada, originstate is required
     if (GetConfig('CompanyCountry') == "United States" || GetConfig('CompanyCountry') == "Canada") {
         $this->_originstate = GetStateISO2ByName(GetConfig('CompanyState'));
     }
     // If we're shipping to the US or Canada, deststate is required, otherwise it isn't - based off post codes
     if ($this->_destcountry != "US" && $this->_destcountry != "CA") {
         $this->_deststate = '';
     }
     if ($this->_ratetype == "account") {
         $listRate = "false";
     } else {
         $listRate = "true";
     }
     $fx_xml = sprintf("<" . "?" . "xml version=\"1.0\" encoding=\"UTF-8\" " . "?" . ">\n\t\t\t\t<FDXRateRequest xmlns:api=\"http://www.fedex.com/fsmapi\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"FDXRateRequest.xsd\">\n\t\t\t\t\t<RequestHeader>\n\t\t\t\t\t\t<CustomerTransactionIdentifier>Express Rate</CustomerTransactionIdentifier>\n\t\t\t\t\t\t<AccountNumber>%s</AccountNumber>\n\t\t\t\t\t\t<MeterNumber>%s</MeterNumber>\n\t\t\t\t\t\t<CarrierCode>%s</CarrierCode>\n\t\t\t\t\t</RequestHeader>\n\t\t\t\t\t<DropoffType>%s</DropoffType>\n\t\t\t\t\t<Service>%s</Service>\n\t\t\t\t\t<Packaging>%s</Packaging>\n\t\t\t\t\t<WeightUnits>LBS</WeightUnits>\n\t\t\t\t\t<Weight>%s</Weight>\n\t\t\t\t\t<OriginAddress>\n\t\t\t\t\t\t<StateOrProvinceCode>%s</StateOrProvinceCode>\n\t\t\t\t\t\t<PostalCode>%s</PostalCode>\n\t\t\t\t\t\t<CountryCode>%s</CountryCode>\n\t\t\t\t\t</OriginAddress>\n\t\t\t\t\t<DestinationAddress>\n\t\t\t\t\t\t<StateOrProvinceCode>%s</StateOrProvinceCode>\n\t\t\t\t\t\t<PostalCode>%s</PostalCode>\n\t\t\t\t\t\t<CountryCode>%s</CountryCode>\n\t\t\t\t\t</DestinationAddress>\n\t\t\t\t\t<Payment>\n\t\t\t\t\t\t<PayorType>SENDER</PayorType>\n\t\t\t\t\t</Payment>\n\t\t\t\t\t<PackageCount>1</PackageCount>\n\t\t\t\t\t<ListRate>%s</ListRate>\n\t\t\t\t</FDXRateRequest>\n\t\t\t", $this->_accountno, $this->_meterno, $this->_carriercode, $this->_dropofftype, $this->_service, $this->_packagingtype, $weight, $this->_originstate, $this->_originzip, $this->_origincountry, $this->_deststate, $this->_destzip, $this->_destcountry, $listRate);
     $result = PostToRemoteFileAndGetResponse($fx_url, $fx_xml);
     if ($result === false) {
         $valid_quote = false;
     } else {
         $valid_quote = true;
         $xml = @simplexml_load_string($result);
     }
     if (!$valid_quote || !is_object($xml)) {
         $this->SetError(GetLang('FedExBadResponse') . ' ' . isc_html_escape(print_r($result, true)));
         return false;
     }
     $netCharge = 0;
     if ($this->_ratetype == "list" && isset($xml->EstimatedCharges->ListCharges->NetCharge)) {
         $netCharge = $xml->EstimatedCharges->ListCharges->NetCharge;
     } elseif ($this->_ratetype == "account" && isset($xml->EstimatedCharges->DiscountedCharges->NetCharge)) {
         $netCharge = $xml->EstimatedCharges->DiscountedCharges->NetCharge;
     }
     if ($netCharge != 0) {
         $serviceType = $this->_deliverytypes[$this->_deliverytype] . ", " . $this->_servicetypes[$this->_service];
         $quote = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), (double) $netCharge, $serviceType);
         return $quote;
     } else {
         $Error = true;
         if (isset($xml->Error->Message)) {
             $this->SetError((string) $xml->Error->Message);
             return false;
         } else {
             $this->SetError(GetLang('FedExBadResponse') . ' ' . print_r($result, true));
             return false;
         }
     }
 }
Example #7
0
	public function VerifyOrderPayment()
	{
		if (empty($_POST['AccessPaymentCode'])) {
			return false;
		}

		$accessPaymentCode = $_POST['AccessPaymentCode'];

		$data = array(
			'CustomerID'		=> $this->GetValue('customerid'),
			'UserName'			=> $this->GetValue('username'),
			'AccessPaymentCode'	=> $accessPaymentCode,
		);

		$verifyUrl = $this->_ewayURL . 'Result?';
		$verifyUrl .= http_build_query($data);

		$response = PostToRemoteFileAndGetResponse($verifyUrl);

		if (empty($response)) {
			$this->logInvalidResponse($response);
			return false;
		}

		try {
			$xml = new SimpleXMLElement($response);
		}
		catch (Exception $ex) {
			$this->logInvalidResponse($response);
			return false;
		}

		$amount = (string)$xml->ReturnAmount;
		$orderId = (string)$xml->MerchantReference;
		$responseCode = (string)$xml->ResponseCode;
		$transactionId = (string)$xml->TrxnNumber;
		$transactionMessage = (string)$xml->TrxnResponseMessage;
		$transactionStatus = (string)$xml->TrxnStatus;
		$errorMessage = (string)$xml->ErrorMessage;

		$expectedAmount = number_format($this->GetGatewayAmount(), '2');

		$transactionLogDetails = array(
			'responseCode'		=> $responseCode,
			'transactionNumber'	=> $transactionId,
			'transactionMessage'=> $transactionMessage,
			'errorMessage'		=> $errorMessage,
		);

		// transaction failed or payment details don't match
		if ($transactionStatus == 'false' || $orderId != $this->GetCombinedOrderId() || $amount != $expectedAmount) {
			$GLOBALS['ISC_CLASS_LOG']->LogSystemError(
				array('payment', $this->GetName()),
				GetLang('EwayFailure', array('orderId' => $this->GetCombinedOrderId())),
				GetLang('EwayTransactionDetailsFailure', $transactionLogDetails)
			);

			$this->SetPaymentStatus(PAYMENT_STATUS_DECLINED);
			return false;
		}

		// set the payment status
		$updatedOrder = array(
			'ordpayproviderid' => $transactionId
		);

		$this->UpdateOrders($updatedOrder);

		$GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(
			array('payment', $this->GetName()),
			GetLang('EwaySuccess', array('orderId' => $this->GetCombinedOrderId())),
			GetLang('EwayTransactionDetailsSuccess', $transactionLogDetails)
		);
		$this->SetPaymentStatus(PAYMENT_STATUS_PAID);

		return true;
	}
 private function SaveUpdatedMailSettings()
 {
     $messages = array();
     if (isset($_POST['MailXMLPath']) && isset($_POST['MailXMLToken']) && isset($_POST['MailUsername'])) {
         $xml_path = $_POST['MailXMLPath'];
         $xml_token = $_POST['MailXMLToken'];
         $api_user = $_POST['MailUsername'];
         $xml = "<xmlrequest>\n\t\t\t\t\t\t\t<username>" . $api_user . "</username>\n\t\t\t\t\t\t\t<usertoken>" . $xml_token . "</usertoken>\n\t\t\t\t\t\t\t<requesttype>authentication</requesttype>\n\t\t\t\t\t\t\t<requestmethod>xmlapitest</requestmethod>\n\t\t\t\t\t\t\t<details>\n\t\t\t\t\t\t\t</details>\n\t\t\t\t\t\t</xmlrequest>";
         $xml = urlencode($xml);
         // Let's make sure the path is valid before enabling the XML API
         $result = PostToRemoteFileAndGetResponse($xml_path, "xml=" . $xml);
         $response = @simplexml_load_string($result);
         if (!is_object($response)) {
             $GLOBALS['MailXMLAPIValid'] = 0;
         }
         // We expect the response to contain SUCCESS - no point using XML to validate when we can do a string comparison
         if (is_numeric(isc_strpos(isc_strtoupper($result), "<STATUS>SUCCESS</STATUS>"))) {
             $GLOBALS['ISC_NEW_CFG']['MailXMLAPIValid'] = "1";
             $GLOBALS['ISC_NEW_CFG']['MailXMLPath'] = $_POST['MailXMLPath'];
             $GLOBALS['ISC_NEW_CFG']['MailXMLToken'] = $_POST['MailXMLToken'];
             $GLOBALS['ISC_NEW_CFG']['MailUsername'] = $_POST['MailUsername'];
         } else {
             $GLOBALS['ISC_NEW_CFG']['MailXMLAPIValid'] = "0";
             $GLOBALS['ISC_NEW_CFG']['MailXMLPath'] = "";
             $GLOBALS['ISC_NEW_CFG']['MailXMLToken'] = "";
             $GLOBALS['ISC_NEW_CFG']['MailUsername'] = "";
             $GLOBALS['ISC_NEW_CFG']['MailAutomaticallyTickNewsletterBox'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailAutomaticallyTickOrderBox'] = 0;
             // Was an error message returned?
             if (isset($response->errormessage)) {
                 $message = strval($response->errormessage);
                 if (isc_strtolower(trim($message)) != "invalid details") {
                     $messages[$message] = MSG_ERROR;
                 }
             }
         }
         // Are we capturing subscribers from the newsletter form?
         if (isset($_POST['UseMailAPIForNewsletters'])) {
             $GLOBALS['ISC_NEW_CFG']['UseMailerForNewsletter'] = 1;
             $GLOBALS['ISC_NEW_CFG']['MailNewsletterList'] = (int) $_POST['MailNewsletterList'];
             $GLOBALS['ISC_NEW_CFG']['MailNewsletterCustomField'] = (int) @$_POST['MailNewsletterCustomField'];
         } else {
             $GLOBALS['ISC_NEW_CFG']['UseMailerForNewsletter'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailNewsletterList'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailNewsletterCustomField'] = 0;
         }
         // Are we capturing subscribers for customers?
         if (isset($_POST['UseMailAPIForOrders'])) {
             $GLOBALS['ISC_NEW_CFG']['UseMailerForOrders'] = 1;
             $GLOBALS['ISC_NEW_CFG']['MailOrderList'] = (int) $_POST['MailOrderList'];
             $GLOBALS['ISC_NEW_CFG']['MailOrderFirstName'] = (int) @$_POST['MailOrderFirstName'];
             $GLOBALS['ISC_NEW_CFG']['MailOrderLastName'] = (int) @$_POST['MailOrderLastName'];
             $GLOBALS['ISC_NEW_CFG']['MailOrderFullName'] = (int) @$_POST['MailOrderFullName'];
             $GLOBALS['ISC_NEW_CFG']['MailOrderZip'] = (int) @$_POST['MailOrderZip'];
             $GLOBALS['ISC_NEW_CFG']['MailOrderCountry'] = (int) @$_POST['MailOrderCountry'];
             $GLOBALS['ISC_NEW_CFG']['MailOrderTotal'] = (int) @$_POST['MailOrderTotal'];
             $GLOBALS['ISC_NEW_CFG']['MailOrderPaymentMethod'] = (int) @$_POST['MailOrderPaymentMethod'];
             $GLOBALS['ISC_NEW_CFG']['MailOrderShippingMethod'] = (int) @$_POST['MailOrderShippingMethod'];
             $GLOBALS['ISC_NEW_CFG']['MailOrderListAutoSubscribe'] = (int) @$_POST['MailOrderListAutoSubscribe'];
         } else {
             $GLOBALS['ISC_NEW_CFG']['UseMailerForOrders'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailOrderList'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailOrderFirstName'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailOrderLastName'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailOrderFullName'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailOrderZip'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailOrderCountry'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailOrderTotal'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailOrderPaymentMethod'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailOrderShippingMethod'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailOrderListAutoSubscribe'] = 0;
         }
         // Are we showing product updates?
         if (isset($_POST['UseMailAPIForUpdates'])) {
             $GLOBALS['ISC_NEW_CFG']['UseMailAPIForUpdates'] = 1;
             $GLOBALS['ISC_NEW_CFG']['MailProductUpdatesListType'] = $_POST['MailProductUpdatesListType'];
         } else {
             $GLOBALS['ISC_NEW_CFG']['UseMailAPIForUpdates'] = 0;
             $GLOBALS['ISC_NEW_CFG']['MailProductUpdatesListType'] = "";
         }
         // Update the settings
         if ($this->CommitSettings($messages)) {
             if (GetConfig('MailXMLAPIValid')) {
                 if ($GLOBALS['CurrentTab'] == 0) {
                     $success_var = "MailAPIInitSuccess";
                 } else {
                     $success_var = "MailAPIIntegrationSuccess";
                 }
                 // Log this action
                 $GLOBALS['ISC_CLASS_LOG']->LogAdminAction();
                 $messages = array_merge(array(GetLang($success_var) => MSG_SUCCESS), $messages);
                 foreach ($messages as $message => $type) {
                     FlashMessage($message, $type);
                 }
                 header("Location: index.php?ToDo=viewMailSettings");
                 exit;
             } else {
                 $GLOBALS['ISC_NEW_CFG']['MailXMLPath'] = $_POST['MailXMLPath'];
                 $GLOBALS['ISC_NEW_CFG']['MailXMLToken'] = $_POST['MailXMLToken'];
                 $GLOBALS['ISC_NEW_CFG']['MailUsername'] = $_POST['MailUsername'];
                 $messages = array_merge(array(GetLang('MailAPIInitFailed') => MSG_ERROR), $messages);
                 foreach ($messages as $message => $type) {
                     FlashMessage($message, $type);
                 }
                 header("Location: index.php?ToDo=viewMailSettings");
                 exit;
             }
         } else {
             $messages = array_merge(array(GetLang('SettingsNotSaved') => MSG_ERROR), $messages);
             foreach ($messages as $message => $type) {
                 FlashMessage($message, $type);
             }
             header("Location: index.php?ToDo=viewMailSettings");
             exit;
         }
     } else {
         header("Location: index.php?ToDo=viewMailSettings");
         exit;
     }
 }
Example #9
0
		/**
		*	Load up an RSS feed, parse its contents and return it.
		*/
		public function _LoadFeed($FeedURL, $NumEntries=0, $CacheTime=0, $FeedId="", $RSSFeedSnippet="", $helpLinks = false)
		{
			$reload = true;
			if($CacheTime > 0) {
				if($FeedId != "") {
					$FeedID = md5($FeedURL);
				}
				$reload = false;
				if(!is_dir(ISC_BASE_PATH."/cache/feeds")) {
					isc_mkdir(ISC_BASE_PATH."/cache/feeds/");
				}
				// Using a cached version that hasn't expired yet
				if(file_exists(ISC_BASE_PATH."/cache/feeds/".$FeedId) && filemtime(ISC_BASE_PATH."/cache/feeds/".$FeedId) > time()-$CacheTime) {
					$contents = file_get_contents(ISC_BASE_PATH."/cache/feeds/".$FeedId);
					// Cache was bad, recreate
					if(!$contents) {
						$reload = true;
					}
				}
				else {
					$reload = true;
				}
			}

			if ($reload === true) {
				$contents = PostToRemoteFileAndGetResponse($FeedURL);
				// Do we need to cache this version?
				if ($CacheTime > 0 && $contents != "") {
					@file_put_contents(ISC_BASE_PATH."/cache/feeds/".$FeedId, $contents);
				}
			}

			$output = "";
			$count = 0;

			// Could not load the feed, return an error
			if(!$contents) {
				return false;
			}


			// Silence errors to not polute out logs with peoples invalid XML feeds
			if($xml = @simplexml_load_string($contents)) {
				require_once(ISC_BASE_PATH . "/lib/xml.php");

				$rss = new ISC_XML();
				$entries = $rss->ParseRSS($xml);

				foreach($entries as $entry) {
					$GLOBALS['RSSTitle'] = $entry['title'];
					$GLOBALS['RSSDescription'] = $entry['description'];
					$GLOBALS['RSSLink'] = $entry['link'];

					if ($RSSFeedSnippet != "") {
						if ($helpLinks) {
							preg_match('#/questions/([0-9]+)/#si', $entry['link'], $matches);
							if (!empty($matches)) {
								$GLOBALS['RSSLink'] = $matches[1];
							}
						}
						if(defined('ISC_ADMIN_CP')) {
							$output .= Interspire_Template::getInstance('admin')->render('Snippets/'.$RSSFeedSnippet.'.html');
						}
						else {
							$output .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet($RSSFeedSnippet);
						}
					} else {
						if(defined('ISC_ADMIN_CP')) {
							$output .= Interspire_Template::getInstance('admin')->render('Snippets/PageRSSItem.html');
						}
						else {
							$output .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("PageRSSItem");
						}
					}

					if($NumEntries > 0 && ++$count >= $NumEntries) {
						break;
					}
				}

				return $output;
			}
			else {
				return false;
			}
		}
 /**
  * DownloadAddonZip
  * Download the zip file for the license and extract it
  *
  * @return Void
  */
 private function DownloadAddonZip()
 {
     $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->LoadLangFile('addons');
     if (!isset($_REQUEST['key']) && !isset($_REQUEST['prodId'])) {
         exit;
     }
     if (isset($_REQUEST['prodId'])) {
         $url = GetConfig('AddonStreamURL') . '?prodId=' . (int) $_REQUEST['prodId'];
     } else {
         $key = $_REQUEST['key'];
         $url = GetConfig('AddonStreamURL') . '?key=' . str_replace("+", "%2B", urlencode($key)) . '&h=' . base64_encode(urlencode($_SERVER['HTTP_HOST']));
     }
     $zip = PostToRemoteFileAndGetResponse($url);
     if (strlen($zip) > 0) {
         // Save the zip file to a temporary file in the cache folder which is writable
         $cache_path = realpath(ISC_BASE_PATH . "/cache/");
         if (is_writable($cache_path)) {
             $temp_file = $cache_path . "/addon_" . rand(1, 100000) . ".zip";
             if ($fp = fopen($temp_file, "wb")) {
                 if (fwrite($fp, $zip)) {
                     fclose($fp);
                     // Is the addons folder writable?
                     $addon_path = realpath(ISC_BASE_PATH . "/addons/");
                     if (is_writable($addon_path)) {
                         // Try to extract the zip to the addons folder
                         Getlib('class.zip');
                         $archive = new PclZip($temp_file);
                         if ($archive->extract(PCLZIP_OPT_PATH, $addon_path) == 0) {
                             // The unzipping failed
                             echo GetLang("AddonUnzipFailed");
                         } else {
                             // The unzip was successful
                             echo "success";
                             $GLOBALS['ISC_CLASS_LOG']->LogAdminAction();
                         }
                         // Remove the temporary zip file
                         unlink($temp_file);
                     } else {
                         echo GetLang("AddonFolderNotWritable");
                     }
                 } else {
                     echo GetLang("AddonTempFolderNotWritable");
                 }
             } else {
                 echo GetLang("AddonTempFolderNotWritable");
             }
         } else {
             echo GetLang("AddonTempFolderNotWritable");
         }
     } else {
         echo GetLang("AddonDownloadZipFailed");
     }
 }
Example #11
0
/**
 * XML API Example: Make sure the user has access to the API
 * Returns the user's ID if successful
 */
$xml = "<xmlrequest>\n\t\t<username>fred</username>\n\t\t<usertoken>9baa79a5871a2bdaac7b437a5b7275a8daff88d9</usertoken>\n\t\t<requesttype>authentication</requesttype>\n\t\t<requestmethod>xmlapitest</requestmethod>\n\t\t<details>\n\t\t</details>\n\t</xmlrequest>";
/**
 * XML API Example: Get a list of completed orders
 * where any field contains interspire.com
 */
$xml = "<xmlrequest>\n\t\t<username>fred</username>\n\t\t<usertoken>9baa79a5871a2bdaac7b437a5b7275a8daff88d9</usertoken>\n\t\t<requesttype>orders</requesttype>\n\t\t<requestmethod>GetOrders</requestmethod>\n\t\t<details>\n\t\t\t<searchQuery>@interspire.com</searchQuery>\n\t\t</details>\n\t</xmlrequest>";
/**
 * XML API Example: Get a list of completed orders
 * that were placed in the last week where the total
 * amount of the order is $200 or more and any field
 * contains the search phrase "seinfield"
 */
$xml = "<xmlrequest>\n\t\t<username>john</username>\n\t\t<usertoken>9baa79a5871a2bdaac7b437a5b7275a8daff88d9</usertoken>\n\t\t<requesttype>orders</requesttype>\n\t\t<requestmethod>GetOrders</requestmethod>\n\t\t<details>\n\t\t\t<dateRange>week</dateRange>\n\t\t\t<totalFrom>200</totalFrom>\n\t\t\t<searchQuery>seinfield</searchQuery>\n\t\t</details>\n\t</xmlrequest>";
/**
 * XML API Example: Get a list of customers from America where
 * any field contains "@interspire.com". Countries are defined
 * along with their numeric ID's in the countries table
 */
$xml = "<xmlrequest>\n\t\t<username>fred</username>\n\t\t<usertoken>9baa79a5871a2bdaac7b437a5b7275a8daff88d9</usertoken>\n\t\t<requesttype>customers</requesttype>\n\t\t<requestmethod>GetCustomers</requestmethod>\n\t\t<details>\n\t\t\t\t<searchQuery>@interspire.com</searchQuery>\n\t\t\t\t<country>226</country>\n\t\t</details>\n\t</xmlrequest>";
/**
 * XML API Example: Get a list of products where the product name contains the
 * word "laserjet" and the price is under $1,000
 */
$xml = "<xmlrequest>\n\t\t<username>admin</username>\n\t\t<usertoken>a6e1efb0f8b737dc92801e9cbe0b355482af1c94</usertoken>\n\t\t<requesttype>products</requesttype>\n\t\t<requestmethod>GetProducts</requestmethod>\n\t\t<details>\n\t\t\t<priceTo>1000</priceTo>\n\t\t</details>\n\t</xmlrequest>";
//header("Content-Type:text/xml");
echo PostToRemoteFileAndGetResponse("http://127.0.0.1/xml.php", $xml);
Example #12
0
 /**
  * Retrieve a license key for a trial installation of Interspire Shopping Cart.
  *
  * @return string The license key.
  */
 private function GetTrialLicenseKey()
 {
     // Already tried to install, no need to fetch the license key again
     if (isset($_SESSION['LK' . md5(strtolower($_POST['ShopPath']))])) {
         return $_SESSION['LK' . md5(strtolower($_POST['ShopPath']))];
     }
     // First we need to fetch the license key from Interspire
     $licenseRequest = array('licenserequest' => array('product' => 'isc', 'customer' => array('name' => $_POST['FullName'], 'email' => $_POST['UserEmail'], 'url' => $_POST['ShopPath'], 'phone' => $_POST['PhoneNumber'], 'country' => GetCSVCountryNameById($_POST['StoreCountryLocationId'])), 'aps' => 'true'));
     // Send the XML request off to the remote server
     $licenseUrl = 'http://partner.interspire.com/gettriallicense.php';
     // Send the XML request off to the remote server
     $response = PostToRemoteFileAndGetResponse($licenseUrl, $this->BuildXMLFromArray($licenseRequest));
     $xml = @simplexml_load_string($response);
     if ($response === false || !is_object($xml)) {
         $this->ShowInstallErrors('There was a problem communicating with the Interspire licensing server. Please try again in a few moments.', $errors, false, false);
         exit;
     }
     // Got a valid license key
     if ($xml->status == "OK") {
         $_SESSION['LK' . md5(strtolower($_POST['ShopPath']))] = (string) $xml->licensekey;
         return (string) $xml->licensekey;
     } else {
         $this->ShowInstallErrors('There was a problem retrieving your license key. Please try again in a few moments. (Error: ' . $xml->error . ')', $errors, false, false);
         exit;
     }
 }
Example #13
0
		private function GetQuote()
		{

			// The following array will be returned to the calling function.
			// It will contain at least one ISC_SHIPPING_QUOTE object if
			// the shipping quote was successful.

			$cp_quote = array();

			// Connect to Canada Post to retrieve a live shipping quote
			$items = "";
			$result = "";
			$valid_quote = false;
			$cp_url = "http://sellonline.canadapost.ca:30000?";
			$readytoship = '';
			if($this->_readytoship == 'yes') {
				$readytoship = "<readyToShip/>";
			}

			foreach($this->_products as $product) {
				$items .= sprintf("<item>
								<quantity>%d</quantity>
								<weight>%s</weight>
								<length>%s</length>
								<width>%s</width>
								<height>%s</height>
								<description><![CDATA[%s]]></description>
								%s
						</item>",
						$product->getquantity(),
						ConvertWeight($product->GetWeight(), 'kgs'),
						ConvertLength($product->getlength(), "cm"),
						ConvertLength($product->getwidth(), "cm"),
						ConvertLength($product->getheight(), "cm"),
						$product->getdesc(),
						$readytoship
						);
			}

			$cp_xml = sprintf("<" . "?" . "xml version=\"1.0\" ?" . ">
				<eparcel>
						<language>en</language>
						<ratesAndServicesRequest>
								<merchantCPCID>%s</merchantCPCID>
								<fromPostalCode>%s</fromPostalCode>
								<lineItems>
									%s
							   </lineItems>
								<city></city>
								<provOrState>%s</provOrState>
								<country>%s</country>
								<postalCode>%s</postalCode>
						</ratesAndServicesRequest>
				</eparcel>
			", $this->_merchantid, $this->_origin_zip, $items, $this->_deststate, isc_strtoupper($this->_destcountry), $this->_destzip);

			$post_vars = implode("&",
			array("XMLRequest=$cp_xml"
				)
			);

			$result = PostToRemoteFileAndGetResponse($cp_url, $post_vars);
			if($result) {
				$valid_quote = true;
			}

			if(!$valid_quote) {
				$this->SetError(GetLang('CanadaPostOpenError'));
				return false;
			}
			$xml = @simplexml_load_string($result);

			if(!is_object($xml)) {
				$this->SetError(GetLang('CanadaPostBadResponse'));
				return false;
			}

			if(isset($xml->error)) {
				$this->SetError((string)$xml->error->statusMessage);
				return false;
			}

			if(isset($xml->ratesAndServicesResponse)) {
				foreach($xml->ratesAndServicesResponse->product as $ship_method) {
					// Calculate the transit time
					$transit_time = -1;

					$today = $ship_method->shippingDate;
					$arr_today = explode("-", $today);
					$today_stamp = mktime(0, 0, 0, $arr_today[1], $arr_today[2], $arr_today[0]);

					$delivered = $ship_method->deliveryDate;
					$arr_delivered = explode("-", $delivered);

					if(count($arr_delivered) == 3) {
						$delivered_stamp = mktime(0, 0, 0, $arr_delivered[1], $arr_delivered[2], $arr_delivered[0]);
						$transit_time = $delivered_stamp - $today_stamp;

						// Convert transit time to days
						$transit_time = floor($transit_time/60/60/24);
					}

					$quote = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), (float)$ship_method->rate, (string)$ship_method->name, $transit_time);
					$cp_quote[] = $quote;
				}
			}
			return $cp_quote;
		}
    /**
     * GetDownloadableAddons
     * Query Interspire.com for a list of available addons
     *
     * @param Array $ExistingAddons An array of addons which have already been installed
     * @return String
     */
    public function GetDownloadableAddons($ExistingAddons)
    {
        $result = PostToRemoteFileAndGetResponse(GetConfig('AddonXMLFile'));
        $xml = new SimpleXMLElement($result);
        $output = "";
        foreach ($xml->addon as $addon) {
            // Have they already downloaded this addon?
            if (!in_array(str_replace("isc_", "", $addon->prodCode), $ExistingAddons)) {
                if ((int) $addon->prodPrice == 0) {
                    $button_text = GetLang("DownloadAddonFree");
                } else {
                    $button_text = sprintf(GetLang("DownloadAddonPaid"), number_format($addon->prodPrice));
                }
                $output .= sprintf('<div style="text-align: center; float:left; margin-right:10px">
									<a href="%s" target="_blank"><img src="%s" width="200" height="92" border="0" /></a>
									<div style="padding-top:10px; width:250px">
										%s (<a target="_blank" href="%s">%s</a>)<br /><br />
										<input type="button" value="%s" onclick="tb_show(\'\', \'index.php?ToDo=purchaseDownloadAddons&prodId=%d&prodPrice=%s&width=300&height=255\')" /><br />
									</div>
								</div>', $addon->prodAddonLink, $addon->prodAddonLogo, $addon->prodAddonSummary, $addon->prodAddonLink, GetLang("AddonMoreInfo"), $button_text, $addon->pk_prodId, $addon->prodPrice);
            }
        }
        return $output;
    }
	/**
	* Retrive the GWO Scripts from Google and save in an array
	*
	* @param string $path, the Google install script path
	* @param string $errorMessage
	*
	* return array
	*/
	private function retriveInstallScripts($path, &$errorMessage)
	{
		$resultXml = PostToRemoteFileAndGetResponse($path);
		if(!$resultXml) {
			$errorMessage = GetLang('ProblemRetrivingScript');
			return array();
		}
		$result = @simplexml_load_string($resultXml);
		$result = (array) $result;

		$scripts = array();
		if(isset($result['install-scripts'])) {
			foreach($result['install-scripts'] as $scriptName => $script) {
				//if it's a shared ssl, it's a cross domain tracking
				if(GetConfig('UseSSL') == 2) {
					switch($scriptName) {
						case 'control-script':
							$script = '<script>_udn = "none";</script>'.$script;
							break;
						case 'test-tracking-script':
						case 'goal-tracking-script':
							$replaceString = 'gwoTracker._setDomainName("none");
gwoTracker._setAllowLinker(true);
gwoTracker._trackPageview';

							$script = str_replace('gwoTracker._trackPageview', $replaceString, $script);
							break;
					}
				}
				$scripts[$scriptName] = trim((string)$script);
			}
		}

		// check if the scripts we need are saved in the array,
		if(empty($scripts)) {
			$errorMessage = GetLang('ProblemRetrivingScript');
			return array();
		}
		return $scripts;
	}
Example #16
0
 private function GetQuote()
 {
     $packages = $this->BuildPackages();
     $shippingCharge = 0;
     $transitTime = 0;
     // Set the description of the method
     $description = "";
     // Load up the module variables
     $this->SetCustomVars();
     foreach ($this->_variables['deliverytypes']['options'] as $k => $v) {
         if ($v == $this->_deliverytype) {
             $description = $k;
         }
     }
     // Now loop through all of the packages we'll be sending
     foreach ($packages as $package) {
         // Convert the dimensions, and convert the weight to grams
         $height = ConvertLength($package['height'], 'mm');
         $length = ConvertLength($package['length'], 'mm');
         $width = ConvertLength($package['width'], 'mm');
         $weight = ConvertWeight($package['weight'], 'grams');
         // minimum dimensions for auspost drc is 50x50x30
         if ($height < 50) {
             $height = 50;
         }
         if ($length < 50) {
             $length = 50;
         }
         if ($width < 30) {
             $width = 30;
         }
         $data = array();
         // Connect to Australia Post to retrieve a live shipping quote
         $validQuote = false;
         $ausPostURL = 'http://drc.edeliver.com.au/ratecalc.asp?';
         $postVars = array('Height' => $height, 'Length' => $length, 'Width' => $width, 'Weight' => $weight, 'Quantity' => 1, 'Pickup_Postcode' => $this->_originzip, 'Destination_Postcode' => $this->_destzip, 'Country' => $this->_destcountry, 'Service_Type' => $this->_deliverytype);
         $postRequest = '';
         foreach ($postVars as $k => $v) {
             $postRequest .= '&' . $k . '=' . urlencode($v);
         }
         $postRequest = ltrim($postRequest, '&');
         $result = PostToRemoteFileAndGetResponse($ausPostURL, $postRequest);
         if ($result !== false) {
             $result = str_replace("\n", "&", $result);
             $result = str_replace("\r", "", $result);
             $result = rtrim($result, '&');
             parse_str($result, $data);
             if (isset($data['charge']) && isset($data['days']) && isset($data['err_msg']) && $data['err_msg'] == "OK") {
                 $shippingCharge += $data['charge'];
                 $transitTime = max($transitTime, $data['days']);
             } else {
                 if (isset($data['err_msg'])) {
                     $this->SetError($data['err_msg']);
                     return false;
                 } else {
                     $this->SetError(GetLang('AusPostOpenError'));
                     return false;
                 }
             }
         } else {
             $this->SetError(GetLang('AusPostOpenError'));
             return false;
         }
     }
     // OK, so create the actual quote
     $packageCount = '';
     if (count($packages) > 1) {
         $packageCount = count($packages) . ' x ';
     }
     $quote = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), number_format($shippingCharge, 2), $packageCount . $description, $transitTime);
     return $quote;
 }
Example #17
0
	/**
	* Downloads image from picnik (or can be used for any url, really) and stores it at a file named $destination -- primarily a wrapper for PostToRemoteFileAndGetResponse with built-in file writing and error handling
	*
	* @param string $url
	* @param string $destination (optional)
	* @return string|bool Returns the filename the image was saved to, or false if anything went wrong
	*/
	public function downloadToFile($url, $destination = false, &$errorType = null)
	{
		$result = PostToRemoteFileAndGetResponse($url);

		if (!$destination) {
			// generate a random name for our downloaded file and store it in cache dir
			while (true) {
				// we can name it .tmp because the extension will be corrected after the image type is detected
				$destination = ISC_CACHE_DIRECTORY . 'picnikimage_' . Interspire_String::generateRandomString(16) . '.tmp';

				if (!file_exists($destination)) {
					break;
				}
			}
		}

		$fh = fopen($destination, 'wb');
		if ($fh) {
			if (!fwrite($fh, $result)) {
				fclose($fh);
				$this->log->LogSystemError('general', 'Failed to write downloaded Picnik image to local file');
				$errorType = 1;
				return false;
			}
			fclose($fh);
			isc_chmod($destination, ISC_WRITEABLE_FILE_PERM); // set the chmod just incase this was a new file
		} else {
			$this->log->LogSystemError('general', 'Failed to open local file for saving downloaded Picnik image');
			$errorType = 2;
			return false;
		}

		return $destination;
	}
Example #18
0
		protected function _Handle3DCallBackResponse()
		{
			if ($this->GetValue("testmode") == "TEST") {
				$callbackUrl = $this->_test3DSecureURL;
			}
			else if ($this->GetValue("testmode") == "LIVE") {
				$callbackUrl = $this->_live3DSecureURL;
			}
			else if ($this->GetValue("testmode") == "SIMULATOR") {
				$callbackUrl = $this->_similator3DSecureURL;
			}

			$postVars = "MD=" . $_REQUEST['MD'] . "&PARes=" . urlencode($_REQUEST['PaRes']);
			$result = PostToRemoteFileAndGetResponse($callbackUrl, $postVars);

			if($this->_HandleResponse($result)) {
				$orderStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
			} else {
				$orderStatus = ORDER_STATUS_DECLINED;
			}
			return $orderStatus;
		}
Example #19
0
	public function getDownloadableTemplates()
	{
		if(getConfig('DisableTemplateDownloading')) {
			return '';
		}

		// Get the list of currently installed templates
		$existingTemplates = $this->_GetTemplateList();
		$numExisting = count($existingTemplates);

		$templateCacheFile = ISC_CACHE_DIRECTORY . '/remote_templates.xml';
		$cacheContent = '';
		if(!file_exists($templateCacheFile) || filemtime($templateCacheFile) < time() - 86400) {
			// Fetch the list of available templates for this version
			$url = $this->BuildTemplateURL($GLOBALS['ISC_CFG']['TemplateURL'], array(
				"version" => PRODUCT_VERSION_CODE
			));

			// Send off a request to the remote server to get a list of available logos
			$templateXML = PostToRemoteFileAndGetResponse($url);

			// A remote connection couldn't be established
			if($templateXML === null || $templateXML === false) {
				return false;
			}

			file_put_contents($templateCacheFile, $templateXML);
			isc_chmod($templateCacheFile, ISC_WRITEABLE_FILE_PERM);
		}
		else {
			$templateXML = file_get_contents($templateCacheFile);
		}

		try {
			$xml = new SimpleXMLElement($templateXML);
		}
		catch(Exception $e) {
			return false;
		}

		if(empty($xml->template)) {
			return false;
		}

		$templateList = array();
		foreach($xml->template as $template) {
			$templateId = (string)$template->id;
			$templateName = (string)$template->name;

			// Don't show this template if we already have it installed
			if(in_array($templateId, $existingTemplates)) {
				continue;
			}

			foreach($template->colors->color as $color) {
				$templateList[] = array(
					'template' => $templateId,
					'templateName' => $templateName,
					'templateColor' => (string)$color->name,
					'preview' => (string)$color->preview,
					'previewFull' => (string)$color->previewFull,
					'installed' => false
				);
			}
		}

		return $templateList;
	}
Example #20
0
		/**
		* _ParseIncludes
		* Parse any includes in the template and insert the required data
		*
		* @return string The template with includes parsed in it
		*/
		private function _ParseIncludes()
		{
			// Parse out all of the panels in the template
			$tplData = $this->_GetTemplate();
			$matches = array();

			if (!isset($this->_tplName)) {
				// No template name specified
				trigger_error(sprintf("%s", $GLOBALS[$this->langVar]["errNoTemplateNameSpecified"]), E_USER_WARNING);
				return $tplData;
			}

			// Parse out the panel tokens in the template file

			preg_match_all("`(?siU)(%%Include.(.*)%%)`", $tplData, $matches);
			$includeRoot = ISC_BASE_PATH . '/templates/__includes/';
			foreach ($matches[0] as $key => $k) {
				$pattern1 = $k;
				$pattern2 = str_replace("%", "", $pattern1);
				$pattern2 = str_replace("Include.", "", $pattern2);
				$localPath = realpath($includeRoot . $pattern2);
				if (strpos($pattern2, "http://") === 0) {
					// Trick the site into thinking it a regular user as some sites stop
					// other servers from taking files
					ini_set('user_agent', $this->userAgent);
					$includeData = PostToRemoteFileAndGetResponse($pattern2);
				}
				else if($localPath && file_exists($localPath) && strpos($localPath, $includeRoot) !== false) {
					// Must be in the root folder
					$includeData = file_get_contents(ISC_BASE_PATH . '/' . $pattern2);
				}
				else {
					continue;
				}
				$tplData = str_replace($pattern1, $includeData, $tplData);
			}
			return $tplData;
		}
Example #21
0
		/**
		 * Process and validate input from a payment form for this provider.
		 *
		 * @return boolean True if valid details and payment has been processed. False if not.
		 */
		public function ProcessPaymentForm($dataSource = array())
		{
			if (empty($dataSource)) {
				$dataSource = $_POST;
			}

			$result = "";
			$error = false;

			$orders = $this->GetOrders();
			list(,$order) = each($orders);

			if(isset($dataSource['eway_name']) && isset($dataSource['eway_ccno']) && isset($dataSource['eway_ccexpm']) && isset($dataSource['eway_ccexpy'])) {
				$ccname = $dataSource['eway_name'];
				$ccnum = $dataSource['eway_ccno'];
				$ccexpm = $dataSource['eway_ccexpm'];
				$ccexpy = $dataSource['eway_ccexpy'];

				if ($this->GetValue('requirecvn') == 'YES' && isset($dataSource['eway_cvn'])) {
					$cvn = $dataSource['eway_cvn'];
				} else {
					$cvn = '';
				}

				$billingDetails = $this->GetBillingDetails();

				// Load the pending order
				$total = number_format($this->GetGatewayAmount(), 2, '.', '');

				// Multiply the total by 100 because it's in cents
				$total *= 100;

				// Load the eWay customer ID
				$eway_id = $this->GetValue("customerid");

				// Is eWay setup in test or live mode?
				if($this->GetValue('testmode') == 'YES') {
					if($this->GetValue('requirecvn') == 'YES') {
						$eWayUrl = 'https://www.eway.com.au/gateway_cvn/xmltest/testpage.asp';
					}
					else {
						$eWayUrl = 'https://www.eway.com.au/gateway/xmltest/testpage.asp';
					}

					// If we're in test mode them "hard code" the eWay customer ID and total to one that works in test mode
					$eway_id = "87654321";
					$ccnum = "4444333322221111";
				}
				else {
					if($this->GetValue('requirecvn') == 'YES') {
						$eWayUrl = 'https://www.eway.com.au/gateway_cvn/xmlpayment.asp';
					}
					else {
						$eWayUrl = 'https://www.eway.com.au/gateway/xmlpayment.asp';
					}
				}

				$order_desc = sprintf(GetLang('YourOrderFrom'), $GLOBALS['StoreName']);

				// Build the XML for the shipping quote
				$xml = new SimpleXMLElement("<ewaygateway/>");
				$xml->addChild('ewayCustomerID', $eway_id);
				$xml->addChild('ewayTotalAmount', $total);
				$xml->addChild('ewayCustomerFirstName', $billingDetails['ordbillfirstname']);
				$xml->addChild('ewayCustomerLastName', $billingDetails['ordbilllastname']);
				$xml->addChild('ewayCustomerEmail', $billingDetails['ordbillemail']);
				$xml->addChild('ewayCustomerAddress', trim($billingDetails['ordbillstreet1'] . " " . $billingDetails['ordbillstreet2']));
				$xml->addChild('ewayCustomerPostcode', $billingDetails['ordbillzip']);
				$xml->addChild('ewayCustomerInvoiceDescription', $order_desc);
				$xml->addChild('ewayCustomerInvoiceRef', $_COOKIE['SHOP_ORDER_TOKEN']);
				$xml->addChild('ewayCardHoldersName', $ccname);
				$xml->addChild('ewayCardNumber', $ccnum);
				$xml->addChild('ewayCardExpiryMonth', $ccexpm);
				$xml->addChild('ewayCardExpiryYear', $ccexpy);

				if ($this->GetValue('requirecvn') == 'YES') {
					$xml->addChild('ewayCVN', $cvn);
				}
				else {
					$xml->addChild('ewayCVN', '');
				}
				$xml->addChild('ewayTrxnNumber', $order['orderid']);
				$xml->addChild('ewayOption1', '');
				$xml->addChild('ewayOption2', '');
				$xml->addChild('ewayOption3', '');
				$ewayXML = $xml->asXML();

				$result = PostToRemoteFileAndGetResponse($eWayUrl, $ewayXML);

				if($result === false || $result == null) {
					$this->SetError("An error occured while trying to contact eWay.");
					return false;
				}

				// We received a response from eWay, let's see what it was
				try {
				$xml = new SimpleXMLElement($result);
				} catch (Exception $e) {
					$this->SetError("An error occured with the response from eWay.");
					return false;
				}


				$order_total = (string)$total;
				$eway_amount = (string)$xml->ewayReturnAmount;

				if((string)$xml->ewayTrxnStatus == "True") {
					// The transaction was successful

					$this->SetPaymentStatus(PAYMENT_STATUS_PAID);

					$ewayTransactionId = (string)$xml->ewayTrxnNumber;
					$updatedOrder = array(
						'ordpayproviderid'	=> $ewayTransactionId,
					);
					$this->UpdateOrders($updatedOrder);

					$GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), GetLang('EWayLogSuccess'));

					return true;
				}
				else {
					// Something went wrong, show the error message with the credit card form
					$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('EWayLogErrorGeneral'), sprintf(GetLang('EWayLogErrorGeneralDesc'), $order['orderid'], (string)$xml->ewayTrxnError));
					$this->SetError(GetLang('EWayProcessingError'));
					return false;
				}
			}
			else {
				// Bad form details, try again
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('EWayLogErrorGeneral'), sprintf(GetLang('EWayLogErrorGeneralDesc'), $order['orderid'], (string)$xml->ewayTrxnError));
				$this->SetError(GetLang('EWayProcessingError'));
				return false;
			}
		}
Example #22
0
    /**
     * Check for new templates to download.
     */
    public function CheckDownloadTemplates()
    {
        $GLOBALS['TemplateGrid'] = '';
        $numNew = 0;
        $numExisting = 0;
        // Get the list of currently installed templates
        $existingTemplates = $this->_GetTemplateList();
        $numExisting = count($existingTemplates);
        // Fetch the list of available templates for this version
        $url = $this->BuildTemplateURL($GLOBALS['ISC_CFG']['TemplateURL'], array("version" => PRODUCT_VERSION_CODE));
        // Send off a request to the remote server to get a list of available logos
        $response = PostToRemoteFileAndGetResponse($url);
        // A remote connection couldn't be established
        if ($response === null || $response === false) {
            $GLOBALS['NewTemplateIntro'] = GetLang('NoNewTemplates');
            return false;
        }
        $templateXML = @simplexml_load_string($response);
        if (!is_object($templateXML)) {
            $GLOBALS['NewTemplateIntro'] = GetLang('NoNewTemplates');
            return false;
        }
        // Loop through the available templates
        foreach ($templateXML->template as $template) {
            $templateId = strval($template->id);
            // Don't show this template if we already have it installed
            if (in_array($templateId, $existingTemplates)) {
                continue;
            }
            $templateName = strval($template->name);
            $GLOBALS['TemplateId'] = $templateId;
            $GLOBALS['Name'] = $templateName;
            if (GetConfig('AllowTemplatePurchase') == 1) {
                // Purchase support needs to go in here
            }
            if (isset($template->price) && strval($templae->price) > 0) {
                if (GetConfig('TemplateMarkup') < 1) {
                    $GLOBALS['ISC_CFG']['TemplateMarkup'] = 1;
                }
                $GLOBALS['ButtonText'] = GetLang('DownloadTemplate') . ' ($' . round($template->price * GetConfig('TemplateMarkup'), 2) . ' USD)';
                $GLOBALS['PopupWidth'] = '300';
                $GLOBALS['PopupHeight'] = '250';
            } else {
                $GLOBALS['ButtonText'] = GetLang('DownloadTemplate') . ' (Free)';
                if (strpos('MSIE 6', $_SERVER['HTTP_USER_AGENT']) !== false) {
                    //using ie6!
                    $GLOBALS['PopupWidth'] = '290';
                    $GLOBALS['PopupHeight'] = '75';
                } else {
                    $GLOBALS['PopupWidth'] = '240';
                    $GLOBALS['PopupHeight'] = '58';
                }
            }
            $GLOBALS['ColorList'] = '';
            $firstColor = null;
            foreach ($template->colors->color as $color) {
                $colorHex = strval($color->hex);
                $colorName = strval($color->name);
                if ($firstColor === null) {
                    $GLOBALS['DefaultPreviewImageFull'] = strval($color->previewFull);
                    $GLOBALS['DefaultPreviewImageSmall'] = strval($color->preview);
                    $firstColor = $colorHex;
                }
                $GLOBALS['ColorList'] .= '
					<img src="images/blank.gif" width="12" height="12" style="cursor: pointer; background: ' . $colorHex . '; margin-right: 2px; margin-top: 5px; border: 1px solid black;" title="' . $colorName . '" onclick="javascript: ChangeTemplateColor(this, \'' . strval($color->preview) . '\', \'' . strval($color->previewFull) . '\');" />
				';
            }
            $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate('downloadernew.manage.row');
            $templateCode = $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
            $GLOBALS['TemplateGrid'] .= '<div class="TemplateBox" id="dl_' . $templateId . '">' . $templateCode . '</div>';
            ++$numNew;
        }
        if ($numNew > 0) {
            $GLOBALS['NumNew'] = $numNew;
            if ($numNew == 1) {
                $GLOBALS['NewTemplateIntro'] = sprintf(GetLang('NewTemplateIntro1'), $numNew);
            } else {
                $GLOBALS['NewTemplateIntro'] = sprintf(GetLang('NewTemplateIntro2'), $numNew);
            }
        } else {
            $GLOBALS['NumNew'] = 0;
            $GLOBALS['DisplayGrid'] = 'none';
            $GLOBALS['NewTemplateIntro'] = GetLang('NoNewTemplates');
        }
    }
 protected function ProcessImg()
 {
     $sql = "select * from [|PREFIX|]import_products where flag=0 order by tempid asc";
     $query = $GLOBALS['ISC_CLASS_DB']->Query($sql);
     while ($record = $GLOBALS['ISC_CLASS_DB']->Fetch($query)) {
         // Do we have a product file? We need to deal with it now damn it!
         if (isset($record['product_file']) && $record['product_file'] != '') {
             // Is this a remote file?
             $downloadDirectory = ISC_BASE_PATH . "/" . GetConfig('DownloadDirectory');
             if (isc_substr(isc_strtolower($record['product_file']), 0, 7) == "http://") {
                 // Need to fetch the remote file
                 $file = PostToRemoteFileAndGetResponse($record['product_file']);
                 if ($file) {
                     // Place it in our downloads directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir($downloadDirectory . $randomDir)) {
                         if (!@mkdir($downloadDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $fileName = $randomDir . "/" . GenRandFileName(basename($record['product_file']));
                     if (!@file_put_contents($downloadDirectory . "/" . $fileName, $file)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductFileUnableToMove');
                     } else {
                         $productFiles[] = array("prodhash" => "", "downfile" => $fileName, "downdateadded" => time(), "downmaxdownloads" => 0, "downexpiresafter" => 0, "downfilesize" => filesize($downloadDirectory . "/" . $fileName), "downname" => basename($record['product_file']), "downdescription" => "");
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductFileDoesntExist');
                 }
             } else {
                 // This file exists, can be imported
                 if (file_exists($downloadDirectory . "/import/" . $record['product_file'])) {
                     // Move it to our images directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir("../" . $downloadDirectory . "/" . $randomDir)) {
                         if (!@mkdir($downloadDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $fileName = $randomDir . "/" . GenRandFileName($record['product_file']);
                     if (!@copy($downloadDirectory . "/import/" . $record['product_file'], $downloadDirectory . "/" . $fileName)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductFileUnableToMove');
                     } else {
                         $productFiles[] = array("prodhash" => "", "downfile" => $fileName, "downdateadded" => time(), "downmaxdownloads" => 0, "downexpiresafter" => 0, "downfilesize" => filesize($downloadDirectory . "/" . $fileName), "downname" => basename($record['product_file']), "downdescription" => "");
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductFileDoesntExist');
                 }
             }
         }
         // Do we have an image? We need to deal with it before we do anything else
         $productImages = array();
         if (isset($record['product_images']) && $record['product_images'] != '') {
             // Is this a remote file?
             $imageDirectory = ISC_BASE_PATH . "/" . GetConfig('ImageDirectory');
             if (isc_substr(isc_strtolower($record['product_images']), 0, 7) == "http://") {
                 // Need to fetch the remote file
                 $image_pieces = preg_split("/[;,]/", $record['product_images']);
                 $end = end($image_pieces);
                 if (empty($end)) {
                     array_pop($image_pieces);
                 }
                 foreach ($image_pieces as $key => $value) {
                     $temp_key = $key + 1;
                     $image = PostToRemoteFileAndGetResponse($value);
                     if ($image) {
                         // Place it in our images directory
                         $randomDir = strtolower(chr(rand(65, 90)));
                         if (!is_dir($imageDirectory . "/" . $randomDir)) {
                             if (!@mkdir($imageDirectory . "/" . $randomDir, 0777)) {
                                 $randomDir = '';
                             }
                         }
                         // Generate a random filename
                         $fileName = $randomDir . "/" . GenRandFileName(basename($value));
                         if (!@file_put_contents($imageDirectory . "/" . $fileName, $image)) {
                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageUnableToMove');
                         } else {
                             if (!is_array(@getimagesize($imageDirectory . "/" . $fileName))) {
                                 @unlink($imageDirectory . "/" . $fileName);
                                 $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageInvalidFile');
                             } else {
                                 $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "large");
                                 $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                                 if ($hasThumb == false) {
                                     if ($key == 0) {
                                         $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName);
                                         if ($thumbName) {
                                             $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                         } else {
                                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                         }
                                         $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "tiny");
                                         if ($tinyName) {
                                             $productImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                         } else {
                                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                         }
                                     }
                                     $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "medium");
                                     if ($mediumName) {
                                         $productImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                     }
                                 }
                             }
                         }
                     } else {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageDoesntExist');
                     }
                 }
             } else {
                 // This file exists, can be imported
                 $image_pieces = preg_split("/[;,]/", $record['product_images']);
                 $end = end($image_pieces);
                 if (empty($end)) {
                     array_pop($image_pieces);
                 }
                 foreach ($image_pieces as $key => $value) {
                     $temp_key = $key + 1;
                     if (file_exists($imageDirectory . "/import/" . $value)) {
                         // Move it to our images directory
                         $randomDir = strtolower(chr(rand(65, 90)));
                         if (!is_dir($imageDirectory . "/" . $randomDir)) {
                             if (!@mkdir($imageDirectory . "/" . $randomDir, 0777)) {
                                 $randomDir = '';
                             }
                         }
                         // Generate a random filename
                         $baseFileName = basename($value);
                         if ($baseFileName != $value) {
                             $localDirectory = dirname($value) . "/";
                         } else {
                             $localDirectory = '';
                         }
                         $fileName = $randomDir . "/" . GenRandFileName($baseFileName);
                         if (!@copy($imageDirectory . "/import/" . $value, $imageDirectory . "/" . $fileName)) {
                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageUnableToMove');
                         } else {
                             $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "large");
                             $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                             // Does a thumbnail file exist?
                             $thumbFile = "thumb_" . $baseFileName;
                             if ($key == 0) {
                                 if (file_exists($imageDirectory . "/import/" . $localDirectory . $thumbFile)) {
                                     $thumbName = $randomDir . "/" . GenRandFileName($thumbFile);
                                     if (@copy($imageDirectory . "/import/" . $localDirectory . $thumbFile, $imageDirectory . "/" . $thumbName)) {
                                         $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     }
                                 } else {
                                     $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName);
                                     if ($thumbName) {
                                         $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     }
                                     // Still need to generate "tiny" thumbnail
                                     $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "tiny");
                                     if ($tinyName) {
                                         $productImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                     }
                                 }
                             }
                             $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "medium");
                             if ($mediumName) {
                                 $productImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                             }
                         }
                     } else {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageDoesntExist');
                     }
                 }
             }
         }
         // Do we have an install image? We need to deal with it after product images added by blessen
         $productInstallImages = array();
         if (isset($record['install_images']) && $record['install_images'] != '') {
             // Is this a remote file?
             $InstallDirectory = ISC_BASE_PATH . "/install_images";
             if (isc_substr(isc_strtolower($record['install_images']), 0, 7) == "http://") {
                 // Need to fetch the remote file
                 $image_pieces = preg_split("/[;,]/", $record['install_images']);
                 $end = end($image_pieces);
                 if (empty($end)) {
                     array_pop($image_pieces);
                 }
                 foreach ($image_pieces as $key => $value) {
                     $temp_key = $key + 1;
                     $image = PostToRemoteFileAndGetResponse($value);
                     if ($image) {
                         // Place it in our images directory
                         $randomDir = strtolower(chr(rand(65, 90)));
                         if (!is_dir($InstallDirectory . "/" . $randomDir)) {
                             if (!@mkdir($InstallDirectory . "/" . $randomDir, 0777)) {
                                 $randomDir = '';
                             }
                         }
                         // Generate a random filename
                         $fileName = $randomDir . "/" . GenRandFileName(basename($value));
                         if (!@file_put_contents($InstallDirectory . "/" . $fileName, $image)) {
                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageUnableToMove');
                         } else {
                             if (!is_array(@getimagesize($InstallDirectory . "/" . $fileName))) {
                                 @unlink($InstallDirectory . "/" . $fileName);
                                 $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageInvalidFile');
                             } else {
                                 $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "large");
                                 $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                                 if ($hasThumb == false) {
                                     if ($key == 0) {
                                         $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName);
                                         if ($thumbName) {
                                             $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                         } else {
                                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                         }
                                         $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "tiny");
                                         if ($tinyName) {
                                             $productInstallImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                         } else {
                                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                         }
                                     }
                                     $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "medium");
                                     if ($mediumName) {
                                         $productInstallImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageCorrupt');
                                     }
                                 }
                             }
                         }
                     } else {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageDoesntExist');
                     }
                 }
             } else {
                 // This file exists, can be imported
                 $image_pieces = preg_split("/[;,]/", $record['install_images']);
                 $end = end($image_pieces);
                 if (empty($end)) {
                     array_pop($image_pieces);
                 }
                 foreach ($image_pieces as $key => $value) {
                     $temp_key = $key + 1;
                     if (file_exists($InstallDirectory . "/import/" . $value)) {
                         // Move it to our images directory
                         $randomDir = strtolower(chr(rand(65, 90)));
                         if (!is_dir($InstallDirectory . "/" . $randomDir)) {
                             if (!@mkdir($InstallDirectory . "/" . $randomDir, 0777)) {
                                 $randomDir = '';
                             }
                         }
                         // Generate a random filename
                         $baseFileName = basename($value);
                         if ($baseFileName != $value) {
                             $localDirectory = dirname($value) . "/";
                         } else {
                             $localDirectory = '';
                         }
                         $fileName = $randomDir . "/" . GenRandFileName($baseFileName);
                         if (!@copy($InstallDirectory . "/import/" . $value, $InstallDirectory . "/" . $fileName)) {
                             $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageUnableToMove');
                         } else {
                             $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "large");
                             $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                             // Does a thumbnail file exist?
                             $thumbFile = "thumb_" . $baseFileName;
                             if ($key == 0) {
                                 if (file_exists($InstallDirectory . "/import/" . $localDirectory . $thumbFile)) {
                                     $thumbName = $randomDir . "/" . GenRandFileName($thumbFile);
                                     if (@copy($InstallDirectory . "/import/" . $localDirectory . $thumbFile, $InstallDirectory . "/" . $thumbName)) {
                                         $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     }
                                 } else {
                                     $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName);
                                     if ($thumbName) {
                                         $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     }
                                     // Still need to generate "tiny" thumbnail
                                     $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "tiny");
                                     if ($tinyName) {
                                         $productInstallImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                     }
                                 }
                             }
                             $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "medium");
                             if ($mediumName) {
                                 $productInstallImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                             }
                         }
                     } else {
                         $this->ImportSession['Results']['Warnings'][] = $record['partnumber'] . GetLang('ImportProductImageDoesntExist');
                     }
                 }
             }
         }
         //fetch the new insert product id.
         $query = "SELECT productid,prodcode,prodvendorprefix FROM [|PREFIX|]products_statistics WHERE prodcode='" . $GLOBALS['ISC_CLASS_DB']->Quote($record['partnumber']) . "' and prodvendorprefix = '" . $record['vendorprefix'] . "'";
         $result = $GLOBALS["ISC_CLASS_DB"]->Query($query);
         while ($rs = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
             $productId = $rs['productid'];
         }
         if (empty($productId) || $productId == "") {
             $productid = 0;
         }
         // Are there any images?
         if (count($productImages) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_images', "WHERE imageprodid='" . $productId . "'");
             foreach ($productImages as $image) {
                 $image['imageprodid'] = $productId;
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_images", $image);
             }
         }
         // Are there any Install images? blessen
         if (count($productInstallImages) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('install_images', "WHERE imageprodid='" . $productId . "'");
             foreach ($productInstallImages as $image) {
                 $image['imageprodid'] = $productId;
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("install_images", $image);
             }
         }
         // Are there any Install videos ? blessen
         if ($record['install_video'] != "") {
             $productInstallVideos = array();
             $video_pieces = preg_split("/[;,]/", $record['install_video']);
             $end = end($video_pieces);
             if (empty($end)) {
                 array_pop($video_pieces);
             }
             foreach ($video_pieces as $key => $values) {
                 $productInstallVideos[] = array("videofile" => $values, "videotype" => 1, "videoprodid" => $productId);
             }
             if (count($productInstallVideos) > 0) {
                 $GLOBALS['ISC_CLASS_DB']->DeleteQuery('install_videos', "WHERE videoprodid='" . $productId . "'");
                 foreach ($productInstallVideos as $video) {
                     $GLOBALS['ISC_CLASS_DB']->InsertQuery("install_videos", $video);
                 }
             }
         }
         // Are there any product videos ? blessen audio_clip
         if ($record['product_video'] != "") {
             $productVideos = array();
             $video_pieces = preg_split("/[;,]/", $record['product_video']);
             $end = end($video_pieces);
             if (empty($end)) {
                 array_pop($video_pieces);
             }
             foreach ($video_pieces as $key => $values) {
                 $productVideos[] = array("videofile" => $values, "videotype" => 1, "videoprodid" => $productId);
             }
             if (count($productVideos) > 0) {
                 $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_videos', "WHERE videoprodid='" . $productId . "'");
                 foreach ($productVideos as $video) {
                     $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_videos", $video);
                 }
             }
         }
         // Are there any product audio_clip ? blessen
         if ($record['audio_clip'] != "") {
             $product_audio_clip = array();
             $audio_pieces = preg_split("/[;,]/", $record['audio_clip']);
             $end = end($audio_pieces);
             if (empty($end)) {
                 array_pop($audio_pieces);
             }
             foreach ($audio_pieces as $key => $values) {
                 $product_audio_clip[] = array("audiofile" => $values, "audiotype" => 1, "audioprodid" => $productId);
             }
             if (count($product_audio_clip) > 0) {
                 $GLOBALS['ISC_CLASS_DB']->DeleteQuery('audio_clips', "WHERE audioprodid='" . $productId . "'");
                 foreach ($product_audio_clip as $audio) {
                     $GLOBALS['ISC_CLASS_DB']->InsertQuery("audio_clips", $audio);
                 }
             }
         }
         // Are there any product article file ? blessen
         if ($recordval[$head['article_file']] != "") {
             $product_article = array();
             $article_pieces = preg_split("/[;,]/", $recordval[$head['article_file']]);
             $end = end($article_pieces);
             if (empty($end)) {
                 array_pop($article_pieces);
             }
             foreach ($article_pieces as $key => $values) {
                 $product_article[] = array("articlefile" => $values, "articletype" => 1, "articleprodid" => $productId);
             }
             if (count($product_article) > 0) {
                 $GLOBALS['ISC_CLASS_DB']->DeleteQuery('article_files', "WHERE articleprodid='" . $productId . "'");
                 foreach ($product_article as $article) {
                     $GLOBALS['ISC_CLASS_DB']->InsertQuery("article_files", $article);
                 }
             }
         }
         // Are there any product instruction_file  ? blessen
         if ($recordval[$head['instruction_file']] != "") {
             $product_instruction = array();
             $instruction_pieces = preg_split("/[;,]/", $recordval[$head['instruction_file']]);
             $end = end($instruction_pieces);
             if (empty($end)) {
                 array_pop($instruction_pieces);
             }
             foreach ($instruction_pieces as $key => $values) {
                 $product_instruction[] = array("instructionfile" => $values, "instructiontype" => 1, "instructionprodid" => $productId);
             }
             if (count($product_instruction) > 0) {
                 $GLOBALS['ISC_CLASS_DB']->DeleteQuery('instruction_files', "WHERE instructionprodid='" . $productId . "'");
                 foreach ($product_instruction as $instruction) {
                     $GLOBALS['ISC_CLASS_DB']->InsertQuery("instruction_files", $instruction);
                 }
             }
         }
         // Are there any product files?
         if (count($productFiles) > 0) {
             foreach ($productFiles as $file) {
                 $file['productid'] = $productId;
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_downloads", $file);
             }
         }
         //when finish image,prodfile,etc. processed,then update the import_products flag=1;
         $updatesql = "update [|PREFIX|]import_products set flag=1 where tempid=" . $record['tempid'];
         $GLOBALS['ISC_CLASS_DB']->Query($updatesql);
     }
     //this record process over!
 }
Example #24
0
 /**
  * Actually fetch the shipping quotes based on the set information.
  *
  * @return array An array of shipping quotes.
  */
 private function FetchQuotes()
 {
     $upsUrl = 'https://wwwcie.ups.com/ups.app/xml/Rate';
     $shipmentXML = $this->GenerateRateXML();
     $result = PostToRemoteFileAndGetResponse($upsUrl, $shipmentXML);
     if ($result === false) {
         $this->SetError(GetLang('UPSOpenError'));
         return false;
     }
     $x = @simplexml_load_string($result);
     if (!is_object($x)) {
         $this->SetError(GetLang('UPSOpenError'));
         return false;
     }
     // Was an error returned from UPS? If so, set that and return
     if (isset($x->Response->ResponseStatusCode) && $x->Response->ResponseStatusCode == 0) {
         $this->SetError((string) $x->Response->Error->ErrorDescription);
         return false;
     }
     $quotes = array();
     if (!isset($x->RatedShipment[0])) {
         $quoteXML = array($x->RatedShipment);
     } else {
         $quoteXML = $x->RatedShipment;
     }
     $deliveryTypes = $this->GetValue('deliverytypes');
     if (!is_array($deliveryTypes)) {
         $deliveryTypes = array($deliveryTypes);
     }
     foreach ($quoteXML as $quote) {
         // Fetch the friendly name of the shipping service for this quote
         $serviceName = GetLang('Unknown');
         $service = (string) $quote->Service->Code;
         // We're not offering this delivery type in the store so skip it
         if (!in_array($service, $deliveryTypes)) {
             continue;
         }
         if (isset($this->internationalTypes[$service])) {
             $serviceName = GetLang('DeliveryType' . $this->internationalTypes[$service]);
         } else {
             if (isset($this->domesticTypes[$service])) {
                 $serviceName = GetLang('DeliveryType' . $this->domesticTypes[$service]);
             }
         }
         $cost = (double) $quote->TotalCharges->MonetaryValue;
         $currencyCode = (string) $quote->TotalCharges->CurrencyCode;
         $quoteCurrency = GetCurrencyByCode($currencyCode);
         if ($quoteCurrency == false) {
             $this->SetError(sprintf(GetLang('UPSCurrencyCodeError'), $currencyCode));
             continue;
         }
         $transitTime = 0;
         if (isset($quote->GuaranteedDaysToDelivery)) {
             $transitTime = (string) $quote->GuaranteedDaysToDelivery;
         }
         $cost = ConvertPriceToDefaultCurrency($cost, $quoteCurrency);
         $quotes[] = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), $cost, $serviceName, $transitTime);
     }
     return $quotes;
 }
Example #25
0
	public function DoVoid($orderId, $transactionId, &$message = '')
	{
		if ($this->GetValue("testmode") == 'YESLIVE') {
			$trainingMode = 'T';
		}
		else {
			$trainingMode = 'F';
		}

		$order = GetOrder($orderId);
		$request = array(
			'UserName'		=> $this->GetValue('username'),
			'Password'		=> $this->GetValue('password'),
			'TransType'		=> 'Void',
			'PNRef'			=> $transactionId,
			'CardNum'		=> '',
			'ExpDate'		=> '',
			'MagData'		=> '',
			'NameOnCard' 	=> '',
			'Amount'		=> number_format($order['total_inc_tax'], 2, '.', ''),
			'InvNum'		=> '',
			'Zip'			=> '',
			'Street'		=> '',
			'CVNum'			=> '',
			'ExtData'		=> '<TrainingMode>' . $trainingMode . '</TrainingMode>'
		);

		if($this->GetValue('testmode') == 'YES') {
			$url = $this->_testTransactionURL.$this->_testTransactionURI;
		}
		else {
			$url = $this->_liveTransactionURL.$this->_liveTransactionURI;
		}

		$response = PostToRemoteFileAndGetResponse($url, http_build_query($request));

		try {
			$xml = new SimpleXMLElement($response);
		}
		catch (Exception $e) {
			// Something went wrong, show the error message.
			$message = GetLang('PayLeapVoidFailed');
			return false;
		}

		$responseCode = '';
		$responseMessage = '';

		if (isset($xml->Result)) {
			$responseCode = (string)$xml->Result;
		}

		if (isset($xml->RespMSG)) {
			$responseMessage = (string)$xml->RespMSG;
		}

		if($responseCode == 0 && $responseMessage == 'Approved') {
			$message = GetLang('PayLeapPaymentVoided');

			// Mark the order as captured
			$updatedOrder = array(
				'ordpaymentstatus' => 'void'
			);

			// Update the orders table with new transaction details
			$GLOBALS['ISC_CLASS_DB']->UpdateQuery('orders', $updatedOrder, "orderid='".(int)$orderId."'");

			// Log the transaction in store logs
			$logMessage = GetLang('PayLeapPaymentVoidedLogMsg', array(
				'orderId' => $orderId
			));
			$GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), $logMessage);

			return true;
		}
		else {
			$message = GetLang('PayLeapVoidFailed');

			$logMessage = GetLang('PayLeapVoidFailedLogMsg', array(
				'orderId' => $orderId
			));

			$logDetails = GetLang('PayLeapVoidFailedLogDetails', array(
				'paymentReference' => $transactionId,
				'responseCode' => $responseCode,
				'responseMessage' => $responseMessage
			));

			$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), $logMessage, $logDetails);
			return false;
		}
	}
Example #26
0
	private function _ImportFile($record, $index = '')
	{
		$productFileName = $record['prodfile' . $index];

		$fileDescription = '';
		if (!empty($record['prodfiledescription' . $index])) {
			$fileDescription = $record['prodfiledescription' . $index];
		}

		$fileMaxDownloads = 0;
		if (!empty($record['prodfilemaxdownloads' . $index])) {
			$fileMaxDownloads = (int)$record['prodfilemaxdownloads' . $index];
		}

		$fileExpiresAfter = 0;
		if (!empty($record['prodfileexpiresafter' . $index])) {
			if (preg_match('/([0-9]+) (days|weeks|months|years)/i', $record['prodfileexpiresafter' . $index], $matches)) {
				$quantity = $matches[1];
				$unit = strtolower($matches[2]);

				switch ($unit) {
					case 'days':
						$fileExpiresAfter = 86400 * $quantity;
						break;
					case 'weeks':
						$fileExpiresAfter = 604800 * $quantity;
						break;
					case 'months':
						$fileExpiresAfter = 2592000 * $quantity; //assumed to be 30 days, as per class.product.php
						break;
					case 'years':
						$fileExpiresAfter = 31536000 * $quantity;
						break;
				}
			}
		}

		$productFile = false;

		// Is this a remote file?
		$downloadDirectory = ISC_BASE_PATH."/".GetConfig('DownloadDirectory');
		if(isc_substr(isc_strtolower($productFileName), 0, 7) == "http://") {
			// Need to fetch the remote file
			$file = PostToRemoteFileAndGetResponse($productFileName);
			if($file) {
				// Place it in our downloads directory
				$randomDir = strtolower(chr(rand(65, 90)));
				if(!is_dir($downloadDirectory.$randomDir)) {
					if(!isc_mkdir($downloadDirectory."/".$randomDir)) {
						$randomDir = '';
					}
				}

				// Generate a random filename
				$fileName = $randomDir . "/" . GenRandFileName(basename($productFileName));
				if(!@file_put_contents($downloadDirectory."/".$fileName, $file)) {
					$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileUnableToMove');
				}
				else {
					$productFile = array(
						"prodhash" => "",
						"downfile" => $fileName,
						"downdateadded" => time(),
						"downmaxdownloads" => $fileMaxDownloads,
						"downexpiresafter" => $fileExpiresAfter,
						"downfilesize" => filesize($downloadDirectory."/".$fileName),
						"downname" => basename($productFileName),
						"downdescription" => $fileDescription
					);
				}
			}
			else {
				$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileDoesntExist');
			}
		}
		// Treating the file as a local file, in the product_fules/import directory
		else {
			// This file exists, can be imported
			if(file_exists($downloadDirectory."/import/".$productFileName)) {

				// Move it to our images directory
				$randomDir = strtolower(chr(rand(65, 90)));
				if(!is_dir("../".$downloadDirectory."/".$randomDir)) {
					if(!isc_mkdir($downloadDirectory."/".$randomDir)) {
						$randomDir = '';
					}
				}

				// Generate a random filename
				$fileName = $randomDir . "/" . GenRandFileName($productFileName);
				if(!@copy($downloadDirectory."/import/".$productFileName, $downloadDirectory."/".$fileName)) {
					$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileUnableToMove');
				}
				else {
					$productFile = array(
						"prodhash" => "",
						"downfile" => $fileName,
						"downdateadded" => time(),
						"downmaxdownloads" => $fileMaxDownloads,
						"downexpiresafter" => $fileExpiresAfter,
						"downfilesize" => filesize($downloadDirectory."/".$fileName),
						"downname" => basename($productFileName),
						"downdescription" => $fileDescription
					);
				}
			}
			else {
				$this->ImportSession['Results']['Warnings'][] = $record['prodname'].GetLang('ImportProductFileDoesntExist');
			}
		}

		return $productFile;
	}
				/**
		 * Process the PayPal IPN ping back.
		 */
		public function ProcessGatewayPing()
		{
			//make it only work for echeck pings
			if($_POST['payment_type'] != 'echeck' || $_POST['payment_status']== 'Pending') {
				exit;
			}

			if(!isset($_POST['custom'])) {
				exit;
			}

			$sessionToken = explode('_', $_REQUEST['custom'], 2);

			$this->SetOrderData(LoadPendingOrdersByToken($sessionToken[0]));

			$amount = number_format($this->GetGatewayAmount(), 2, '.', '');

			if($amount == 0) {
				exit;
			}

			// Perform a post back to PayPal with exactly what we received in order to validate the request
			$queryString = array();
			$queryString[] = "cmd=_notify-validate";
			foreach($_POST as $k => $v) {
				$queryString[] = $k."=".urlencode($v);
			}
			$queryString = implode('&', $queryString);

			$testMode = $this->GetValue('testmode');
			if($testMode == 'YES') {
				$verifyURL = 'http://www.sandbox.paypal.com/cgi-bin/webscr';
			}
			else {
				$verifyURL = 'http://www.paypal.com/cgi-bin/webscr';
			}

			$response = PostToRemoteFileAndGetResponse($verifyURL, $queryString);

			// This pingback was not valid
			if($response != "VERIFIED") {
				// Bad order details
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('PayPalErrorInvalid'), "RESPONSE : "  .$response);
				return false;
			}

			// If we're still here, the ping back was valid, so we check the payment status and everything else match up


			$paypalEmail = $this->GetValue('email');

			if(!isset($_POST['receiver_email']) || !isset($_POST['mc_gross']) || !isset($_POST['payment_status'])) {
				// Bad order details
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('PayPalErrorInvalid'), print_r($_POST, true));
				return false;
			}

			// The values passed don't match what we expected
			if(($_POST['mc_gross'] != $amount && !in_array($_POST['payment_status'], array('Reversed', 'Refunded', 'Canceled_Reversed')))) {
				$errorMsg = sprintf(GetLang('PayPalErrorInvalidMsg'), $_POST['mc_gross'], $amount, $_POST['receiver_email'], $paypalEmail, $_POST['payment_status']);
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('PayPalErrorInvalid'), $errorMsg);
				return false;
			}

			$currency = GetDefaultCurrency();

			if($_POST['mc_currency'] != $currency['currencycode']) {
				$errorMsg = sprintf(GetLang('PayPalErrorInvalidMsg3'), $currency['currencycode'], $_POST['mc_currency']);
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('PayPalErrorInvalid'), $errorMsg);
				return false;
			}

			// Has the transaction been processed before? If so, we can't process it again
			$transaction = GetClass('ISC_TRANSACTION');

			$newTransaction = array(
				'providerid' => $this->GetId(),
				'transactiondate' => time(),
				'transactionid' => $_POST['txn_id'],
				'orderid' => array_keys($this->GetOrders()),
				'message' => '',
				'status' => '',
				'amount' => $_POST['mc_gross'],
				'extrainfo' => array()
			);

			$orderPaymentStatus = '';
			switch($_POST['payment_status']) {
				case "Completed":
					$orderPaymentStatus = 'captured';
					$newTransaction['status'] = TRANS_STATUS_COMPLETED;
					$newOrderStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
					break;
				case "Pending":
					if($_POST['payment_type'] != 'echeck') {
						$orderPaymentStatus = 'authorized';
					}
					$newTransaction['status'] = TRANS_STATUS_PENDING;
					$newOrderStatus = ORDER_STATUS_AWAITING_PAYMENT;
					$newTransaction['extrainfo']['reason'] = $_POST['pending_reason'];
					break;
				case "Denied":
					$newTransaction['status'] = TRANS_STATUS_DECLINED;
					$newOrderStatus = ORDER_STATUS_DECLINED;
					break;
				case "Failed":
					$newTransaction['status'] = TRANS_STATUS_FAILED;
					$newOrderStatus = ORDER_STATUS_DECLINED;
					break;
				case "Refunded":
					$newTransaction['status'] = TRANS_STATUS_REFUND;
					$newOrderStatus = ORDER_STATUS_REFUNDED;
					break;
				case "Reversed":
					$newTransaction['status'] = TRANS_STATUS_CHARGEBACK;
					$newOrderStatus = ORDER_STATUS_REFUNDED;
					break;
				case "Canceled_Reversal":
					$newTransaction['status'] = TRANS_STATUS_CANCELLED_REVERSAL;
					$newOrderStatus = ORDER_STATUS_REFUNDED;
					break;
			}


			$previousTransaction = $transaction->LoadByTransactionId($_POST['txn_id'], $this->GetId());

			// Already processed before, HALT and log error
			if(is_array($previousTransaction) && $previousTransaction['transactionid'] && $previousTransaction['status'] == $newTransaction['status']) {
				$GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), sprintf(GetLang('PayPalTransactionAlreadyProcessed'), $_POST['txn_id']));
				return false;
			}


			$newTransaction['message'] = $this->GetPayPalTransactionMessage($_POST);

			$transactionId = $transaction->Create($newTransaction);

			$oldOrderStatus = $this->GetOrderStatus();
			// If the order was previously incomplete, we need to do some extra work
			if($oldOrderStatus == ORDER_STATUS_INCOMPLETE) {
				// If a customer doesn't return to the store from PayPal, their cart will never be
				// emptied. So what we do here, is if we can, load up the existing customers session
				// and empty the cart and kill the checkout process. When they next visit the store,
				// everything should be "hunky-dory."
				session_write_close();
				$session = new ISC_SESSION($sessionToken[1]);
				EmptyCartAndKillCheckout();
			}

			// Update the status for all orders that we've just received the payment for
			foreach($this->GetOrders() as $orderId => $order) {
				$status = $newOrderStatus;
				// If it's a digital order & awaiting fulfillment, automatically complete it
				if($order['ordisdigital'] && $status == ORDER_STATUS_AWAITING_FULFILLMENT) {
					$status = ORDER_STATUS_COMPLETED;
				}
				UpdateOrderStatus($orderId, $status);
			}

			$updatedOrder = array(
				'ordpaymentstatus' => $orderPaymentStatus,
			);

			$this->UpdateOrders($updatedOrder);

			// This was a successful order
			$oldStatus = GetOrderStatusById($oldOrderStatus);
			if(!$oldStatus) {
				$oldStatus = 'Incomplete';
			}
			$newStatus = GetOrderStatusById($newOrderStatus);

			$extra = sprintf(GetLang('PayPalSuccessDetails'), implode(', ', array_keys($this->GetOrders())), $amount, '', $_POST['txn_id'], $_POST['payment_status'], $newStatus, $oldStatus);

			$successMsg = sprintf(GetLang('PayPalPaymentsProSuccess'), implode(', ', array_keys($this->GetOrders())));

			$GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), $successMsg, $extra);
			return true;
		}
Example #28
0
 /**
  *	Load up an RSS feed, parse its contents and return it.
  */
 public function _LoadFeed($FeedURL, $NumEntries = 0, $CacheTime = 0, $FeedId = "", $RSSFeedSnippet = "", $helpLinks = false)
 {
     $reload = true;
     if ($CacheTime > 0) {
         if ($FeedId != "") {
             $FeedID = md5($FeedURL);
         }
         $reload = false;
         if (!is_dir(ISC_BASE_PATH . "/cache/feeds")) {
             @mkdir(ISC_BASE_PATH . "/cache/feeds/", 0777);
         }
         // Using a cached version that hasn't expired yet
         if (file_exists(ISC_BASE_PATH . "/cache/feeds/" . $FeedId) && filemtime(ISC_BASE_PATH . "/cache/feeds/" . $FeedId) > time() - $CacheTime) {
             $contents = file_get_contents(ISC_BASE_PATH . "/cache/feeds/" . $FeedId);
             // Cache was bad, recreate
             if (!$contents) {
                 $reload = true;
             }
         } else {
             $reload = true;
         }
     }
     if ($reload === true) {
         $contents = PostToRemoteFileAndGetResponse($FeedURL);
         // Do we need to cache this version?
         if ($CacheTime > 0 && $contents != "") {
             @file_put_contents(ISC_BASE_PATH . "/cache/feeds/" . $FeedId, $contents);
         }
     }
     $output = "";
     $count = 0;
     // Could not load the feed, return an error
     if (!$contents) {
         return false;
     }
     if ($xml = SimpleXML_Load_String($contents)) {
         $rss = new ISC_XML();
         $entries = $rss->ParseRSS($xml);
         foreach ($entries as $entry) {
             $GLOBALS['RSSTitle'] = $entry['title'];
             $GLOBALS['RSSDescription'] = $entry['description'];
             $GLOBALS['RSSLink'] = $entry['link'];
             if ($RSSFeedSnippet != "") {
                 if ($helpLinks) {
                     preg_match('#/questions/([0-9]+)/#si', $entry['link'], $matches);
                     if (!empty($matches)) {
                         $GLOBALS['RSSLink'] = $matches[1];
                     }
                 }
                 $output .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet($RSSFeedSnippet);
             } else {
                 $output .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("PageRSSItem");
             }
             if ($NumEntries > 0 && ++$count >= $NumEntries) {
                 break;
             }
         }
         return $output;
     } else {
         return false;
     }
 }
 protected function _ImportRecord($record)
 {
     $loggedid = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetUserId();
     static $categoryCache;
     if (!is_array($categoryCache)) {
         $categoryCache = array();
     }
     /*
     		if(!isset($record['prodname']) || empty($record['prodname'])) {
     			$this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record'])." ".GetLang('ImportProductsMissingName');
     			return;
     		}
     
     	if ($message = strtokenize($_REQUEST, '#')) {
     			$this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record'])." ".GetLang(B('UmVhY2hlZFByb2R1Y3RMaW1pdA=='));
     			return;
     		}*/
     if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
         $vendorId = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId();
     } else {
         $vendorId = (int) @$record['prodvendorid'];
     }
     if (!is_int($record['prodvendorid'])) {
         $query = "SELECT vendorid FROM [|PREFIX|]vendors WHERE vendorname='" . $record['prodvendorid'] . "'";
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         if ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
             $vendorId = $row['vendorid'];
         }
     }
     /*
     $record['category1'] = str_replace("/", "SlaSH", $record['category1']);
     $record['category2'] = str_replace("/", "SlaSH", $record['category2']);
     $record['category3'] = str_replace("/", "SlaSH", $record['category3']);
     */
     // Automatically fetching categories based on CSV field
     if (isset($this->ImportSession['AutoCategory'])) {
         // We specified more than one level for the category back in the configuration
         if (isset($record['category1'])) {
             $record['category'] = array($record['category1']);
             if (isset($record['category2']) && $record['category2'] != '') {
                 $record['category'][] = $record['category2'];
             }
             //if(isset($record['category3']) && $record['category3'] != '') {
             //$record['category'][] = $record['category3'];
             //}
             $record['category'] = implode("/#/", $record['category']);
         }
         if (!$record['category']) {
             $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record']) . " " . GetLang('ImportProductsMissingCategory');
             return;
         }
         // Import the categories for the products too
         $categoryList = explode(";", $record['category']);
         $cats = array();
         foreach ($categoryList as $importCategory) {
             $categories = explode("/#/", $importCategory);
             $parentId = 0;
             $lastCategoryId = 0;
             if (!isset($categoryCache[$importCategory])) {
                 foreach ($categories as $category) {
                     $category = trim($category);
                     if ($category == '') {
                         continue;
                     }
                     //$category = str_replace("SlaSH", "/", $category);
                     $query = "SELECT categoryid, catparentlist FROM [|PREFIX|]categories WHERE LOWER(catname)='" . $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($category)) . "' AND catparentid='" . $parentId . "'";
                     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
                     $existingCategory = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
                     if (!$existingCategory['categoryid']) {
                         // Create the category .But no need to create any category while import since all possiple categories are added to the db. blessen
                         $lastCategoryId = -2;
                     } else {
                         $lastCategoryId = $existingCategory['categoryid'];
                     }
                     $parentId = $lastCategoryId;
                 }
                 if ($lastCategoryId) {
                     $categoryCache[$importCategory] = $lastCategoryId;
                     $cats[] = $lastCategoryId;
                 }
             } else {
                 $cats[] = $categoryCache[$importCategory];
             }
         }
     } else {
         $cats = array($this->ImportSession['CategoryId']);
     }
     $cat_condition = false;
     if (isset($this->ImportSession['PreCategory'])) {
         $cat_condition = $cats[0] == -2 || !in_array($cats[0], $this->ImportSession['PreCategory']) ? true : false;
         // checking for  invalid category and selected category
     } else {
         $cat_condition = $cats[0] == -2 ? true : false;
     }
     if ($cat_condition) {
         $this->writetherejected($record['original_record'], 'Un defined Category', $vendorId, $loggedid);
         return;
     }
     // Does the brand already exist?
     $brandId = 0;
     if (isset($record['brandname']) && $record['brandname'] != '') {
         $query = sprintf("select brandid from [|PREFIX|]brands where lower(brandname)='%s'", $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($record['brandname'])));
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         if ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
             $brandId = $row['brandid'];
         } else {
             $this->writetherejected($record['original_record'], 'Brand Does not exist', $vendorId, $loggedid);
             return;
         }
     }
     //reject if vendor prefix is not present
     $prodvendorprefix = strtolower($record['prodvendorprefix']);
     if ($prodvendorprefix == "") {
         $this->writetherejected($record['original_record'], 'Vendor Prefix is Missing', $vendorId, $loggedid);
         return;
     }
     $prodmake = $record['prodmake'];
     $prodsubmodel = $record['prodsubmodel'];
     $prodmodel = $record['prodmodel'];
     $prodstartyear = $record['prodstartyear'];
     $prodendyear = $record['prodendyear'];
     //$catuniversal = $existingCategory['catuniversal'];
     $query4 = "SELECT catuniversal , catcombine, catparentid, Productname  FROM [|PREFIX|]categories WHERE categoryid = '" . $cats[0] . "' ";
     $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
     $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
     $catuniversal = $eng_row['catuniversal'];
     $catparentid = $eng_row['catparentid'];
     $Productname_elements = explode(",", $eng_row['Productname']);
     if (in_array(0, $Productname_elements) and in_array(1, $Productname_elements)) {
         $catcombine = $eng_row['catcombine'];
     } else {
         $catcombine = "";
     }
     // no need to store products under root category if any subcategory exist.
     if ($catparentid == 0) {
         //check for subcategories
         $query4 = "SELECT count(catparentid) as subcnt  FROM [|PREFIX|]categories WHERE catparentid = '" . $cats[0] . "' ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
         $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
         $subcnt = $eng_row['subcnt'];
         if ($subcnt > 0) {
             //if any subcategory exist, Reject it.
             $this->writetherejected($record['original_record'], 'Products cannot store directly to the root category ', $vendorId, $loggedid);
             return;
         }
     }
     //Reject data if invalid Year make Model and submodel except for universal categories.
     if ($catuniversal == 0) {
         // no need Universal Products with non-universal category
         if (strtolower($prodstartyear) == "all" || strtolower($prodendyear) == "all" || strtolower($prodmodel) == "all" || strtolower($prodmake) == "non-spec vehicle") {
             $this->writetherejected($record['original_record'], 'Universal Products with non-universal category', $vendorId, $loggedid);
             return;
         }
         $query2 = "SELECT id FROM [|PREFIX|]product_mmy  WHERE (year  = '" . $prodstartyear . "' or year  = '" . $prodendyear . "' ) and model   = '" . $prodmodel . "' and submodel = '" . $prodsubmodel . "' and make   = '" . $prodmake . "' limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query2);
         if ($GLOBALS['ISC_CLASS_DB']->CountResult($result2) == 0) {
             // 09495245211
             $this->writetherejected($record['original_record'], 'Invalid MMY and Submodel List', $vendorId, $loggedid);
             return;
         } else {
             $row_ymm_id = $GLOBALS["ISC_CLASS_DB"]->Fetch($result2);
             $ymm_id = $row_ymm_id['id'];
         }
     }
     $productId = 0;
     $hasThumb = false;
     $productFiles = array();
     $productImages = array();
     $existing = null;
     $generalize_bedvalue = "";
     $generalize_cabvalue = "";
     // genarating prod name added by blessen
     $subcat = strtolower($record['category2']);
     $cat = strtolower($record['category1']);
     $partnumber = $record['prodcode'];
     $product_series = strtolower($record['product_series']);
     $brand = $record['brandname'];
     $selected = array_values(array_intersect($_SESSION['assocvqpq'][$cats[0]], $_SESSION['qualifiers']));
     //$selected = $_SESSION['assocvqpq'][$cats[0]];
     if (!isset($selected)) {
         $selected = array();
     }
     if (in_array('VQliter', $selected) and $catuniversal == 0 and $record['VQliter'] != "") {
         $query4 = "SELECT liter FROM [|PREFIX|]engine_table WHERE ymm_id = '" . $ymm_id . "'  limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
         $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
         $liter = $eng_row['liter'];
     }
     if (in_array('VQenginetype', $selected) and $catuniversal == 0 and $record['VQenginetype'] != "") {
         $query4 = "SELECT engtype FROM [|PREFIX|]engine_table WHERE ymm_id = '" . $ymm_id . "'  limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
         $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
         $engtype = $eng_row['engtype'];
     }
     // this is for cabsize traslation
     if (in_array('VQcabsize', $selected) and $record['VQcabsize'] != "") {
         $cabsize_pieces = preg_split("/[;,]/", $record['VQcabsize']);
         $end = end($cabsize_pieces);
         if (empty($end)) {
             array_pop($cabsize_pieces);
         }
         foreach ($cabsize_pieces as $key => $value) {
             $query4 = "SELECT id,generalize_value FROM [|PREFIX|]cabsize_translation WHERE prodstartyear = '" . $prodstartyear . "' and prodendyear = '" . $prodendyear . "'  and prodmake  = '" . $prodmake . "' and prodmodel  = '" . $prodmodel . "' and irregular_value = '" . $value . "'  limit 0,1 ";
             $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
             $cab_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
             $generalize_cabvalue .= $cab_row['generalize_value'] . ";";
         }
         $generalize_cabvalue = trim($generalize_cabvalue, ";");
     }
     // this is for bedsize traslation
     if (in_array('VQbedsize', $selected) and $record['VQbedsize'] != "") {
         $bedsize_pieces = preg_split("/[;,]/", $record['VQbedsize']);
         $end = end($bedsize_pieces);
         if (empty($end)) {
             array_pop($bedsize_pieces);
         }
         foreach ($bedsize_pieces as $key => $value) {
             $query3 = "SELECT id,generalize_value FROM [|PREFIX|]bedsize_translation WHERE irregular_value = '" . $value . "'  limit 0,1 ";
             $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query3);
             $bed_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
             $generalize_bedvalue .= $bed_row['generalize_value'] . ";";
         }
         $generalize_bedvalue = trim($generalize_bedvalue, ";");
         // and checking for repeated values is not done
     }
     if (in_array('VQcabsize', $selected) and $generalize_cabvalue == "" and $catuniversal == 0 and $record['VQcabsize'] != "") {
         $query4 = "SELECT cabsize  FROM [|PREFIX|]cabbed_table  WHERE ymm_id = '" . $ymm_id . "'  limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
         $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
         if ($eng_row['cabsize'] != "") {
             $generalize_cabvalue = $eng_row['cabsize'];
         }
     }
     if ($generalize_bedvalue == "" and in_array('VQbedsize', $selected) and $catuniversal == 0 and $record['VQbedsize'] != "") {
         $query4 = "SELECT bedsize  FROM [|PREFIX|]cabbed_table  WHERE ymm_id = '" . $ymm_id . "'  limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query4);
         $eng_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result2);
         if ($eng_row['bedsize'] != "") {
             $generalize_bedvalue = $eng_row['bedsize'];
         }
     }
     // $Productname_elements
     // $pnamearray = array('Category Name', 'Sub Category Name', 'Brand Name','Series Name', 'Part Number', 'Product Code','Product color', 'Product Material', 'Product Style');
     //key = 0,1,2,3,4,5,6,7,8
     //0,2,3,5,6,8
     // this is for cat-subcat combined name
     if ($catcombine == "" and in_array(0, $Productname_elements) and in_array(1, $Productname_elements)) {
         //$sc = str_word_count($subcat, 1);
         $sc = explode(" ", $subcat);
         foreach ($sc as $value) {
             $cat = str_ireplace($value, " ", $cat);
         }
         $c = str_word_count($cat, 1, "1234567890'-_");
         foreach ($c as $value) {
             $subcat = str_ireplace($value . "s", " ", $subcat);
             $subcat = str_ireplace($value . "es", " ", $subcat);
         }
         if (trim($cat) == "s" || trim($cat) == "S") {
             $cat = "";
         }
         $catcombine = $subcat . " " . $cat;
     }
     if (in_array(0, $Productname_elements) and !in_array(1, $Productname_elements)) {
         $catcombine = $cat;
     } else {
         if (!in_array(0, $Productname_elements) and in_array(1, $Productname_elements)) {
             $catcombine = $subcat;
         }
     }
     if (in_array(3, $Productname_elements) and in_array(0, $Productname_elements) and in_array(1, $Productname_elements)) {
         $product_series = str_word_count($product_series, 1, "1234567890'-_");
         $subcatcomp = str_word_count($catcombine, 1, "1234567890'-_");
         $product_series = array_diff($product_series, $subcatcomp);
         $product_series = implode(" ", $product_series);
     } else {
         if (!in_array(3, $Productname_elements)) {
             $product_series = "";
         }
     }
     // process 3
     if (isset($record['PQcolor']) and in_array(6, $Productname_elements)) {
         $prodcolor = rtrim(strtolower($record['PQcolor']), ";");
     } else {
         $prodcolor = "";
     }
     if (isset($record['PQmaterial']) and in_array(7, $Productname_elements)) {
         $prodmaterial = rtrim(strtolower($record['PQmaterial']), ";");
     } else {
         $prodmaterial = "";
     }
     if (isset($record['PQstyle']) and in_array(8, $Productname_elements)) {
         $prodstyle = rtrim(strtolower($record['PQstyle']), ";");
     } else {
         $prodstyle = "";
     }
     if (in_array(4, $Productname_elements) and in_array(5, $Productname_elements)) {
         $PartNumberTXT = " Part Number ";
     } else {
         $PartNumberTXT = " ";
     }
     if (!in_array(5, $Productname_elements)) {
         $partnumber = "";
     }
     if (!in_array(2, $Productname_elements)) {
         $brand = "";
     }
     $prodname = $catcombine . " " . $brand . " " . $product_series . $PartNumberTXT . $partnumber . " " . $prodcolor . " " . $prodmaterial . " " . $prodstyle;
     $prodname = str_replace("/", " ", $prodname);
     $prodname = preg_replace('/(\\s+)/', ' ', $prodname);
     $newprodname = trim($prodname);
     $newprodname = ucwords($newprodname);
     array_push($selected, "prodmake", "prodmodel", "prodsubmodel", "prodstartyear", "prodendyear");
     // Is there an existing product with the same name?
     $query = sprintf("SELECT * FROM [|PREFIX|]products WHERE LOWER(prodcode)='%s' and LOWER(prodvendorprefix) = '" . $prodvendorprefix . "'  ", $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($record['prodcode'])));
     $result = $GLOBALS["ISC_CLASS_DB"]->Query($query);
     if ($existing = $GLOBALS["ISC_CLASS_DB"]->Fetch($result)) {
         $query2 = "SELECT id FROM [|PREFIX|]import_variations  WHERE prodstartyear = '" . $prodstartyear . "' and prodendyear = '" . $prodendyear . "' and prodmodel  = '" . $prodmodel . "' and prodsubmodel  = '" . $prodsubmodel . "' and prodmake  = '" . $prodmake . "' and prodcode  = '" . $record['prodcode'] . "' limit 0,1 ";
         $result2 = $GLOBALS['ISC_CLASS_DB']->Query($query2);
         if ($GLOBALS['ISC_CLASS_DB']->CountResult($result2) == 0) {
             $sqlinsert2 = "INSERT INTO `isc_import_variations` ( `productid`, `prodcode` , ";
             $values = ") VALUES (" . $existing['productid'] . ", '" . $record['prodcode'] . "' ,";
             for ($i = 0; $i < count($selected); $i++) {
                 $fieldname = $selected[$i];
                 $thevalue = rtrim($record[$fieldname], ";");
                 $sqlinsert2 .= "`" . $fieldname . "` ,";
                 $values .= "'" . $thevalue . "',";
                 // VQenginetype validation checking
                 if ($fieldname == "VQenginetype" and $thevalue != "") {
                     $thevalue = $engtype;
                 }
                 // VQliter validation checking
                 if ($fieldname == "VQliter" and $thevalue != "") {
                     $thevalue = $liter;
                 }
                 // this table is only for to make search fast
                 if ($thevalue != "") {
                     $sql = "INSERT INTO `isc_qualifier_value` (`pid`, `qid`, `q_value` , `row_no`) VALUES ('" . $existing['productid'] . "', '" . $_SESSION['qualifiers_name'][$fieldname] . "', '" . $thevalue . "' ,  '" . $_SESSION['row_no'] . "')";
                     mysql_query($sql);
                 }
                 // only for search fast end
             }
             $_SESSION['row_no']++;
             $sqlinsert2 .= "`bedsize_generalname` , `cabsize_generalname` ";
             $values .= "'" . $generalize_bedvalue . "', '" . $generalize_cabvalue . "'";
             $joinedsql = $sqlinsert2 . $values . " ) ";
             mysql_query($joinedsql);
             //complementary items  ;
             $record['complementaryitems'] = str_replace('โ€', '"', $record['complementaryitems']);
             $record['complementaryitems'] = str_replace('โ€œ', '"', $record['complementaryitems']);
             $comData = array("complementaryitems" => $record['complementaryitems'], "variationid" => mysql_insert_id(), "productid" => $existing['productid']);
             $GLOBALS['ISC_CLASS_DB']->InsertQuery("application_data", $comData);
         } else {
             if (isset($this->ImportSession['OverrideDuplicates']) && $this->ImportSession['OverrideDuplicates'] == 1) {
                 $existing_iv = $GLOBALS["ISC_CLASS_DB"]->Fetch($result2);
                 $ivid = $existing_iv['id'];
                 $sqlupdate = "Update  `isc_import_variations` set ";
                 for ($i = 0; $i < count($selected); $i++) {
                     $thevalue = $record[$selected[$i]];
                     if ($thevalue != "") {
                         $fieldname = $selected[$i];
                         if ($thevalue == "<BLANK>") {
                             $thevalue = "";
                         }
                         $sqlup = "update `isc_qualifier_value` set  `q_value` = " . $thevalue . "  where `pid` = " . $productId . " and `qid` = '" . $_SESSION['qualifiers_name'][$fieldname] . "' and `row_no` = " . $ivid;
                         mysql_query($sqlup);
                         $sqlupdate .= "`" . $fieldname . "` = '" . $thevalue . "',";
                     }
                 }
                 $sqlupdate .= " productid = " . $existing['productid'] . " where id = " . $ivid;
                 mysql_query($sqlupdate);
                 //complementary items  ;
                 $record['complementaryitems'] = str_replace('โ€', '"', $record['complementaryitems']);
                 $record['complementaryitems'] = str_replace('โ€œ', '"', $record['complementaryitems']);
                 $comData = array("complementaryitems" => $record['complementaryitems']);
                 $GLOBALS['ISC_CLASS_DB']->UpdateQuery("application_data", $comData, "variationid = '{$ivid}' ");
             }
         }
         // Overriding existing products, set the product id
         if (isset($this->ImportSession['OverrideDuplicates']) && $this->ImportSession['OverrideDuplicates'] == 1) {
             $productId = $existing['productid'];
             //$cats = null;  // blessen
             //$cats = "";   let the category change in re-import blessen 22-10 as per client req.
             if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId() && $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId() != $existing['prodvendorid']) {
                 $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record']) . " " . GetLang('ImportProductInvalidVendor');
                 return;
             }
             $this->ImportSession['Results']['Updates'][] = $record['prodcode'];
         } else {
             //$this->ImportSession['Results']['Duplicates'][] = $record['prodcode'];
             ++$this->ImportSession['Results']['Imported'];
             return;
         }
     }
     // Do we have a product file? We need to deal with it now damn it!
     if (isset($record['prodfile']) && $record['prodfile'] != '') {
         // Is this a remote file?
         $downloadDirectory = ISC_BASE_PATH . "/" . GetConfig('DownloadDirectory');
         if (isc_substr(isc_strtolower($record['prodfile']), 0, 7) == "http://") {
             // Need to fetch the remote file
             $file = PostToRemoteFileAndGetResponse($record['prodfile']);
             if ($file) {
                 // Place it in our downloads directory
                 $randomDir = strtolower(chr(rand(65, 90)));
                 if (!is_dir($downloadDirectory . $randomDir)) {
                     if (!@mkdir($downloadDirectory . "/" . $randomDir, 0777)) {
                         $randomDir = '';
                     }
                 }
                 // Generate a random filename
                 $fileName = $randomDir . "/" . GenRandFileName(basename($record['prodfile']));
                 if (!@file_put_contents($downloadDirectory . "/" . $fileName, $file)) {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductFileUnableToMove');
                 } else {
                     $productFiles[] = array("prodhash" => "", "downfile" => $fileName, "downdateadded" => time(), "downmaxdownloads" => 0, "downexpiresafter" => 0, "downfilesize" => filesize($downloadDirectory . "/" . $fileName), "downname" => basename($record['prodfile']), "downdescription" => "");
                 }
             } else {
                 $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductFileDoesntExist');
             }
         } else {
             // This file exists, can be imported
             if (file_exists($downloadDirectory . "/import/" . $record['prodfile'])) {
                 // Move it to our images directory
                 $randomDir = strtolower(chr(rand(65, 90)));
                 if (!is_dir("../" . $downloadDirectory . "/" . $randomDir)) {
                     if (!@mkdir($downloadDirectory . "/" . $randomDir, 0777)) {
                         $randomDir = '';
                     }
                 }
                 // Generate a random filename
                 $fileName = $randomDir . "/" . GenRandFileName($record['prodfile']);
                 if (!@copy($downloadDirectory . "/import/" . $record['prodfile'], $downloadDirectory . "/" . $fileName)) {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductFileUnableToMove');
                 } else {
                     $productFiles[] = array("prodhash" => "", "downfile" => $fileName, "downdateadded" => time(), "downmaxdownloads" => 0, "downexpiresafter" => 0, "downfilesize" => filesize($downloadDirectory . "/" . $fileName), "downname" => basename($record['prodfile']), "downdescription" => "");
                 }
             } else {
                 $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductFileDoesntExist');
             }
         }
     }
     // Do we have an image? We need to deal with it before we do anything else
     $productImages = array();
     if (isset($record['prodimagefile']) && $record['prodimagefile'] != '') {
         // Is this a remote file?
         $imageDirectory = ISC_BASE_PATH . "/" . GetConfig('ImageDirectory');
         if (isc_substr(isc_strtolower($record['prodimagefile']), 0, 7) == "http://") {
             // Need to fetch the remote file
             $image_pieces = preg_split("/[;,]/", $record['prodimagefile']);
             $end = end($image_pieces);
             if (empty($end)) {
                 array_pop($image_pieces);
             }
             foreach ($image_pieces as $key => $value) {
                 $temp_key = $key + 1;
                 $image = PostToRemoteFileAndGetResponse($value);
                 if ($image) {
                     // Place it in our images directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir($imageDirectory . "/" . $randomDir)) {
                         if (!@mkdir($imageDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $fileName = $randomDir . "/" . GenRandFileName(basename($value));
                     if (!@file_put_contents($imageDirectory . "/" . $fileName, $image)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageUnableToMove');
                     } else {
                         if (!is_array(@getimagesize($imageDirectory . "/" . $fileName))) {
                             @unlink($imageDirectory . "/" . $fileName);
                             $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageInvalidFile');
                         } else {
                             $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "large");
                             $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                             if ($hasThumb == false) {
                                 if ($key == 0) {
                                     $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName);
                                     if ($thumbName) {
                                         $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                     }
                                     $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "tiny");
                                     if ($tinyName) {
                                         $productImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                     }
                                 }
                                 $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "medium");
                                 if ($mediumName) {
                                     $productImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                                 } else {
                                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                 }
                             }
                         }
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageDoesntExist');
                 }
             }
         } else {
             // This file exists, can be imported
             $image_pieces = preg_split("/[;,]/", $record['prodimagefile']);
             $end = end($image_pieces);
             if (empty($end)) {
                 array_pop($image_pieces);
             }
             foreach ($image_pieces as $key => $value) {
                 $temp_key = $key + 1;
                 if (file_exists($imageDirectory . "/import/" . $value)) {
                     // Move it to our images directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir($imageDirectory . "/" . $randomDir)) {
                         if (!@mkdir($imageDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $baseFileName = basename($value);
                     if ($baseFileName != $value) {
                         $localDirectory = dirname($value) . "/";
                     } else {
                         $localDirectory = '';
                     }
                     $fileName = $randomDir . "/" . GenRandFileName($baseFileName);
                     if (!@copy($imageDirectory . "/import/" . $value, $imageDirectory . "/" . $fileName)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageUnableToMove');
                     } else {
                         $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "large");
                         $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                         // Does a thumbnail file exist?
                         $thumbFile = "thumb_" . $baseFileName;
                         if ($key == 0) {
                             if (file_exists($imageDirectory . "/import/" . $localDirectory . $thumbFile)) {
                                 $thumbName = $randomDir . "/" . GenRandFileName($thumbFile);
                                 if (@copy($imageDirectory . "/import/" . $localDirectory . $thumbFile, $imageDirectory . "/" . $thumbName)) {
                                     $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                 }
                             } else {
                                 $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName);
                                 if ($thumbName) {
                                     $productImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                 }
                                 // Still need to generate "tiny" thumbnail
                                 $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "tiny");
                                 if ($tinyName) {
                                     $productImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                 }
                             }
                         }
                         $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateThumb($fileName, "medium");
                         if ($mediumName) {
                             $productImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                         }
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageDoesntExist');
                 }
             }
         }
     }
     // Do we have an install image? We need to deal with it after product images added by blessen
     $productInstallImages = array();
     if (isset($record['prodinstallimagefile']) && $record['prodinstallimagefile'] != '') {
         // Is this a remote file?
         $InstallDirectory = ISC_BASE_PATH . "/install_images";
         if (isc_substr(isc_strtolower($record['prodinstallimagefile']), 0, 7) == "http://") {
             // Need to fetch the remote file
             $image_pieces = preg_split("/[;,]/", $record['prodinstallimagefile']);
             $end = end($image_pieces);
             if (empty($end)) {
                 array_pop($image_pieces);
             }
             foreach ($image_pieces as $key => $value) {
                 $temp_key = $key + 1;
                 $image = PostToRemoteFileAndGetResponse($value);
                 if ($image) {
                     // Place it in our images directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir($InstallDirectory . "/" . $randomDir)) {
                         if (!@mkdir($InstallDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $fileName = $randomDir . "/" . GenRandFileName(basename($value));
                     if (!@file_put_contents($InstallDirectory . "/" . $fileName, $image)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageUnableToMove');
                     } else {
                         if (!is_array(@getimagesize($InstallDirectory . "/" . $fileName))) {
                             @unlink($InstallDirectory . "/" . $fileName);
                             $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageInvalidFile');
                         } else {
                             $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "large");
                             $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                             if ($hasThumb == false) {
                                 if ($key == 0) {
                                     $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName);
                                     if ($thumbName) {
                                         $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                     }
                                     $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "tiny");
                                     if ($tinyName) {
                                         $productInstallImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                     } else {
                                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                     }
                                 }
                                 $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "medium");
                                 if ($mediumName) {
                                     $productInstallImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                                 } else {
                                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageCorrupt');
                                 }
                             }
                         }
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageDoesntExist');
                 }
             }
         } else {
             // This file exists, can be imported
             $image_pieces = preg_split("/[;,]/", $record['prodinstallimagefile']);
             $end = end($image_pieces);
             if (empty($end)) {
                 array_pop($image_pieces);
             }
             foreach ($image_pieces as $key => $value) {
                 $temp_key = $key + 1;
                 if (file_exists($InstallDirectory . "/import/" . $value)) {
                     // Move it to our images directory
                     $randomDir = strtolower(chr(rand(65, 90)));
                     if (!is_dir($InstallDirectory . "/" . $randomDir)) {
                         if (!@mkdir($InstallDirectory . "/" . $randomDir, 0777)) {
                             $randomDir = '';
                         }
                     }
                     // Generate a random filename
                     $baseFileName = basename($value);
                     if ($baseFileName != $value) {
                         $localDirectory = dirname($value) . "/";
                     } else {
                         $localDirectory = '';
                     }
                     $fileName = $randomDir . "/" . GenRandFileName($baseFileName);
                     if (!@copy($InstallDirectory . "/import/" . $value, $InstallDirectory . "/" . $fileName)) {
                         $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageUnableToMove');
                     } else {
                         $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "large");
                         $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 0, "imagesort" => $temp_key);
                         // Does a thumbnail file exist?
                         $thumbFile = "thumb_" . $baseFileName;
                         if ($key == 0) {
                             if (file_exists($InstallDirectory . "/import/" . $localDirectory . $thumbFile)) {
                                 $thumbName = $randomDir . "/" . GenRandFileName($thumbFile);
                                 if (@copy($InstallDirectory . "/import/" . $localDirectory . $thumbFile, $InstallDirectory . "/" . $thumbName)) {
                                     $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                 }
                             } else {
                                 $thumbName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName);
                                 if ($thumbName) {
                                     $productInstallImages[] = array("imagefile" => $thumbName, "imageisthumb" => 1, "imagesort" => 0);
                                 }
                                 // Still need to generate "tiny" thumbnail
                                 $tinyName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "tiny");
                                 if ($tinyName) {
                                     $productInstallImages[] = array("imagefile" => $tinyName, "imageisthumb" => 2, "imagesort" => 0);
                                 }
                             }
                         }
                         $mediumName = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_AutoGenerateInsThumb($fileName, "medium");
                         if ($mediumName) {
                             $productInstallImages[] = array("imagefile" => $mediumName, "imageisthumb" => 3, "imagesort" => $temp_key);
                         }
                     }
                 } else {
                     $this->ImportSession['Results']['Warnings'][] = $record['prodcode'] . GetLang('ImportProductImageDoesntExist');
                 }
             }
         }
     }
     // If this is an update then we have to merge in the existing information that is NOT in the CSV file
     if (is_array($existing)) {
         $record = $record + $existing;
     }
     // Apply any default data
     $defaults = array('prodistaxable' => 1, 'prodprice' => 0, 'prodcostprice' => 0, 'prodretailprice' => 0, 'prodsaleprice' => 0, 'prodsearchkeywords' => '', 'prodsortorder' => 0, 'prodvisible' => 1, 'prodfeatured' => 0, 'prodrelatedproducts' => '', 'prodoptionsrequired' => 0, 'prodfreeshipping' => 0, 'prodlayoutfile' => '', 'prodtags' => '', 'prodmyobasset' => '', 'prodmyobincome' => '', 'prodmyobexpense' => '', 'prodpeachtreegl' => '', 'price_log' => '', 'SKU_last_update_time' => '', 'price_update_time' => '', 'unilateralprice' => '', 'testdata' => 'No', 'prodalternates' => '', 'skubarcode' => '');
     $record += $defaults;
     // Does the series already exist? //blessen
     $seriesId = 0;
     if (isset($record['product_series']) && $record['product_series'] != '') {
         $query = sprintf("select seriesid from [|PREFIX|]brand_series where lower(seriesname)='%s'", $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($record['product_series'])));
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         if ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
             $seriesId = $row['seriesid'];
         } else {
             $newSeries = array("brandid" => $brandId, "seriesname" => $record['product_series']);
             $seriesId = $GLOBALS['ISC_CLASS_DB']->InsertQuery("brand_series", $newSeries);
             $seriesId = $GLOBALS['ISC_CLASS_DB']->LastId();
         }
     }
     if (!isset($record['prodinvtrack'])) {
         $record['prodinvtrack'] = 0;
     }
     if (isset($record['prodfile']) && $record['prodfile'] != '') {
         $productType = 2;
     } else {
         if (isset($existing['prodtype']) && isId($existing['prodtype'])) {
             $productType = (int) $existing['prodtype'];
         } else {
             $productType = 1;
         }
     }
     if (isset($record['prodistaxable'])) {
         $record['prodistaxable'] = $this->StringToYesNoInt($record['prodistaxable']);
     }
     $record['proddesc'] = str_replace("ยฎ", "&reg;", $record['proddesc']);
     // This is our product
     $productData = array("prodname" => $newprodname, "prodcode" => @$record['prodcode'], "proddesc" => @$record['proddesc'], "prodsearchkeywords" => @$record['prodsearchkeywords'], "prodtype" => $productType, "prodprice" => DefaultPriceFormat($record['prodprice']), "prodcostprice" => DefaultPriceFormat($record['prodcostprice']), "prodretailprice" => DefaultPriceFormat($record['prodretailprice']), "prodsaleprice" => DefaultPriceFormat($record['prodsaleprice']), "prodavailability" => @$record['prodavailability'], "prodsortorder" => $record['prodsortorder'], "prodvisible" => $record['prodvisible'], "prodfeatured" => $record['prodfeatured'], "prodrelatedproducts" => $record['prodrelatedproducts'], "prodinvtrack" => (int) @$record['prodinvtrack'], "prodcurrentinv" => (int) @$record['prodcurrentinv'], "prodlowinv" => (int) @$record['prodlowinv'], "prodoptionsrequired" => $record['prodoptionsrequired'], "prodwarranty" => @$record['prodwarranty'], "prodheight" => (double) @$record['prodheight'], "prodweight" => (double) @$record['prodweight'], "prodwidth" => (double) @$record['prodwidth'], "proddepth" => (double) @$record['proddepth'], "prodfreeshipping" => $record['prodfreeshipping'], "prodfixedshippingcost" => DefaultPriceFormat(@$record['prodfixedshippingcost']), "prodbrandid" => (int) $brandId, "prodcats" => $cats, "prodpagetitle" => @$record['prodpagetitle'], "prodmetakeywords" => @$record['prodmetakeywords'], "prodmetadesc" => @$record['prodmetadesc'], "prodlayoutfile" => $record['prodlayoutfile'], "prodistaxable" => $record['prodistaxable'], 'prodvendorid' => $vendorId, 'prodtags' => $record['prodtags'], "prodvendorprefix" => $record['prodvendorprefix'], "proddescfeature" => $record['proddescfeature'], "prodmfg" => $record['prodmfg'], "jobberprice" => $record['jobberprice'], "mapprice" => $record['mapprice'], "alternativecategory" => $record['alternativecategory'], "complementaryupcharge" => $record['complementaryupcharge'], "ourcost" => $record['ourcost'], "package_length" => $record['package_length'], "package_height" => $record['package_height'], "package_weight" => $record['package_weight'], "package_width" => $record['package_width'], "brandseriesid" => $seriesId, "future_retail_price" => $record['future_retail_price'], "future_jobber_price" => $record['future_jobber_price'], "prod_instruction" => $record['prod_instruction'], "prod_article" => $record['prod_article'], "skubarcode" => $record['skubarcode'], "install_time" => $record['install_time']);
     /**
      * The variation is part of the product record, so it will have to be attached to the record if this is an
      * update AND the existing product already has a variation
      */
     if (is_array($existing) && isId($existing['prodvariationid'])) {
         $productData['prodvariationid'] = $existing['prodvariationid'];
     }
     if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
         $productData['prodvendorid'] = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId();
     }
     $empty = array();
     // Save it
     $err = '';
     if (isset($this->ImportSession['OverrideDuplicates']) && $this->ImportSession['OverrideDuplicates'] == 1) {
         foreach ($productData as $key => $value) {
             if ($value == "" and isset($existing[$key])) {
                 $productData[$key] = $existing[$key];
             }
             if ($value == "<BLANK>") {
                 $productData[$key] = "";
             }
         }
         $pricelog = $existing['price_log'];
         $pricelogtime = $existing['price_update_time'];
         $splitprice = split(',', $pricelog);
         $oldprice = end($splitprice);
         if ($oldprice != $productData['prodprice']) {
             $productData['price_log'] = $pricelog . "," . $productData['prodprice'];
             $productData['price_update_time'] = date('Y-m-d H:i:s');
         } else {
             $productData['price_log'] = $pricelog;
             $productData['price_update_time'] = $pricelogtime;
         }
         //fixed values in re-import
         $productData['SKU_last_update_time'] = date('Y-m-d H:i:s');
         if ($existing['prodcode'] != "") {
             $productData['prodcode'] = $existing['prodcode'];
         }
         if ($existing['prodvendorid'] != "") {
             $productData['prodvendorid'] = $existing['prodvendorid'];
         }
         if ($existing['prodbrandid'] != "") {
             $productData['prodbrandid'] = $existing['prodbrandid'];
         }
     }
     // temp declaraton to avoid entering in to system log.
     $productData += $defaults;
     foreach ($productData as $key => $value) {
         if (!isset($productData[$key])) {
             $productData[$key] = "";
         }
     }
     if ($this->ImportSession['Importastest'] == 1) {
         $productData['testdata'] = "Yes";
         $productData['prodvisible'] = 0;
     }
     $added_or_not = $GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_CommitImportProduct($productId, $productData, $empty, $empty, $empty, $empty, $err, $empty, true);
     if ($added_or_not == 1) {
         // there is a problem , if multiple category present
         if (isset($GLOBALS['NewProductId']) and $GLOBALS['NewProductId'] != "") {
             $sqlinsert2 = "INSERT INTO `isc_import_variations` ( `productid`, `prodcode` , ";
             $values = ") VALUES (" . $GLOBALS['NewProductId'] . ", '" . $record['prodcode'] . "' ,";
             for ($i = 0; $i < count($selected); $i++) {
                 $fieldname = $selected[$i];
                 $thevalue = rtrim($record[$fieldname], ";");
                 $sqlinsert2 .= "`" . $fieldname . "` ,";
                 $values .= "'" . $thevalue . "',";
                 // VQenginetype validation checking
                 if ($fieldname == "VQenginetype" and $thevalue != "") {
                     $thevalue = $engtype;
                 }
                 // VQliter validation checking
                 if ($fieldname == "VQliter" and $thevalue != "") {
                     $thevalue = $liter;
                 }
                 // only for make search fast
                 if ($thevalue != "") {
                     $sql = "INSERT INTO `isc_qualifier_value` (`pid`, `qid`, `q_value` , `row_no`) VALUES ('" . $GLOBALS['NewProductId'] . "', '" . $_SESSION['qualifiers_name'][$fieldname] . "', '" . $thevalue . "' , '" . $_SESSION['row_no'] . "')";
                     mysql_query($sql);
                 }
                 // only for made search fast end
             }
             $_SESSION['row_no']++;
             $sqlinsert2 .= "`bedsize_generalname` , `cabsize_generalname` ";
             $values .= "'" . $generalize_bedvalue . "', '" . $generalize_cabvalue . "'";
             $joinedsql = $sqlinsert2 . $values . " ) ";
             mysql_query($joinedsql);
             //complementary items  ;
             $record['complementaryitems'] = str_replace('โ€', '"', $record['complementaryitems']);
             $record['complementaryitems'] = str_replace('โ€œ', '"', $record['complementaryitems']);
             $comData = array("complementaryitems" => $record['complementaryitems'], "variationid" => mysql_insert_id(), "productid" => $GLOBALS['NewProductId']);
             $GLOBALS['ISC_CLASS_DB']->InsertQuery("application_data", $comData);
         }
     }
     if ($productId == 0) {
         $productId = $GLOBALS['NewProductId'];
     }
     // Are there any images?
     if (count($productImages) > 0) {
         $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_images', "WHERE imageprodid='" . $productId . "'");
         foreach ($productImages as $image) {
             $image['imageprodid'] = $productId;
             $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_images", $image);
         }
     }
     // Are there any Install images? blessen
     if (count($productInstallImages) > 0) {
         $GLOBALS['ISC_CLASS_DB']->DeleteQuery('install_images', "WHERE imageprodid='" . $productId . "'");
         foreach ($productInstallImages as $image) {
             $image['imageprodid'] = $productId;
             $GLOBALS['ISC_CLASS_DB']->InsertQuery("install_images", $image);
         }
     }
     // Are there any Install videos ? blessen
     if ($record['prodinstallvideo'] != "") {
         $productInstallVideos = array();
         $video_pieces = preg_split("/[;,]/", $record['prodinstallvideo']);
         $end = end($video_pieces);
         if (empty($end)) {
             array_pop($video_pieces);
         }
         foreach ($video_pieces as $key => $values) {
             $productInstallVideos[] = array("videofile" => $values, "videotype" => 1, "videoprodid" => $productId);
         }
         if (count($productInstallVideos) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('install_videos', "WHERE videoprodid='" . $productId . "'");
             foreach ($productInstallVideos as $video) {
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("install_videos", $video);
             }
         }
     }
     // Are there any product videos ? blessen audio_clip
     if ($record['prodvideo'] != "") {
         $productVideos = array();
         $video_pieces = preg_split("/[;,]/", $record['prodvideo']);
         $end = end($video_pieces);
         if (empty($end)) {
             array_pop($video_pieces);
         }
         foreach ($video_pieces as $key => $values) {
             $productVideos[] = array("videofile" => $values, "videotype" => 1, "videoprodid" => $productId);
         }
         if (count($productVideos) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_videos', "WHERE videoprodid='" . $productId . "'");
             foreach ($productVideos as $video) {
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_videos", $video);
             }
         }
     }
     // Are there any product audio_clip ? blessen
     if ($record['audio_clip'] != "") {
         $product_audio_clip = array();
         $audio_pieces = preg_split("/[;,]/", $record['audio_clip']);
         $end = end($audio_pieces);
         if (empty($end)) {
             array_pop($audio_pieces);
         }
         foreach ($audio_pieces as $key => $values) {
             $product_audio_clip[] = array("audiofile" => $values, "audiotype" => 1, "audioprodid" => $productId);
         }
         if (count($product_audio_clip) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('audio_clips', "WHERE audioprodid='" . $productId . "'");
             foreach ($product_audio_clip as $audio) {
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("audio_clips", $audio);
             }
         }
     }
     // Are there any product article file ? blessen
     if ($record['article_file'] != "") {
         $product_article = array();
         $article_pieces = preg_split("/[;,]/", $record['article_file']);
         $end = end($article_pieces);
         if (empty($end)) {
             array_pop($article_pieces);
         }
         foreach ($article_pieces as $key => $values) {
             $product_article[] = array("articlefile" => $values, "articletype" => 1, "articleprodid" => $productId);
         }
         if (count($product_article) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('article_files', "WHERE articleprodid='" . $productId . "'");
             foreach ($product_article as $article) {
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("article_files", $article);
             }
         }
     }
     // Are there any product instruction_file  ? blessen
     if ($record['instruction_file'] != "") {
         $product_instruction = array();
         $instruction_pieces = preg_split("/[;,]/", $record['instruction_file']);
         $end = end($instruction_pieces);
         if (empty($end)) {
             array_pop($instruction_pieces);
         }
         foreach ($instruction_pieces as $key => $values) {
             $product_instruction[] = array("instructionfile" => $values, "instructiontype" => 1, "instructionprodid" => $productId);
         }
         if (count($product_instruction) > 0) {
             $GLOBALS['ISC_CLASS_DB']->DeleteQuery('instruction_files', "WHERE instructionprodid='" . $productId . "'");
             foreach ($product_instruction as $instruction) {
                 $GLOBALS['ISC_CLASS_DB']->InsertQuery("instruction_files", $instruction);
             }
         }
     }
     // Are there any product files?
     if (count($productFiles) > 0) {
         foreach ($productFiles as $file) {
             $file['productid'] = $productId;
             $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_downloads", $file);
         }
     }
     ++$this->ImportSession['Results']['Imported'];
     ++$this->ImportSession['Results']['SuccessCount'];
 }
	/**
	 * Method: verify_signature
	 */
	private function verifySignature($parameters, $urlEndPoint){
		// Switch hostnames
		if (stripos($parameters[self::CERTIFICATE_URL_KEYNAME], self::FPS_SANDBOX_ENDPOINT) === 0){
			$fpsServiceEndPoint = self::FPS_SANDBOX_ENDPOINT;
		}
		elseif (stripos($parameters[self::CERTIFICATE_URL_KEYNAME], self::FPS_PROD_ENDPOINT) === 0){
			$fpsServiceEndPoint = self::FPS_PROD_ENDPOINT;
		}

		$url = $fpsServiceEndPoint . '?Action=VerifySignature&UrlEndPoint=' . rawurlencode($urlEndPoint);

		$queryString = rawurlencode(http_build_query($parameters, '', '&'));
		//$queryString = str_replace(array('%2F', '%2B'), array('%252F', '%252B'), $queryString);

		$url .= '&HttpParameters=' . $queryString . '&Version=2008-09-17';

		$response = PostToRemoteFileAndGetResponse($url);
		$xml = new SimpleXMLElement($response);
		$result = (string) $xml->VerifySignatureResult->VerificationStatus;

		return ($result === 'Success');
	}