Jump to content

xml feed issue with price


Vali Iacobescu

Recommended Posts

Hi,

I have a problem with a script file which collect data directly from database to output datas into xml format.

The problem is that the price extracted is "pre-tax retail price" and I actually need the "retail price with tax" to be outputed.
I don't know how to achieve that. Please help.

This is the link to the feed: https://scufita-rosie.ro/okazii_pronat.php

Here it is the code which collect the datas:

<?php

Okazii_Connector_Adapter_Prestashop::Run();

class Okazii_Connector_PlatformInfo{

	public $Name = '';
	public $Version = '';


}

class Okazii_Connector_Exception extends Exception
{
	const ADAPTER_PROPERTY_NOT_DEFINED = 51;
	
	const SERVICE_REQUEST_SIGNATURE_DECRYPT_ERROR	= 4001;
	const SERVICE_REQUEST_SIGNATURE_INVALID			= 4002;
	const SERVICE_REQUEST_IP_DENIED					= 4003;
	const SERVICE_REQUEST_INVALID_JSON				= 4004;
	
	const SERVICE_RPC_INVALID_CALLBACK				= 5001;
	const SERVICE_RPC_ADAPTER_NOT_LOADED			= 5002;
	const SERVICE_RPC_PLATFORM_NOT_INSTALLED		= 5003;
	const SERVICE_RPC_METHOD_NOT_FOUND				= 5004;
	const SERVICE_RPC_ACCESS_DENIED					= 5005;
	const SERVICE_RPC_INVALID_PARAMETERS			= 5006;
	
	const SERVICE_ADAPTER_NOT_FOUND					= 5015;
	
	const SERVICE_PLATFORM_NOT_DETECTED				= 5021;
	const SERVICE_PLATFORM_NOT_DETECTED_RELIABLE	= 5022;
}

class Okazii_Connector_Product
{
	public $ID;
	public $UniqueID;
	public $Title;
	public $Category;
	public $Description;
	/**
	 * @property $Price
	 * @property $DiscountPrice
	 */
	protected $Price;
	protected $DiscountPrice;
	public $Currency;
	public $Amount;
	public $Brand;
	public $InStock;
	public $GTIN;
	/**
	 * @property $Photos
	 * @property $Attributes
	 * @property $Stocks
	 */
	protected $Photos = array();
	protected $Attributes = array();
	protected $Stocks = array();

	public function AddPhoto(Okazii_Connector_Product_Photo $Photo) {
		$this->Photos[] = $Photo;
	}

	public function AddAttribute(Okazii_Connector_Product_Attribute $Attribute) {
		$this->Attributes[] = $Attribute;
	}
	
	public function AddStock(Okazii_Connector_Product_Stock $Stock)
	{
		$this->Stocks[] = $Stock;
	}
	
	public function __set($Property, $Value)
	{
		$SetterName = "Set{$Property}";
		if(method_exists($this, $SetterName)) {
			$this->$SetterName($Value);
			return true;
		} else return false;
	}
	
	public function __get($Property)
	{
		return $this->$Property;
	}
	
	protected function SetPrice($Price)
	{
		$this->Price = number_format((float)$Price, $decimals = 2, $decimalSep = '.', $thousandSep = '');
	}
	
	protected function SetDiscountPrice($Price)
	{
		$this->DiscountPrice = number_format((float)$Price, $decimals = 2, $decimalSep = '.', $thousandSep = '');
	}
	
}

class Okazii_Connector_Product_Photo
{
	public $URL;

	public function __construct($URL)
	{
		$this->URL = $URL;
	}
}

class Okazii_Connector_Product_Attribute
{
	public $Name;
	public $Value;
	
	public function __construct($AttributeName, $AttributeValue)
	{
		$this->Name = $AttributeName;
		$this->Value = $AttributeValue;
	}
}

class Okazii_Connector_Product_Stock
{
	public $Attributes = array();
	public $Amount;
	
	public function __construct($Amount)
	{
		$this->Amount = $Amount;
	}
	
	public function AddAttribute(Okazii_Connector_Product_Attribute $Attribute)
	{
		$this->Attributes[] = $Attribute;
	}
}


class Okazii_Connector_Output
{
	/**
	 * @var DOMDocument
	 */
	protected $XMLDocument;

	public function __construct()
	{
		$this->XMLDocument = new DOMDocument('1.0', 'UTF-8');
		#$this->XMLDocument->appendChild($this->XMLProducts = $this->XMLDocument->createElement('AUCTIONS'));
	}

	/*
		Functie folosita pentru a crea noduri care contin caractere speciale gen &
		pentru a nu primi eroarea : unterminated entity reference
	*/
	public function CreateElement($name, $value = null){
		$Element = $this->XMLDocument->createElement($name);
		$Element = $this->XMLDocument->importNode($Element);
		if( $value!==null ){
			$Element->appendChild(new DOMText($value));
		}
		return $Element;
	}
	public function AddItem(Okazii_Connector_Product $Product)
	{
		$XMLProduct = $this->CreateElement('AUCTION');

		if(strlen($Product->Description) < 3) {
			$Product->Description = $Product->Title;
		}

		if(!$Product->Category) {
			$Product->Category = '-';
		}

		$XMLProduct->appendChild($this->CreateElement('UNIQUEID', $Product->UniqueID));
		$XMLProduct->appendChild($this->CreateElement('TITLE', $Product->Title));
		$XMLProduct->appendChild($this->CreateElement('CATEGORY', $Product->Category));
		try {
			$XMLProduct->appendChild($this->CreateElement('DESCRIPTION'))->appendChild($this->XMLDocument->createCDATASection($Product->Description));
		} catch (Exception $e){}
		$XMLProduct->appendChild($this->CreateElement('PRICE', $Product->Price));

		if((int)$Product->DiscountPrice) {
			$XMLProduct->appendChild($this->CreateElement('DISCOUNT_PRICE', $Product->DiscountPrice));
		}

		$XMLProduct->appendChild($this->CreateElement('CURRENCY', $Product->Currency));
		$XMLProduct->appendChild($this->CreateElement('AMOUNT', $Product->Amount));

		if($Product->Brand) {
			$XMLProduct->appendChild($this->CreateElement('BRAND', $Product->Brand));
		}
		if($Product->InStock) {
			$XMLProduct->appendChild($this->CreateElement('IN_STOCK', $Product->InStock));
		}
		if($Product->GTIN) {
			$XMLProduct->appendChild($this->CreateElement('GTIN', $Product->GTIN));
		}


		if($Product->Photos) {
			$XMLProduct->appendChild($XMLProductPhotos = $this->CreateElement('PHOTOS'));
			foreach ($Product->Photos as $Photo) {
				$XMLProductPhotos->appendChild($this->CreateElement('URL', $Photo->URL));
			}
		}

		if($Product->Attributes) {
			$XMLProduct->appendChild($XMLProductAttributes = $this->CreateElement('ATTRIBUTES'));
			foreach ($Product->Attributes as $Attribute) {
				$XMLProductAttributes->appendChild($this->CreateElement(strtoupper($this->Slugify($Attribute->Name)), $Attribute->Value));
			}
		}

		if($Product->Stocks) {
			$XMLProduct->appendChild($XMLProductStocks = $this->CreateElement('STOCKS'));
			foreach ($Product->Stocks as $Stock) {
				$XMLProductStocks->appendChild($XMLProductStock = $this->CreateElement('STOCK'));
				$XMLProductStock->appendChild($this->CreateElement('AMOUNT', $Stock->Amount));
				foreach ($Stock->Attributes as $Attribute) {
					$XMLProductStock->appendChild($this->CreateElement(strtoupper($Attribute->Name), $Attribute->Value));
				}
			}
		}


		#$this->XMLProducts->appendChild($XMLProduct);

		echo $this->XMLDocument->saveXML($XMLProduct);
	}

	public function AddCategory()
	{

	}

	public function StartTag($Tag)
	{
		header('Content-type: text/xml');
		echo $this->XMLDocument->saveXML();
		echo '<OKAZII>';
		#echo '<OKAZII><' . strtoupper($Tag) . '>';
	}

	public function EndTag($Tag)
	{
		echo '</OKAZII>';
		#echo '</' . strtoupper($Tag) . '></OKAZII>';
		exit();
	}

	public function __destruct()
	{
		#echo $this->XMLDocument->saveXML();
	}

	protected function Slugify($String)
	{
		//Lower case everything
		$String = strtolower($String);
		//Make alphanumeric (removes all other characters)
		$String = preg_replace("/[^a-z0-9_\s-]/", "", $String);
		//Clean up multiple dashes or whitespaces
		$String = preg_replace("/[\s-]+/", " ", $String);
		//Convert whitespaces and underscore to dash
		//$String = preg_replace("/[\s_]/", "-", $String);
		$String = preg_replace("/[\s]/", "-", $String);

		if(is_numeric(substr($String,0,1))) {
		    $String = 'A-' . $String;
        }

		return $String;
	}
}


abstract class Okazii_Connector_Adapter
{
	protected $PlatformInitialized = false;
	protected $PlatformDirectory = '';
	protected $DEBUG = false;
	
	abstract protected function FetchProducts();

	abstract protected function FetchCategories();

	abstract protected function IsPlatformInstalled();

	abstract protected function LoadPlatform();

	abstract public function GetPlatformInfo();

	final public function __construct($DEBUG = false)
	{
		if ($DEBUG === true) {
			$this->DEBUG = true;
		} else {
			$this->DEBUG = false;
		}

		if(!isset($this->AdapterName))
			throw new Okazii_Connector_Exception('Invalid adapter - property AdapterName not defined', Okazii_Connector_Exception::ADAPTER_PROPERTY_NOT_DEFINED);

		if(!isset($this->AdapterVersion))
			throw new Okazii_Connector_Exception('Invalid adapter - property AdapterVersion not defined', Okazii_Connector_Exception::ADAPTER_PROPERTY_NOT_DEFINED);

		if (!$this->InitPlatform(realpath('.')) && !$this->InitPlatform(realpath('..'))) {
			return false;
		}
	}

	final public function InitPlatform($PlatformDirectory = '')
	{
		if($this->PlatformInitialized === true) {
			return true;
		}

		$this->PlatformDirectory = $PlatformDirectory;

		if($this->IsPlatformInstalled()) {
			$this->PlatformInitialized = $this->LoadPlatform();
		} else {
			$this->PlatformDirectory = '';
		}

		return $this->PlatformInitialized;
	}

	final public function ListProducts()
	{
		if(!$this->DEBUG) {
			$this->OutputXML = new Okazii_Connector_Output();
			$this->OutputXML->StartTag('AUCTIONS');
			$this->FetchProducts();
			$this->OutputXML->EndTag('AUCTIONS');
		} else {
			$this->FetchProducts();
			return print_r($this->Products, true);
		}
	}

	final public function ListCategories()
	{
		if(!$this->DEBUG) {
			$this->OutputXML = new Okazii_Connector_Output();
			$this->OutputXML->StartTag('CATEGORIES');
			$this->FetchCategories();
			$this->OutputXML->EndTag('CATEGORIES');
		} else {
			$this->FetchCategories();
			return print_r($this->Products, true);
		}
	}

	final protected function AddProduct(Okazii_Connector_Product $Product)
	{
		if (!$this->DEBUG)
			$this->OutputXML->AddItem($Product);
		else
			$this->Products[] = $Product;
	}

	final protected function AddCategory(Okazii_Connector_Product $Category)
	{
		if (!$this->DEBUG)
			$this->OutputXML->AddItem($Category);
		else
			$this->Categories[] = $Category;
	}

	final public function GetAdapterInfo()
	{
		return array(
			'Name'		=>	$this->AdapterName,
			'Version'	=>	$this->AdapterVersion
		);
	}

	final public static function Run()
	{
		if(isset($_GET['debug'])) {
			$DEBUG = true;
		} else {
			$DEBUG = false;
		}

		//Decomenteaza linia urmatoare pentru a fi debugging tot timpul activat
		//$DEBUG = true;

		$Adapter = new static($DEBUG);

		if(!$Adapter->InitPlatform()) {
			echo "Platform " . $Adapter->AdapterName . "not installed.";
			exit();
		}

		if(isset($_SERVER['PATH_INFO'])) {
			switch ($_SERVER['PATH_INFO']) {
				case '/PlatformInfo':
					echo "<pre><strong>";
					print_r($Adapter->GetPlatformInfo());
					exit();
					break;
				case '/AdapterInfo':
					echo "<pre><strong>";
					print_r($Adapter->GetAdapterInfo());
					exit();
					break;
				case '/PHPInfo':
					echo "<pre><strong>";
					print_r(phpversion());
					exit();
					break;
				case '/DebugInfo':
					if(method_exists($Adapter, 'GetDebugInfo')){
						return $Adapter->GetDebugInfo();
					}
					else {
						return "Error. NonExistent";
					}
					exit();
					break;
			}
		}
		//se face echo pentru a se afisa si debugging info, daca este setat
		//DEBUG
		echo $Adapter->ListProducts();
	}
}


class Okazii_Connector_Adapter_Prestashop extends Okazii_Connector_Adapter{
	protected $AdapterName = 'Prestashop';
	protected $AdapterVersion = '1.6.1.0';

	private $resConnection = NULL;

	private $arrTables = array();

	private $intIdLanguage = '';


	private $blnCurrencyByIso = false;
	private $strCurrency;
	private $dblConversionRate;
	private $strImageType = NULL;
	private $arrCategories = NULL;
	private $arrManufacturers = NULL;
	
	public function GetPlatformInfo()
	{
		
		$strVersion = '';
		
		if (defined('AppKernel::VERSION'))
		{
			$strVersion = AppKernel::VERSION;
		}
		
		if (defined('_PS_VERSION_'))
		{
			$strVersion = _PS_VERSION_;
		}

		if(empty($strVersion))
		{
			return null;
		}
		
		$objPlatformInfo = new Okazii_Connector_PlatformInfo();
		$objPlatformInfo->Name = 'PrestaShop';
		$objPlatformInfo->Version = $strVersion;

		return $objPlatformInfo;
	}

	protected function IsPlatformInstalled(){
		if (file_exists($this->PlatformDirectory . '/config/defines.inc.php')){
			$strContent = file_get_contents($this->PlatformDirectory . '/config/defines.inc.php');
			if (strpos($strContent, 'PrestaShop')){
				return true;
			}
		}
		return false;
	}

	protected function LoadPlatform(){
		global $cookie;

		if (!(file_exists($this->PlatformDirectory . '/config/config.inc.php')
			&& file_exists($this->PlatformDirectory . '/init.php')
			&& file_exists($this->PlatformDirectory . '/config/settings.inc.php')
		)){
			return false;
		}

		require_once $this->PlatformDirectory . '/config/config.inc.php';
		require_once $this->PlatformDirectory . '/init.php';
		require_once $this->PlatformDirectory . '/config/settings.inc.php';
		require_once $this->PlatformDirectory . '/classes/Cookie.php';



		$this->resConnection = mysqli_connect(_DB_SERVER_, _DB_USER_, _DB_PASSWD_);
		mysqli_set_charset($this->resConnection, 'utf8');
		mysqli_select_db($this->resConnection, _DB_NAME_);
		$this->setTables();
		if(empty($cookie))
		{
			$cookie = new Cookie( 'ps' );
		}
		$this->intIdLanguage = $cookie->id_lang; // TODO: De vazut ce-i cu globala asta


		return true;
	}


	protected function FetchCategories(){

	}

	private function setTables(){
		$okazii_DbPrefix = _DB_PREFIX_;
		$this->arrDbTables = array(
			'attribute' => $okazii_DbPrefix.'attribute',
			'attribute_group_lang' => $okazii_DbPrefix.'attribute_group_lang',
			'attribute_group' => $okazii_DbPrefix.'attribute_group',
			'attribute_lang' => $okazii_DbPrefix.'attribute_lang',
			'category' => $okazii_DbPrefix.'category',
			'category_lang' => $okazii_DbPrefix.'category_lang',
			'configuration' => $okazii_DbPrefix.'configuration',
			'currency' => $okazii_DbPrefix.'currency',
			'image' => $okazii_DbPrefix.'image',
			'product' => $okazii_DbPrefix.'product',
			'product_lang' => $okazii_DbPrefix.'product_lang',
			'product_attribute' => $okazii_DbPrefix.'product_attribute',
			'product_attribute_shop' => $okazii_DbPrefix.'product_attribute_shop',
			'product_attribute_combination' => $okazii_DbPrefix.'product_attribute_combination',
			'manufacturer' => $okazii_DbPrefix.'manufacturer',
			'stock_available' => $okazii_DbPrefix.'stock_available',
			'tax' => $okazii_DbPrefix.'tax',
			'specific_price' => $okazii_DbPrefix.'specific_price',
			'category_product' => $okazii_DbPrefix.'category_product',
			'image_type' => $okazii_DbPrefix.'image_type'
		);

	}

	protected function getTableFields($strTable)
	{
		$arrReturn = [];
		$strQuery = 'desc ' . $strTable;
		
		$resResult = mysqli_query($this->resConnection, $strQuery);
		while ($arrItems = mysqli_fetch_assoc($resResult))
		{
			$arrReturn[] = $arrItems['Field'];
		}
		
		return $arrReturn;
	}
	
	protected function FetchProducts()
	{
		$strExtraFields = '';
		$arrFields = $this->getTableFields($this->arrDbTables['product_lang']);
		if(!empty($arrFields))
		{
			foreach($arrFields as $strField)
			{
				if($strField == 'available_now' || $strField == 'available_later')
				{
					$strExtraFields .= $this->arrDbTables['product_lang'] . '.' . $strField . ',';
				}
			}
		}
		
		$strQuery = 'SELECT
				'.$this->arrDbTables['product'].'.id_product,
				'.$this->arrDbTables['product'].'.quantity,
				'.$this->arrDbTables['product'].'.price,
				'.$this->arrDbTables['product_lang'].'.link_rewrite,
				'.$this->arrDbTables['product'].'.id_manufacturer,
				'.$this->arrDbTables['product'].'.id_category_default,
				'.$this->arrDbTables['product'].'.upc,
				'.$this->arrDbTables['product'].'.ean13,
				'.$this->arrDbTables['category_product'].'.id_category,
				'.$strExtraFields.'
				'.$this->arrDbTables['product_lang'].'.name,
				'.$this->arrDbTables['product_lang'].'.description,
				'.$this->arrDbTables['product_lang'].'.description_short
			FROM
				'.$this->arrDbTables['product'].'
			LEFT JOIN
				'.$this->arrDbTables['product_lang'].' ON '.$this->arrDbTables['product'].'.id_product = '.$this->arrDbTables['product_lang'].'.id_product AND '.$this->arrDbTables['product_lang'].'.id_lang = ' . $this->intIdLanguage . '
			LEFT JOIN
				'.$this->arrDbTables['category_product'].' ON '.$this->arrDbTables['product'].'.id_product = '.$this->arrDbTables['category_product'].'.id_product
			LEFT JOIN
				'.$this->arrDbTables['category'].' USING(id_category)
			WHERE
				'.$this->arrDbTables['product'].'.active = 1
			ORDER BY '.$this->arrDbTables['product'].'.id_product ASC, level_depth DESC, id_parent DESC
			';

		$resResult = mysqli_query($this->resConnection, $strQuery);
		while ($arrProduct = mysqli_fetch_assoc($resResult)){
			$this->AddProduct($this->getProductFromArray($arrProduct));
		}

	}

	private function getProductFromArray($arrProduct){
		$objProduct = new Okazii_Connector_Product();

		$objProduct->ID = $arrProduct['id_product'];
		$objProduct->UniqueID = $arrProduct['id_product'];
		$objProduct->Title = $arrProduct['name'];
		if (mb_strlen($arrProduct['description']) > 3){
			$objProduct->Description = $arrProduct['description'];
		} else if (mb_strlen($arrProduct['description_short'])) {
			$objProduct->Description = $arrProduct['description_short'];
		} else {
			$objProduct->Description = $arrProduct['name'];
		}
		$objProduct->Amount = $arrProduct['quantity'];

		if ($objProduct->Amount == 0){
			$objProduct->Amount = $this->getAmountFromStock($arrProduct['id_product']);
		}
		$objProduct->Category = $this->getCategoryString($arrProduct['id_category']);
		$objProduct->Currency = $this->getCurrency();
		$objProduct->Price = $arrProduct['price'];
		
		if(!empty($arrProduct['available_now']) && $objProduct->Amount > 0)
		{
			$objProduct->InStock = $arrProduct['available_now'];
		}
		
		if(!empty($arrProduct['gtin']))
		{
			$objProduct->GTIN = $arrProduct['gtin'];
		}
		else if(!empty($arrProduct['ean13']))
		{
			$objProduct->GTIN = $arrProduct['ean13'];
		}
		else if(!empty($arrProduct['isbn']))
		{
			$objProduct->GTIN = $arrProduct['isbn'];
		}
		
		$this->setProductImages($objProduct);
		$this->setProductBrand($objProduct, $arrProduct['id_manufacturer']);

		return $objProduct;
	}

	private function getCurrency(){
		if (!is_null($this->strCurrency)){
			return $this->strCurrency;
		}
		if ($this->blnCurrencyByIso){
			$strQuery = "SELECT * FROM " . $this->arrDbTables['currency'] . " WHERE iso_code = 'RON'";
			$resResult = mysqli_query($this->resConnection, $strQuery);
			if ($arrRow = mysqli_fetch_assoc($resResult)){
				$this->strCurrency = $arrRow['iso_code'];
				$this->dblConversionRate = $arrRow['conversion_rate'];
				return $this->strCurrency;
			}
		} else {
			$strQueryConfig = "SELECT * FROM " . $this->arrDbTables['configuration'] . " WHERE name = 'PS_CURRENCY_DEFAULT'";
			$resResultConfig = mysqli_query($this->resConnection, $strQueryConfig);
			if ($arrConfig = mysqli_fetch_assoc($resResultConfig)) {
				$strQuery = "SELECT * FROM " . $this->arrDbTables['currency'] . " WHERE id_currency = '" . $arrConfig['value'] . "'";
				$resResult = mysqli_query($this->resConnection, $strQuery);
				if ($arrRow = mysqli_fetch_assoc($resResult)){
					$this->strCurrency = $arrRow['iso_code'];
					$this->dblConversionRate = $arrRow['conversion_rate'];
					return $this->strCurrency;
				}
			}
		}
		return '';
	}

	private function getAmountFromStock($intProductId){
		$strQuery = 'SELECT quantity FROM ' . $this->arrDbTables['stock_available'] . ' WHERE id_product = ' . $intProductId  . ' AND id_product_attribute = 0';
		$resResult = mysqli_query($this->resConnection, $strQuery);
		$intAmount = 0;
		while ($arrRow = mysqli_fetch_assoc($resResult)){
			$intAmount += $arrRow['quantity'];
		}
		return $intAmount;
	}


	private function getCategoryString($intCategoryId){
		if (is_null($this->arrCategories)){
			$this->loadCategories();
		}
		$strCategoryString = '';
		$arrCategories = array();
		if ($intCategoryId >= 0){
			$blnSearchRoot = true;
			$intCurrentCategory = $intCategoryId;
			$i = 0;
			while ($blnSearchRoot){
				$arrCategories[] =  $this->arrCategories[$intCurrentCategory]['category'];
				if ($this->arrCategories[$intCurrentCategory]['parentid'] > 0){
					$intCurrentCategory = $this->arrCategories[$intCurrentCategory]['parentid'];
				} else {
					$blnSearchRoot = false;
				}
				if ($i++ == 10){
					break;
				}
			}
		}
		$strCategoryString = nl2br(str_replace(';', ' ', strip_tags(join(' > ', array_reverse($arrCategories)))));
		$strCategoryString = str_replace(array("\n", "\r", "\t"), " ", $strCategoryString);
		if (empty($strCategoryString)){
			return 'Catalog ' . $intCategoryId;
		}
		return $strCategoryString;
	}

	private function loadCategories(){
		$cookie = new Cookie('ps');
		$intLanguage = $cookie->id_lang;
		$this->arrCategories = array();
		$strQuery = 'SELECT
			    	' . $this->arrDbTables['category'] . '.id_category AS categoryid,
			        ' . $this->arrDbTables['category'] . '.id_parent AS parentid,
			        ' . $this->arrDbTables['category_lang'] . '.name AS category
				FROM
					' . $this->arrDbTables['category'] . '
				LEFT JOIN
					' . $this->arrDbTables['category_lang'] . ' ON ' . $this->arrDbTables['category'] . '.id_category = ' . $this->arrDbTables['category_lang'] . '.id_category
				';
		if (!empty($intLanguage)){
			$strQuery .= ' WHERE
					' .  $this->arrDbTables['category_lang'].'.id_lang = ' . $intLanguage . '
				';
		}
		$resResult = mysqli_query($this->resConnection, $strQuery);
		while ($arrRow = mysqli_fetch_assoc($resResult)){
			$this->arrCategories[$arrRow['categoryid']] = $arrRow;
		}
	}

	private function getImageType(){
		if (!is_null($this->strImageType)){
			return $this->strImageType;
		}
		$strQuery = "SELECT name FROM " . $this->arrDbTables['image_type'] . " WHERE width <= 1000 AND height <= 1000 AND products = 1 ORDER BY width DESC, height DESC LIMIT 1";
		$resResult = mysqli_query($this->resConnection, $strQuery);
		if ($arrRow = mysqli_fetch_assoc($resResult)){
			$this->strImageType = $arrRow['name'];
		}
		return $this->strImageType;

	}

	private function setProductBrand(Okazii_Connector_Product &$objProduct, $intManufacturerId){
		if (empty($intManufacturerId)){
			return;
		}
		if (is_null($this->arrManufacturers)){
			$strQuery = "SELECT id_manufacturer, name FROM `" . $this->arrDbTables['manufacturer'] . "`";
			$resResult = mysqli_query($this->resConnection, $strQuery);
			$this->arrManufacturers = array();
			while ($arrRow = mysqli_fetch_assoc($resResult)){
				$this->arrManufacturers[$arrRow['id_manufacturer']] = $arrRow['name'];
			}
		}
		if (isset($this->arrManufacturers[$intManufacturerId])){
			$objProduct->Brand = $this->arrManufacturers[$intManufacturerId];
		}
	}

	private function setProductImages(Okazii_Connector_Product &$objProduct){

		$arrImages = array();

		if (empty($this->getImageType())){
			return;
		}

		$strQuery = "SELECT id_image FROM " . $this->arrDbTables['image'] . " WHERE id_product = " . $objProduct->ID . " ORDER BY cover DESC, position ASC";
		$resResult = mysqli_query($this->resConnection, $strQuery);
		while ($arrRow = mysqli_fetch_assoc($resResult)){
			$strImagePath = '';
			$strPhotoUrlO = substr(_THEME_PROD_DIR_ . $objProduct->ID . "-" . $arrRow['id_image'] . ".jpg",1);
			$strPhotoUrlR = substr(_THEME_PROD_DIR_ . $objProduct->ID . "-" . $arrRow['id_image'] . "-" . $this->getImageType() . ".jpg",1);

			if (file_exists($this->PlatformDirectory . $strPhotoUrlO)){
				$arrSizeO = @getimagesize($strPhotoUrlO);
				$arrSizeR = @getimagesize($strPhotoUrlR);
				if ($arrSizeO[0] > $arrSizeR[0] || $arrSizeO[1] > $arrSizeR[1]){
					$strImagePath = $strPhotoUrlR;
				} else {
					$strImagePath = $strPhotoUrlO;
				}
			} else {
				$paths = '';
				for($i=0;$i<strlen($arrRow['id_image']);$i++){
					if($i<8)
						$paths .= $arrRow['id_image'][$i]."/";
				}
				$url_o = substr(_THEME_PROD_DIR_ . $paths . $arrRow['id_image'] . ".jpg",1);
				$url_r = substr(_THEME_PROD_DIR_ . $paths . $arrRow['id_image'] . "-" . $this->getImageType() . ".jpg",1);
				// sizes
				$size_o = @getimagesize($url_o);
				$size_r = @getimagesize($url_r);
				if($size_o[0] > $size_r[0] || $size_o[1] > $size_r[1])
					$strImagePath = $url_r;
				else
					$strImagePath = $url_o;

			}
			if (!empty($strImagePath)){
				$host = htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, "UTF-8");
				if(substr($host, -1) != "/"){
					$host .= "/";
				}

				$objPhoto = new Okazii_Connector_Product_Photo("http".((isset($_SERVER['HTTPS']))?"s":"")."://" . $host . $strImagePath);
				$objProduct->AddPhoto($objPhoto);
			}

		}
	}

}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...