<?php
define('FROOGLE_US_FTP_FILENAME','froogle_en_usd.txt');
function protype($pid)
{
	$c=mysql_connect(DB_SERVER,DB_SERVER_USERNAME,DB_SERVER_PASSWORD);
	//exist prant class
	mysql_select_db(DB_DATABASE);
	$pstr="select categories_description.categories_name,categories_description.categories_id from categories_description inner join categories on categories_description.categories_id=categories.parent_id where categories.categories_id=$pid and categories_description.language_id='4' limit 1";
	//echo($pstr);	
	$q=mysql_query($pstr);
	if ($r=mysql_fetch_object($q))
		{
			$str=str_replace("&nbsp;"," ",$r->categories_name);
			$str=str_replace("Others","Electronics Accessories",$str);
			return ($str);
		}
		//return str_replace("Others","Electronic accessories",str_replace("&nbsp;"," " ,$r->categories_name));
	else
		//no parent class
		{
			$cstr="select categories_name from categories_description where categories_id='$pid' and language_id='4'";
			//echo($cstr);
			$cq=mysql_query($cstr,$c);
			if ($cr=mysql_fetch_object($cq))
				{
					$str=str_replace("&nbsp;"," ",$cr->categories_name);
					$str=str_replace("Others","Electronics Accessories",$str);
					return ($str);
				}
				//return ($cr->categories_name);
				//return str_replace("Others","Electronic accessories",str_replace("&nbsp;"," " ,$cr->categories_name));
			else
				return "Electronic accessories";
		}
	mysql_close($c);
}
//
// Google Base Feed vX.03 - 2007-01-30
// Original Author unknown.
//

include('includes/application_top.php');
//  Start TIMER
//  -----------
$stimer = explode( ' ', microtime() );
$stimer = $stimer[1] + $stimer[0];
//  -----------

$OutFile = DIR_FS_DOCUMENT_ROOT."/feeds/".FROOGLE_US_FTP_FILENAME;
$destination_file = FROOGLE_US_FTP_FILENAME;  //"CHANGEME-filename-to-upload-to-froogle.txt" ;
$source_file = $OutFile;
//$imageURL = HTTP_SERVER . DIR_WS_CATALOG . DIR_WS_IMAGES;
$imageURL = HTTP_SERVER ."images/products_images/unfurl/";
$productURL = HTTP_SERVER .'product_info.php?products_id=';
$already_sent = array();

$home=DB_SERVER;
$user=DB_SERVER_USERNAME;
$pass=DB_SERVER_PASSWORD;
$base=DB_DATABASE;

$taxRate = 0; //default = 0 (e.g. for 17.5% tax use "$taxRate = 17.5;")
$taxCalc = ($taxRate/100) + 1;  //Do not edit
$convertCur = true; //default = false
$curType = "USD"; // Converts Currency to any defined currency (eg. USD, EUR, GBP)
if($convertCur)
{
	$productURL = HTTP_SERVER.'product_info.php?currency=' . $curType . '&products_id=';  // Product URL if Currency Conversion is enabled
}

// Mod by Ben - Use the Product and Category Descriptions of a specific language
$chooseLanguage = true; //default = false
$lang_code = "en";  // Language code of the description to use, eg. "en", "fr, "es", "de", etc.  Must match the one used in your shop in Localization -> Languages
if($chooseLanguage)
{
	if($convertCur)
	{
		$productURL = HTTP_SERVER .'product_info.php?language='. $lang_code .'&currency=' . $curType . '&products_id=';  // Product URL if Currency Conversion AND Language Selection is enabled
	}
	else
	{
		$productURL = HTTP_SERVER .'product_info.php?language='. $lang_code .'&products_id=';  // Product URL if Language Selection but NOT Currency Conversion is enabled
	}
}
// End mod by Ben - Use the Product and Category Descriptions of a specific language

// Mod by Ben - Define which localization of Google Base (which country) is this feed used for
$GB_localization = "us";  // Do not modify! - unless Google Base opens up other localized versions, e.g. Australiia.

//START Advance Optional Values

//(0=False 1=True) (optional_sec must be enabled to use any options)
$optional_sec = 1;   // Suggested to leave enabled if you use a specific language for your descriptions
//$instock = 0;
$instock = 1;
//$shipping = 0;
$shipping = 0;
$lowestShipping = "2.99";  //this is not binary.
//$brand = 0;
$brand = 0;
//$upc = 0;   //Not supported by default osC
$upc = 1;
$manufacturer_id = 0;  //Not supported by default osC
//$manufacturer_id = 1;
//$product_type = 0;
$product_type = 1;
//$currency = 0;
$currency = 1;
	$default_currency = "USD";  //this is not binary.
$feed_language = 1;   // Suggested to leave enabled if you use a specific language for your descriptions
$default_feed_language = $lang_code;  //this is not binary.
	//echo($default_feed_language);
//$ship_to = 0;
$ship_to = 1;
	$default_ship_to = "ALL"; //this is not binary, not supported by default osC for individual products.
$ship_from = 0;
//$ship_from = 1;
	$default_ship_from = "USD"; //this is not binary, not supported by default osC for individual products.

//END of Advance Optional Values

if (!($link=mysql_connect($home,$user,$pass)))
{
echo "Error when connecting itself to the data base";
exit();
}
if (!mysql_select_db( $base , $link ))
{
echo "Error the data base does not exist";
exit();
}

// Mod by Ben - Use the Product and Category Descriptions of a specific language
if($chooseLanguage)
{

	$lang_id=4; //set lang_id "en"
	// SQL query if Language Selection is enabled
	$sql = "
	SELECT concat( '" . $productURL . "' ,products.products_id) AS product_url,
	products_model AS prodModel, products_weight,
	manufacturers.manufacturers_name AS mfgName,
	manufacturers.manufacturers_id,
	products.products_id AS id,
	products.code,	
	categories.categories_id as cid,
	products_description.products_name AS name,
	products_description.keywords,
	products_description.products_description AS description,
	products.products_quantity AS quantity,
	products.products_status AS prodStatus,
	FORMAT( IFNULL(specials.specials_new_products_price, products.products_price) * " . $taxCalc . ",2) AS price,
	CONCAT( '" . $imageURL . "' ,products.products_image) AS image_url,
	products_to_categories.categories_id AS prodCatID,
	categories.parent_id AS catParentID,
	categories_description.categories_name AS catName
	
	FROM categories,
	categories_description,
	products,
	products_description,
	products_to_categories
	
	left join manufacturers on ( manufacturers.manufacturers_id = products.manufacturers_id )
	left join specials on ( specials.products_id = products.products_id AND ( ( (specials.expires_date > CURRENT_DATE) OR (specials.expires_date = 0) ) AND ( specials.status = 1 ) ) )
	
	WHERE products.products_id=products_description.products_id
	AND products.products_id=products_to_categories.products_id
	AND products_to_categories.categories_id=categories.categories_id
	AND categories.categories_id=categories_description.categories_id
	AND products.products_status != 0
	AND products.products_price != 0
	AND products.products_price != ''
	AND products_description.language_id = '" . $lang_id . "'
	AND categories_description.language_id = '" . $lang_id . "'
	ORDER BY
	products.products_id ASC
	";
	//echo($sql . "<br>");
}
//echo($sql);
// Mod by Ben - Use the Product and Category Descriptions of a specific language

$catInfo = "
SELECT
categories.categories_id AS curCatID,
categories.parent_id AS parentCatID,
categories_description.categories_name AS catName
FROM
categories,
categories_description
WHERE categories.categories_id = categories_description.categories_id
";

function findCat($curID, $catTempPar, $catTempDes, $catIndex)
{
	if( (isset($catTempPar[$curID])) && ($catTempPar[$curID] != 0) )
	{
		if(isset($catIndex[$catTempPar[$curID]]))
		{
			$temp=$catIndex[$catTempPar[$curID]];
		}
		else
		{
			$catIndex = findCat($catTempPar[$curID], $catTempPar, $catTempDes, $catIndex);
			$temp = $catIndex[$catTempPar[$curID]];
		}
	}
	if( (isset($catTempPar[$curID])) && (isset($catTempDes[$curID])) && ($catTempPar[$curID] == 0) )
	{
		$catIndex[$curID] = $catTempDes[$curID];
	}
	else
	{
		$catIndex[$curID] = $temp . " > " . $catTempDes[$curID];
	}
	return $catIndex;

}

$catIndex = array();
$catTempDes = array();
$catTempPar = array();
$processCat = mysql_query( $catInfo )or die( $FunctionName . ": SQL error " . mysql_error() . "| catInfo = " . htmlentities($catInfo) );
$no=0;
while ( $catRow = mysql_fetch_object( $processCat ) )
{
	$no++;
	$catKey = $catRow->curCatID;
	$catName = $catRow->catName;
	$catParID = $catRow->parentCatID;
	if($catName != "")
	{
		$catTempDes[$catKey]=$catName;
		$catTempPar[$catKey]=$catParID;
	}
}

foreach($catTempDes as $curID=>$des)  //don't need the $des
{
	$catIndex = findCat($curID, $catTempPar, $catTempDes, $catIndex);
}

$_strip_search = array(
"![\t ]+$|^[\t ]+!m", // remove leading/trailing space chars
'%[\r\n]+%m', // remove CRs and newlines
'%[,]+%m'); // remove CRs and newlines
$_strip_replace = array(
'',
' ',
' ');
$_cleaner_array = array(">" => "> ", "&reg;" => "", "?" => "", "&trade;" => "", "?" => "", "\t" => "", "	" => "");

if ( file_exists( $OutFile ) )
unlink( $OutFile );

//$output = "link \t title \t description \t label \t price \t image_link \t id";
$output = "link \t title \t description \t price \t image_link \t id";

//create optional section
//echo($optional_sec . "<br>");
if($optional_sec == 1)
{	
	if($instock == 1)
		$output .= "\t instock ";
	if($shipping == 1)
		$output .= "\t shipping ";
	if($brand == 1)
		$output .= "\t brand ";
	if($upc == 1)
		$output .= "\t upc ";
	if($manufacturer_id == 1)
		$output .= "\t manufacturer_id ";
	if($product_type == 1)
		$output .= "\t product_type ";
	if($currency == 1)
		$output .= "\t currency ";
	if($feed_language == 1)
		$output .= "\t language ";
	if($ship_to == 1)
		$output .= "\t ship_to ";
	if($ship_from == 1)
		$output .= "\t ship_from ";
}
$output .= "\n";
echo "sql=".$sql;
//echo ($output);
$result=mysql_query( $sql )or die( $FunctionName . ": SQL error " . mysql_error() . "| sql = " . htmlentities($sql) );

//Currency Information
if($convertCur)
{
	$sql3 = "
	SELECT
	currencies.value AS curUSD
	FROM
	currencies
	WHERE currencies.code = '$curType'
	";

	$result3=mysql_query( $sql3 )or die( $FunctionName . ": SQL error " . mysql_error() . "| sql3 = " . htmlentities($sql3) );
	$row3 = mysql_fetch_object( $result3 );
}

$loop_counter = 0;

while( $row = mysql_fetch_object( $result ) )
{
	if (isset($already_sent[$row->id])) continue; // if we've sent this one, skip the rest of the while loop

	if( $row->prodStatus == 1 || ($optional_sec == 1 && $instock == 1) )
	{

		if($convertCur)
		{
			$row->price = ereg_replace("[^.0-9]", "", $row->price);
			$row->price = $row->price *  $row3->curUSD;
			$row->price = number_format($row->price, 2, '.', ',');
		}

		if ($imageURL == $row->image_url) {
			$image = "";
		}else{
			$image = $row->image_url;
		}
		//$label="";
		//$label = $row->keywords;  //4-13 update
		$output .= $row->product_url . "\t" .
		preg_replace($_strip_search, $_strip_replace, strip_tags( strtr($row->name, $_cleaner_array) ) ) . "\t" .
		preg_replace($_strip_search, $_strip_replace, strip_tags( strtr($row->description, $_cleaner_array) ) ) . "\t" .
		//$label . "\t" 
		$row->price . "\t" .
		$image . "\t" .
		// Mod by Ben - Added the Google Base localization country to the id, to permit submitting to the different Google Base (US, UK & DE)
		$row->id . "" . $GB_localization;

	if($optional_sec == 1)
	{
		if($instock == 1)
		{
			if($row->prodStatus == 1)
			{
				$prodStatusOut = "Y";
			}
			else
			{
				$prodStatusOut = "N";
			}
			$output .= " \t " . $prodStatusOut;
		}
		if($shipping == 1)
			$output .= " \t " . $lowestShipping;
		if($brand == 1)
			$output .= " \t " . $row->mfgName;
		if($upc == 1)
			$output .= " \t " . $row->code; //output Upc
		if($manufacturer_id == 1)
			$output .= " \t " . "Not Supported";
		if($product_type == 1)
		{
			$productTypeOut=protype($row->cid);
			$output .= " \t " . $productTypeOut;
		}
		if($currency == 1)
			$output .= " \t " . $default_currency;
		if($feed_language == 1)
			$output .= " \t " . $default_feed_language;
		if($ship_to == 1)
			$output .= " \t " . $default_ship_to;
		if($ship_from == 1)
			$output .= " \t " . $default_ship_from;
	}
	$output .= " \n";
	}
	/*$already_sent[$row->id] = 1;

	$loop_counter++;
	if ($loop_counter>750) {
	$fp = fopen( $OutFile , "w" );
	$fout = fwrite( $fp , $output );
	fclose( $fp );
	$loop_counter = 0;
	$output = "";
 }*/
}

//echo($OutFile);
$fp = fopen( $OutFile , "w" );
$fout = fwrite( $fp , $output );
fclose( $fp );
echo "File completed: /feeds/" .FROOGLE_US_FTP_FILENAME. "<br>\n";
chmod($OutFile, 0777);
$etimer = explode( ' ', microtime() );
$etimer = $etimer[1] + $etimer[0];
echo '<p style="margin:auto; text-align:center">';
printf( "Script timer: <b>%f</b> seconds.", ($etimer-$stimer) );
echo '</p>';
echo $no;
//  ---------

?>