<?php

##########################################################################################
# 
# General options
# show_stores = on,off - view stores from magento database
# store = 'store_name' - generate datafeed with products from specific store
# description = on,off
# image = on,off
# add_vat = on,off
# currency = 'CURRENCY_CODE'
# 
##########################################################################################

set_time_limit(0);
ignore_user_abort();
error_reporting(E_ALL^E_NOTICE);
$_SVR = array();

$path_include = "app/Mage.php";

// Include configuration file
if(!file_exists($path_include)) {
	exit('<HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>Not Found</H1>Please ensure that this file is in the root directory, or make sure the path to the directory where the configure.php file is located is defined corectly above in $path_include variable</BODY></HTML>');
}
else {
	require_once $path_include;
}

// Get default store code
$default_store = Mage::app()->getStore();
$default_store_code = $default_store->getCode();

if (isset($_GET['show_stores']) && ($_GET['show_stores'] == 'on')) {
	$stores = Mage::app()->getStores();
	
	foreach ($stores as $i) {
		print $i->getCode() . "<br />";
	}
	exit;
}
if (isset($_GET['store']) && ($_GET['store'] != "")) {
	$store = $_GET['store'];
}
else {
	$store = $default_store_code;
}

Mage::app($store);

// Datafeed specific settings
$datafeed_separator = "|"; // Possible options are \t or |

// Define VAT value
$vat_value = 1.19; // 19%

// Description options - possible values on, off
if (isset($_GET['description'])){
	$show_description = ($_GET['description'] == "off") ? "off" : "on";
}
else {
	$show_description = "on";
}

if (isset($_GET['currency'])) {
	$currency_code = $_GET['currency'];
	$convert_price_to_currency = 1;
}

// Image options - possible values on, off
if (isset($_GET['image'])){
	$show_image = ($_GET['image'] == "off") ? "off" : "on";
}
else {
	$show_image = "on";
}

// Add VAT to prices
if (isset($_GET['add_vat'])){
	$add_vat = ($_GET['add_vat'] == "on") ? "on" : "off";
}
else {
	$add_vat = "off";
}

// Get current date
$datetime = date("Y-m-d G:i:s");

try{

	// Get store ID use this to filter products
	$storeId = Mage::app()->getStore()->getId(); 

	// Get shop currency
	$default_currency = Mage::getModel('directory/currency')->getConfigBaseCurrencies();
	$datafeed_default_currency = $default_currency[0];

	if (@$convert_price_to_currency == 1) {
		$currency_value_rate = Mage::getModel('directory/currency')->getCurrencyRates($datafeed_default_currency, $currency_code);
		$datafeed_currency = $currency_code;
	}
	else {
		$datafeed_currency = $datafeed_default_currency;
	}

	$GROUPED = array();

	// Get grouped products
	$grouped_products = Mage::getModel('catalog/product')->getCollection();
	$grouped_products->addAttributeToFilter('status', 1);//enabled
	$grouped_products->addAttributeToFilter('type_id', 'grouped');//catalog, search
	$grouped_products->addAttributeToSelect('*');
	$grouped_products->addStoreFilter($storeId); 
	$grouped_prodIds = $grouped_products->getAllIds();

	$grouped_product = Mage::getModel('catalog/product');
	
	foreach($grouped_prodIds as $grouped_productId) { 


		$grouped_product->load($grouped_productId);

		$grouped_prod_sku = $grouped_product->getSKU();
		
		// Get linked products 
        $LINKED = array();
        
		$grouped_product->getLinkInstance()->useGroupedLinks();

        foreach ($grouped_product->getGroupedLinkCollection() as $_link) {
            $LINKED[$_link->getLinkedProductId()] = $_link->getLinkedProductId();
        }
		
		$category_name = "";
		
		// Get the product categories            		
		foreach($grouped_product->getCategoryIds() as $_categoryId){
			$category = Mage::getModel('catalog/category')->load($_categoryId);
			if ($category->getName() && $category_name) {
				$category_name .= " > " . $category->getName();
			}
			else {
				$category_name .= $category->getName();
			}
	    }
		
		$grouped_prod_url = function_to_get_product_url($grouped_product->getProductUrl());

		if ($show_image == "off"){
			$grouped_prod_image = "";		
		}
		else {
			$grouped_prod_image = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$grouped_product->getImage();
		}

		$grouped_prod_desc = $grouped_product->getDescription();
		
		foreach ($LINKED as $_linked_id) {
			$GROUPED[$_linked_id] = array();
			$GROUPED[$_linked_id]['prod_sku'] = $grouped_prod_sku;
			$GROUPED[$_linked_id]['category_name'] = $category_name;
			$GROUPED[$_linked_id]['prod_url'] = $grouped_prod_url;
			$GROUPED[$_linked_id]['prod_desc'] = $grouped_prod_desc;
			$GROUPED[$_linked_id]['prod_image'] = $grouped_prod_image;
		}
		
	}

	// Get bundle products
	$grouped_products = Mage::getModel('catalog/product')->getCollection();
	$grouped_products->addAttributeToFilter('status', 1);//enabled
	$grouped_products->addAttributeToFilter('type_id', 'bundle');//catalog, search
	$grouped_products->addAttributeToSelect('*');
	$grouped_products->addStoreFilter($storeId);
	$grouped_prodIds = $grouped_products->getAllIds();
	
	$grouped_product = Mage::getModel('catalog/product');

	foreach($grouped_prodIds as $grouped_productId) { 

		$grouped_product->load($grouped_productId);

		$grouped_prod_sku = $grouped_product->getSKU();
		
		// Get linked products 
        $LINKED = array();
		
		$grouped_product->getLinkInstance()->useGroupedLinks();

		foreach ($grouped_product->getRelatedLinkCollection() as $_link) {
			$LINKED[$_link->getLinkedProductId()] = $_link->getLinkedProductId();
		}
		
		$category_name = "";
		
		// Get the product categories            		
		foreach($grouped_product->getCategoryIds() as $_categoryId){
			$category = Mage::getModel('catalog/category')->load($_categoryId);
			if ($category->getName() && $category_name) {
				$category_name .= " > " . $category->getName();
			}
			else {
				$category_name .= $category->getName();
			}
	    }
		
		$grouped_prod_url = function_to_get_product_url($grouped_product->getProductUrl());

		if ($show_image == "off"){
			$grouped_prod_image = "";		
		}
		else {
			$grouped_prod_image = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$grouped_product->getImage();
		}

		$grouped_prod_desc = $grouped_product->getDescription();
		
		foreach ($LINKED as $_linked_id) {
			$GROUPED[$_linked_id] = array();
			$GROUPED[$_linked_id]['prod_sku'] = $grouped_prod_sku;
			$GROUPED[$_linked_id]['category_name'] = $category_name;
			$GROUPED[$_linked_id]['prod_url'] = $grouped_prod_url;
			$GROUPED[$_linked_id]['prod_desc'] = $grouped_prod_desc;
			$GROUPED[$_linked_id]['prod_desc'] = $grouped_prod_image;
		}
		
	}

	// Get configurable products
	$conf_products = Mage::getModel('catalog/product')->getCollection();
	$conf_products->addAttributeToFilter('status', 1);//enabled
	$conf_products->addAttributeToFilter('type_id', 'configurable');//catalog, search
	$conf_products->addAttributeToSelect('*');
	$conf_products->addStoreFilter($storeId);
	$conf_prodIds = $conf_products->getAllIds();

	$conf_product = Mage::getModel('catalog/product');
	
	foreach($conf_prodIds as $conf_productId) { 

		$conf_product->load($conf_productId);
		
		$conf_prod_sku = $conf_product->getSKU();
		
		// Get linked products
        $LINKED = array();
        
		$grouped_product->getLinkInstance()->useRelatedLinks();

        foreach ($grouped_product->getRelatedLinkCollection() as $_link) {
            $LINKED[$_link->getLinkedProductId()] = $_link->getLinkedProductId();
        }
		
		$category_name = "";
		
		// Get the product categories            		
		foreach($conf_product->getCategoryIds() as $_categoryId){
			$category = Mage::getModel('catalog/category')->load($_categoryId);
			if ($category->getName() && $category_name) {
				$category_name .= " > " . $category->getName();
			}
			else {
				$category_name .= $category->getName();
			}
	    }
		
		$conf_prod_url = function_to_get_product_url($conf_product->getProductUrl());
		
		$conf_prod_desc = $conf_product->getDescription();
		$conf_prod_price = $conf_product->getPrice();
		
		if ($show_image == "off"){
			$conf_prod_image = "";		
		}
		else {
			$conf_prod_image = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product' . $conf_product->getImage();
		}
		
		foreach ($LINKED as $_linked_id) {
			$GROUPED[$_linked_id] = array();
			$GROUPED[$_linked_id]['prod_sku'] = $conf_prod_sku;
			$GROUPED[$_linked_id]['category_name'] = $category_name;
			$GROUPED[$_linked_id]['prod_url'] = $conf_prod_url;
			$GROUPED[$_linked_id]['prod_price'] = $conf_prod_price;
			$GROUPED[$_linked_id]['prod_image'] = $conf_prod_image;
			$GROUPED[$_linked_id]['prod_desc'] = $conf_prod_desc;
		}
		
	}
	
	// ******************************************************************************
	// Get the products
	$products = Mage::getModel('catalog/product')->getCollection();
	$products->addAttributeToFilter('status', 1);//enabled
	$products->addAttributeToFilter('visibility', 4);//catalog, search
	$products->addAttributeToFilter('type_id', 'simple');//catalog, search
	$products->addAttributeToSelect('*');
	$products->addStoreFilter($storeId);
	$prodIds = $products->getAllIds();
	


	// Array to check if product is already send
	$already_sent = array();
	
	foreach($prodIds as $productId) {

		$product = Mage::getModel('catalog/product');

		$product->load($productId);

		$prod_model = $product->getSku();	
		$prod_id = $product->getId();
		// If we've sent this one, skip the rest - this is to ensure that we do not get duplicate products
		if (@$already_sent[$prod_id] == 1) continue;
		$prod_name = $product->getName();

		if ($show_description == "off"){
			$prod_desc = "";	   
		}
		else {
			$prod_desc = $product->getDescription();
		}

		$prod_attribute_id = $product->getAttributeSetId();
		
		$prod_url = function_to_get_product_url($product->getProductUrl());

		if ($show_image == "off"){
			$prod_image = "";		
		}
		else {
			$prod_image = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage();
		}
	
		$prod_price = function_to_get_product_price($product);
		// $prod_price = $product->getPrice();

		// Add VAT to prices
		if ($add_vat == "on") {
			$prod_price = $prod_price * $vat_value;
		}

		if ($product->getResource()->getAttribute('manufacturer')) {
			$manufacturer = $product->getResource()->getAttribute('manufacturer')->getFrontend()->getValue($product);
			if ($manufacturer == "No") {
				$manufacturer = "";
			}
		}
		else {
			$manufacturer = "";
		}

		if ($product->getResource()->getAttribute('isbn')) {
			$isbn = $product->getResource()->getAttribute('isbn')->getFrontend()->getValue($product);
			$prod_model = $isbn;
		}
		else {
			$isbn = "";
		}

	    $category_name = "";		

		// Get the product categories            		
		foreach($product->getCategoryIds() as $_categoryId){
			$category = Mage::getModel('catalog/category')->load($_categoryId);
			if ($category->getName() && $category_name) {
				$category_name .= " > " . $category->getName();
			}
			else {
				$category_name .= $category->getName();
			}
	    }
		
		// Clean product name (new lines)
		$prod_name = str_replace("\n", "", strip_tags($prod_name));
		$prod_name = str_replace("\r", "", strip_tags($prod_name));
		$prod_name = str_replace("\t", " ", strip_tags($prod_name));

		if (isset($GROUPED[$prod_id])) {

			$category_name = $GROUPED[$prod_id]['category_name'];
			$prod_url = $GROUPED[$prod_id]['prod_url'];
			if ($show_description == "off"){
				$prod_desc = "";	   
			}
			else {
				$prod_desc = $GROUPED[$prod_id]['prod_desc'];
			}
			if (@$GROUPED[$prod_id]['prod_price'] > 0) {
				$prod_price = $GROUPED[$prod_id]['prod_price'];
			}
			else {
				$prod_price = $product->getPrice();
			}

			if ($GROUPED[$prod_id]['prod_image'] != '') {
				$prod_image = $GROUPED[$prod_id]['prod_image'];
			}
		}


		// Clean product names and descriptions (separators)
		if ($datafeed_separator == "\t") {
			// Continue... tabs were already removed
		}
		elseif ($datafeed_separator == "|") {
			$prod_name = str_replace("|", " ", strip_tags($prod_name));
			$prod_desc = str_replace("|", " ", $prod_desc);
		}
		else {
			print "Incorrect columns separator.";
			exit;
		}

		// Clean product description (Replace new line with <BR>). In order to make sure the code does not contains other HTML code it might be a good ideea to strip_tags()
		$prod_desc = replace_not_in_tags("\n", "<BR />", $prod_desc);
		$prod_desc = str_replace("\n", " ", $prod_desc);		
		$prod_desc = str_replace("\r", "", $prod_desc);
		$prod_desc = str_replace("\t", " ", $prod_desc);

		if (strpos($prod_image, "no_selection")) {
			$prod_image = "";
		}

		if ($category_name == "") {
			$category_name = "Home";
		}
		
		print $category_name . $datafeed_separator . 
		$manufacturer . $datafeed_separator . 
		$prod_model . $datafeed_separator . 
		$prod_id . $datafeed_separator . 
		$prod_name . $datafeed_separator . 
		$prod_desc . $datafeed_separator . 
		$prod_url . $datafeed_separator . 
		$prod_image . $datafeed_separator . 
		$prod_price . $datafeed_separator . 
		$datafeed_currency . 
		"\n";
		
		unset($product);

		$already_sent[$prod_id] = 1;
	}


}
catch(Exception $e){
	die($e->getMessage());
}

// Function to return the Product URL based on your product ID
function function_to_get_product_url($product_url){
	$current_file_name = basename($_SERVER['REQUEST_URI']);
	$product_url = str_replace($current_file_name, "index.php", $product_url);
	$product_url = str_replace("datafeed_magento", "index", $product_url);
	
	// Eliminate id session 
	$pos_SID = strpos( $product_url, "?SID");
	if ($pos_SID) {
		$product_url = substr($product_url, 0, $pos_SID);
	}
	return $product_url;
	
}

function replace_not_in_tags($find_str, $replace_str, $string) {
	
	$find = array($find_str);
	$replace = array($replace_str);	
	preg_match_all('#[^>]+(?=<)|[^>]+$#', $string, $matches, PREG_SET_ORDER);	
	foreach ($matches as $val) {	
		if (trim($val[0]) != "") {
			$string = str_replace($val[0], str_replace($find, $replace, $val[0]), $string);
		}
	}	
	return $string;
}

function function_to_get_product_price($product) {

	$_taxHelper  = Mage::helper('tax');

	if ( $product->getSpecialPrice() && (date("Y-m-d G:i:s") > $product->getSpecialFromDate() || !$product->getSpecialFromDate()) &&  (date("Y-m-d G:i:s") < $product->getSpecialToDate() || !$product->getSpecialToDate())){
		$price = $product->getSpecialPrice();
	} else {
		$price = $product->getPrice();
	}

	$price = $_taxHelper->getPrice($product, $price, true);
	return $price;
}

?>