<?php

class prodmCache extends Memcache {
	static private $instance = null;
	static private $port = 11211;
	static function mGet() {
		if(self::$instance == null) {
			self::$instance = new Memcache;
			self::$instance->addServer('192.168.30.51', self::$port);
		}
		return self::$instance;
	}
}

function new_product_search($data) {
	if ($data['search']) {
		$search = urlencode($data['search']);
	} elseif($data['keyword']) {
		$search = urlencode($data['keyword']);
	} elseif ($data['q']) {
		$search = urlencode($data['q']);
	}
	if(!isset($data['limit']) || $data['limit'] < 1) {
		$limit = '10';
	}
	if(!isset($data['start']) || $data['start'] < 1) {
		$start = '1';
	}
	if(!isset($data['totalResults']) || $data['totalResults'] < 1) {
		$data['totalResults'] = 20;
	}
	$filters = '';
	if(isset($data['filters'])) {
		$filters = $data['filters'];
	}

	//$feeds['pricegrabber'] = buildFeedUrl('pricegrabber', $search, $limit);
	$feeds['ebay'] = buildFeedUrl('ebay', $search, $limit);
	$feeds['amazon'] = buildFeedUrl('amazon', $search, $limit);
	$feeds['bestbuy'] = buildFeedUrl('bestbuy', $search, $limit);
	$feeds['dealsurf'] = buildFeedUrl('dealsurf', $search, $limit);
	//$feeds['dealnews'] = buildFeedUrl('dealnews', $search, $limit);
	$feeds['overstock'] = buildFeedUrl('overstock', $search, $limit);
	$feeds['linkshare'] = buildFeedUrl('linkshare', $search);
	
	//$pricegrabber = parse_PriceGrabber($feeds['pricegrabber']);
	$ebay = parse_Ebay($feeds['ebay'], $search);
	$amazon = parse_Amazon($feeds['amazon'], $search);
	$bestbuy = parse_BestBuy($feeds['bestbuy'], $search);
	if(rand(1,10) % 10 == 0) { $dealsurf = parse_DealSurf($feeds['dealsurf']); }
	//$dealnews = parse_DealNews($feeds['dealnews'], $search);
	$overstock = parse_Overstock($feeds['overstock'], $search);
	$linkshare = parse_Linkshare($feeds['linkshare']);
	
	$results = array_values(array_filter(array_merge((array)$pricegrabber, (array)$ebay, (array)$amazon, (array)$bestbuy, (array)$dealsurf, (array)$dealnews, (array)$overstock, (array)$linkshare)));
	shuffle($results);
	$results = array_slice($results, 0, $data['totalResults']);

	return $results;
}

function buildFeedUrl($name, $search, $limit = 20) {
	switch($name) {
		case 'pricegrabber':
			$url = 'http://ah.pricegrabber.com/export_feeds.php?pid=gghiabeb&document_type=xml&limit=10&topcat_id=all&category=topcat:all&col_mfrpartnum=1&col_mfrname=1&col_description=1&col_short_description=1&col_price=1&col_newprice=1&col_rebate=1&col_rating=1&col_sellers=1&col_images=1&form_keyword='.$search;
			break;
		case 'ebay':
			$devId = 'c1a19c31-34e6-4d0e-8f73-f9ef3b36ea32';
			$appId = 'CheapStu-cad1-4ffe-bb5e-b41ad1e3ee21';
			$certId = '3fd2a214-51a8-40a1-b9bb-94b483e285dd';
			$endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1';
			$version = '1.0.0';
			$globalId = 'EBAY-US';
			$operationName = 'findItemsByKeywords';
			$entriesPerPage = $limit;

			$url = $endpoint.'?OPERATION-NAME='.$operationName.'&SERVICE-VERSION='.$version.'&SECURITY-APPNAME='.$appId.'&GLOBAL-ID='.$globalId.'&keywords='.$search.'&paginationInput.entriesPerPage='.$entriesPerPage;
			break;
		case 'amazon':
			$accessKey = 'AKIAJSVZDRBJOZMLWSZQ';
			$associateKey = '299366458314';
			$secretKey = 'GxZ8DjLYmLQkxwNpse2KEyAmhyAnlKykK8XWnJaK';
			$term = str_replace('+', '%20', $search);
			$operation = 'ItemSearch';
			$version = '2011-08-01';
			$responseGroup = urlencode('Images,ItemAttributes');
			$searchIndex = 'All';
			date_default_timezone_set('Europe/London');
			$time = urlencode(gmdate('Y-m-d\TH:i:s\Z'));

			$method = 'GET';
			$schema = 'http';
			$host = 'ecs.amazonaws.com';
			$path = '/onca/xml';
			$query = 'AWSAccessKeyId='.$accessKey.'&AssociateTag='.$associateKey.'&Keywords='.$term.'&Operation='.$operation.'&ResponseGroup='.$responseGroup.'&SearchIndex='.$searchIndex.'&Service=AWSECommerceService&Timestamp='.$time.'&Version='.$version;
			$toSign = "$method\n$host\n$path\n$query";
			$signature = urlencode(base64_encode(hash_hmac('sha256', $toSign, $secretKey, true)));
			$url = $schema.'://'.$host.$path.'?'.$query.'&Signature='.$signature;
			break;
		case 'bestbuy':
			$url = 'http://api.remix.bestbuy.com/v1/products(search='.$search.')?apiKey=h73s6sajs3je2sjacuaqj7gj';
			break;
		case 'dealsurf':
			if(stristr($_SERVER['HTTP_X_FORWARDED_FOR'], '192.168.')) {
				$ip = '199.27.174.35';
			} else {
				$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
			}
			$url = 'http://api.dealsurf.com/deals/list.xml?apikey=8902337d76a199b7818b11f6a5efd221&ip='.$ip.'&keyword='.$search.'&city=US';
			break;
		case 'dealnews':
			$url = 'http://dealnews.com/synd/2.1/api.php?format=xml&refcode=cheapstuff&search='.$search;
			break;
		case 'overstock':
			$url = 'http://www.overstock.com/productxml?keywords='.$search.'&quicklist=1&ProductURL=Y';
			break;
		case 'linkshare':
			if(stristr($_SERVER['HTTP_X_FORWARDED_FOR'], '192.168.')) {
				$ip = '199.27.174.35';
			} else {
				$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
			}
			$url = 'http://xml.admedia.com/xml.php?Terms='.$search.'&affiliate=testnbcsearch&debug=7&clearcache=1&showme=1&IP='.$ip.'&ua='.urlencode($_SERVER['HTTP_USER_AGENT']);
			break;
	}

	return $url;
}

function parse_PriceGrabber($url) {
	$expire = 60 * 60 * 24;
	$tab = 'pricegrabber';
	$mkey = $tab.'_'.md5($url);

	$result = prodmCache::mGet()->get($mkey);
	
	if($result === false || $result === null) {
		$xml = simplexml_load_file($url);
		
		if ($xml === false || !$xml->item || count($xml->item) == 0) {
			return false;
		}
		
		foreach ($xml->item as $i) {
			$title = (string)$i->title;
			$title = substr($title, 0, 45);
			$title = str_replace('"', '', $title);
			$url = (string)$i->link;
			$description = (string)$i->description;
			$description = str_replace('"', '', $description);
			$sellers = (string)$i->sellers;
			$price = number_format(str_replace('$', '', (string)$i->price_new), 2);
			$namespaces = $i->getNameSpaces(true);
			$pg = $i->children($namespaces['pg']);
			$img = (string)$pg->product_image;
			
			if($price != '' && $url != '' && $title != '' && $img != '') {
				$result[] = array(
					'title' => $title,
					'url' => $url,
					'description' => $description,
					'price' => $price,
					'img' => $img
				);
			}
		}
		
		prodmCache::mGet()->set($mkey, $result, 0, $expire);
	}
	
	shuffle($result);
	$result = array_map('unserialize', array_unique(array_map('serialize', $result)));;
	return $result;
}

function parse_Ebay($url, $search) {
	$expire = 60 * 60 * 24;
	$tab = 'ebay';
	$mkey = $tab.'_'.md5($search);

	$result = prodmCache::mGet()->get($mkey);
	
	if($result === false || $result === null) {
		$xml = simplexml_load_file($url);
		
		if ($xml === false || !$xml->searchResult->item || count($xml->searchResult->item) == 0) {
			return false;
		}
		
		foreach ($xml->searchResult->item as $i) {
			$img = (string)$i->galleryURL;
			$url = (string)$i->viewItemURL;
			$title = (string)$i->title;
			$condition = (string)$i->condition->conditionDisplayName;
			$price = number_format(str_replace('$', '', (string)$i->sellingStatus->convertedCurrentPrice), 2);
			if($i->shippingInfo->shippingServiceCost && trim($i->shippingInfo->shippingServiceCost) != '')
				$shipping = "+\${$i->shippingInfo->shippingServiceCost}";
			else 
				$shipping = 'No Shipping';
			if(trim($condition) == 'Manufacturer refurbished')
				$title = substr($title, 0, 45);
			else
				$title = substr($title, 0, 45);

			$title = str_replace('"', '', $title);
			$timeleft = (string)$i->sellingStatus->timeLeft;
			$parsed_time = array();
			$pattern = "/^P([0-9]+)DT([0-9]+)H([0-9]+)M([0-9]+)S$/";
			$testreturn = preg_match($pattern, $timeleft, $parsed_time);
			$days = "{$parsed_time[1]}d";
			$hours = "{$parsed_time[2]}h";
			$minutes = "{$parsed_time[3]}m";
			$seconds = "{$parsed_time[4]}s";
			
			if($price != '' && $url != '' && $title != '' && $img != '') {
				$result[] = array(
					'title' => $title,
					'url' => $url,
					'description' => $condition,
					'price' => $price,
					'img' => $img
				);
			}
		}
		
		prodmCache::mGet()->set($mkey, $result, 0, $expire);
	}
	
	shuffle($result);
	$result = array_map('unserialize', array_unique(array_map('serialize', $result)));
	return $result;
}

function parse_Amazon($url, $search) {
	$expire = 60 * 60 * 24;
	$tab = 'amazon';
	$mkey = $tab.'_'.md5($search);

	$result = prodmCache::mGet()->get($mkey);
	
	if($result === false || $result === null) {
		$xml = simplexml_load_file($url);
	
		if ($xml === false || !$xml->Items->Item || count($xml->Items->Item) == 0) {
			return false;
		}
		foreach ($xml->Items->Item as $i) {
			$url = (string)$i->DetailPageURL;
			$img = (string)$i->ImageSets->ImageSet->MediumImage->URL;
			$title = (string)$i->ItemAttributes->Title;
			$title = substr($title, 0, 45);
			$category = (string)$i->ItemAttributes->ProductGroup;
			$price = number_format(str_replace('$', '', (string)$i->ItemAttributes->ListPrice->FormattedPrice), 2);
			$title = str_replace('"', '', $title);
			
			if($price != '' && $url != '' && $title != '' && $img != '') {
				$result[] = array(
					'title' => $title,
					'url' => $url,
					'description' => $category,
					'price' => $price,
					'img' => $img
				);
			}
		}
		
		prodmCache::mGet()->set($mkey, $result, 0, $expire);
	}
	
	shuffle($result);
	$result = array_map('unserialize', array_unique(array_map('serialize', $result)));
	return $result;
}

function parse_BestBuy($url, $search) {
	$expire = 60 * 60 * 24;
	$tab = 'bestbuy';
	$mkey = $tab.'_'.md5($search);

	$result = prodmCache::mGet()->get($mkey);
	
	if($result === false || $result === null) {
		$xml = simplexml_load_file($url);
		
		if ($xml === false || !$xml->product || count($xml->product) == 0) {
			return false;
		}
		
		foreach ($xml->product as $p) {
			$name = (string)$p->name;
			$name = substr($name, 0, 45);
			$name = str_replace('"', '', $name);
			$description = (string)$p->shortDescription;
			$description = substr($description, 0, 55);
			$description = str_replace('"', '', $description);
			$price = number_format(str_replace('$', '', (string)$p->salePrice), 2);
			$img = (string)$p->image;
			$url = (string)$p->url;
			$newItem = (string)$p->new;

			switch ($newItem)
			{
				case "false":
					$newStatus = "";
					break;
				default:
					$newStatus = "New!&nbsp;";
			}
			
			if($price != '' && $url != '' && $name != '' && $img != '') {
				$result[] = array(
					'title' => $name,
					'url' => $url,
					'description' => $description,
					'price' => $price,
					'img' => $img
				);
			}
		}
		
		prodmCache::mGet()->set($mkey, $result, 0, $expire);
	}
	
	shuffle($result);
	$result = array_map('unserialize', array_unique(array_map('serialize', $result)));
	return $result;
}

function parse_DealSurf($url) {
	$expire = 60 * 60 * 24;
	$tab = 'dealsurf';
	$mkey = $tab.'_'.md5($url);

	$result = prodmCache::mGet()->get($mkey);
	
	if($result === false || $result === null) {
		$xml = simplexml_load_file($url);
		
		if ($xml === false || !$xml->deals->deal || count($xml->deals->deal) == 0) {
			return false;
		}
		
		foreach ($xml->deals->deal as $d) {
			$title = (string)$d->title;
			$title = substr($title, 0, 45);
			$title = str_replace('"', '', $title);
			$description = (string)$d->merchant;
			$description = substr($description, 0, 55);
			$description = str_replace('"', '', $description);
			$price = number_format(str_replace('$', '', (string)$d->value), 2);
			$img = (string)$d->picture;
			$url = (string)$d->url;
			
			if($price != '' && $url != '' && $title != '' && $img != '') {
				$result[] = array(
					'title' => $title,
					'url' => $url,
					'description' => $description,
					'price' => $price,
					'img' => $img
				);
			}
		}
		
		$result = array_slice($result, 0, 30);
		prodmCache::mGet()->set($mkey, $result, 0, $expire);
	}
	
	shuffle($result);
	$result = array_map('unserialize', array_unique(array_map('serialize', $result)));
	return $result;
}

function parse_DealNews($url, $search) {
	$expire = 60 * 60 * 24;
	$tab = 'dealnews';
	$mkey = $tab.'_'.md5($search);

	$result = prodmCache::mGet()->get($mkey);
	
	if($result === false || $result === null) {
		$xml = simplexml_load_file($url);
		
		if ($xml === false || !$xml->deals->deal || count($xml->deals->deal) == 0) {
			return false;
		}
		
		foreach ($xml->deals->deal as $d) {
			$title = (string)$d->title;
			$title = substr($title, 0, 45);
			$title = str_replace('"', '', $title);
			$description = (string)$d->description;
			$description = substr($description, 0, 55);
			$description = str_replace('"', '', $description);
			$price = number_format(str_replace('$', '', (string)$d->value), 2);
			$img = (string)$d->images_medium;
			$url = (string)$d->url;
			
			if($price != '' && $url != '' && $title != '' && $img != '') {
				$result[] = array(
					'title' => $title,
					'url' => $url,
					'description' => $description,
					'price' => $price,
					'img' => $img
				);
			}
		}
		
		prodmCache::mGet()->set($mkey, $result, 0, $expire);
	}

	shuffle($result);
	$result = array_map('unserialize', array_unique(array_map('serialize', $result)));
	return $result;
}

function parse_Overstock($url, $search) {
	$expire = 60 * 60 * 24;
	$tab = 'overstock';
	$mkey = $tab.'_'.md5($search);

	$result = prodmCache::mGet()->get($mkey);
	
	if($result === false || $result === null) {
		$xml = simplexml_load_file($url);
		
		if ($xml === false || !$xml->OSTKPRODUCT || count($xml->OSTKPRODUCT) == 0) {
			return false;
		}
		
		foreach ($xml->OSTKPRODUCT as $p) {
			$name = (string)$p->Name;
			$name = substr($name, 0, 45);
			$name = str_replace('"', '', $name);
			$description = (string)$p->ShortDescription;
			$description = substr($description, 0, 55);
			$description = str_replace('"', '', $description);
			$price = number_format(str_replace('$', '', (string)$p->Price), 2);
			$marketPrice = number_format(str_replace('$', '', (string)$p->MSRP), 2);
			$url = (string)$p->ProductURL;
			$img = (string)$p->ThumbnailURL;

			if(!empty($price) && empty($marketPrice))
				$printprice = $price;
			else if(empty($price) && !empty($marketPrice))
				$printprice = $marketPrice;
			else if(!empty($price) && !empty($marketPrice))
				$printprice = $price;
				
			if($printprice != '' && $url != '' && $name != '' && $img != '') {
				$result[] = array(
					'title' => $name,
					'url' => $url,
					'description' => $description,
					'price' => $printprice,
					'img' => $img
				);
			}
		}
		
		prodmCache::mGet()->set($mkey, $result, 0, $expire);
	}
	
	shuffle($result);
	$result = array_map('unserialize', array_unique(array_map('serialize', $result)));
	return $result;
}

function parse_Linkshare($url) {
	$expire = 60 * 60 * 24;
	$tab = 'linkshare';
	$mkey = $tab.'_'.md5($url);

	$result = prodmCache::mGet()->get($mkey);
	
	if($result === false || $result === null) {
		$xml = simplexml_load_file($url);
		
		if ($xml === false || !$xml->results->listing || count($xml->results->listing) == 0) {
			return false;
		}
		
		foreach ($xml->results->listing as $i) {
			$title = (string)$i->title;
			$title = substr($title, 0, 45);
			$title = str_replace('"', '', $title);
			$url = (string)$i->redirect;
			$description = (string)$i->description;
			$description = str_replace('"', '', $description);
			$price = number_format(str_replace('$', '', str_replace(' USD', '', (string)$i->price_new)), 2);
			$img = (string)$i->img;
			
			if($price != '' && $url != '' && $title != '' && $img != '') {
				$result[] = array(
					'title' => $title,
					'url' => $url,
					'description' => $description,
					'price' => $price,
					'img' => $img
				);
			}
		}
		
		prodmCache::mGet()->set($mkey, $result, 0, $expire);
	}

	shuffle($result);
	$result = array_map('unserialize', array_unique(array_map('serialize', $result)));;
	return $result;
}