view php/read/getBookDetails.php @ 10:5aa24c984a3b

if no code show entire response
author Henry S. Thompson <ht@markup.co.uk>
date Sat, 18 Feb 2017 12:28:36 +0000
parents 232deb0b066a
children 385ddd7c4b55 ae1459564f66
line wrap: on
line source

<?php

function findGenre($browseNode, &$ID, &$gen)
{
	if($browseNode->Name == "Subjects")
	{
		 return true;		 
	}
	else
	{
		if($browseNode->Ancestors->BrowseNode)
		{
			if(findGenre($browseNode->Ancestors->BrowseNode, $ID, $gen) == true)
			{
				$gen = $browseNode->Name;
				$ID = $browseNode->BrowseNodeId;
				
				//if($browseNode->Name == "Literature & Fiction") //to return one level up the tree as well
				//	return true;
			}		
		}
		return false;		
	}
}

global $out,$isbn;
if(isset($_GET['isbn'])){
	$isbn = $_GET['isbn'];
	if(isset($_GET['locale'])){
	$locale=$_GET['locale'];
	
	switch ($locale) {
    case "uk":
        $loc = 1;
        break;
    case "us":
        $loc = 0;
        break;
    case "ca":
        $loc = 2;
        break;
	case "de":
        $loc = 3;
        break;
	case "fr":
        $loc = 4;
        break;
	case "":
        $loc = 0;
        break;
	}
	}
	else{
	$loc=0;
	}
	$output = "";

	$output .=  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	$output .=  "<BookDetails>";
	
	$proceed = true;
	include "../../../private/db.php";

	$query = "CALL b_getBookInfo('$isbn', $loc)";
	//select Timestamp,Title,Author,Binding,DeweyDecimal,ImageURL,SalesRank,PublicationDate,Publisher,Genre1,Genre2,Genre3 from books where ISBN = '$isbn'";
	//echo $query;
	$res = mysqli_query($link, $query) or exit( mysqli_error( $link ));
	
	if ( mysqli_num_rows( $res ) > 0 )
	{
		$rows=mysqli_fetch_array($res, MYSQLI_ASSOC);
		$timestamp=$rows['Timestamp'];
		//echo $timestamp;
		date_default_timezone_set('UTC');
		$dbStamp = strtotime($timestamp);
		//echo $dbStamp;
		$unixTime = time();
		//echo $unixTime;			
		$timeDiff = $unixTime - $dbStamp;
		//echo $timeDiff;
		
		if($timeDiff < 2592000) //if it has been updated in the last 30 days 
		{	
			$proceed = false;
			$output .=  "<ISBN>" . $isbn . "</ISBN>";
			$output .=  "<Title>" . htmlspecialchars($rows["Title"]) . "</Title>";
			$output .=  "<Author>" . htmlspecialchars($rows["Author"]) . "</Author>";
			$output .=  "<Binding>" . htmlspecialchars($rows["Binding"]) . "</Binding>";
			$output .=  "<Dewey>" . htmlspecialchars($rows["DeweyDecimal"]) . "</Dewey>";
			$output .=  "<ImageURL>" . htmlspecialchars($rows["ImageURL"]) . "</ImageURL>";
			$output .=  "<SalesRank>" . htmlspecialchars($rows["SalesRank"]) . "</SalesRank>";
			$output .=  "<PublicationDate>" . htmlspecialchars($rows["PublicationDate"]) . "</PublicationDate>";
			$output .=  "<Publisher>" . htmlspecialchars($rows["Publisher"]) . "</Publisher>";
			$output .=  "<Genre1>" . htmlspecialchars($rows["Genre1"]) . "</Genre1>";
			$output .=  "<Genre2>" . htmlspecialchars($rows["Genre2"]) . "</Genre2>";
			$output .=  "<Genre3>" . htmlspecialchars($rows["Genre3"]) . "</Genre3>";
			$output .=  "<ProductGroup>Book</ProductGroup>";
		}
	}
	mysqli_close($link);	//do not remove. reset is needed otherwise mysqli_fetch_array doesn't work after first loop
	include "../../../private/db.php";
	
	if($proceed == true)
	{
		include "aws_signed_request.php"; 
		//book does not exist already so look up all the info from browse nodes....

		$Adefault=array(
		  'language'           =>'en',           //what language to render the page in
		  'locale'             =>'us',           //which server's products? available: ca,de,fr,jp,uk,us
		  'page'               =>1,              //first page to show (we are counting from 1 not 0)
		  'operation'          =>'ItemLookup',   //what to do?	//ItemSearch
		  'searchparameter'    =>'ItemId',       //what kind of search?
		  'searchindex'     => 'Books',
		  'searchparameterdata'=>$isbn,  //what to search for?
		  'search' =>$isbn,
		  //here some debugging flags you can put at the end of the URL to call this script with, like: '?show_array=true'
		  'show_array'         =>false,          //debug: show complete incoming array? You can use this to see what other information Amazon is sending
		  'show_url'           =>false,          //debug: show XML request url to be send to Amazon?
		  'show_xml'           =>false,          //debug: show incoming XML code from Amazon?
		);
		//change the debug options to true if you want to activate them or call the script with '?show_array=true' to see what actual information you're getting from Amazon and how little my standard script is actually showing of it

		$Aassociates_id=array(
		  'uk' => 'bookwhack-21',
		  'us' => 'your02b-20',
		  'ca' => 'book009-20',
		  'de' => 'book04c-21',
		  'fr' => 'book07f-21',
		);

		$Aserver=array(
		  'ca' => array(
			'ext' => 'ca'                      ,  //Canadian normal server
			'nor' => 'http://www.amazon.ca'    ,  //Canadian normal server
			'xml' => 'http://xml.amazon.com'   ,  //Canadian xml server
		  ),
		  'de' => array(
			'ext' => 'de'                      ,  //German normal server
			'nor' => 'http://www.amazon.de'    ,  //German normal server
			'xml' => 'http://xml-eu.amazon.com',  //German xml server
		  ),
		  'fr' => array(
			'ext' => 'fr'                      ,  //French normal server
			'nor' => 'http://www.amazon.fr'    ,  //French normal server
			'xml' => 'http://xml-eu.amazon.com',  //French xml server
		  ),
		  'jp' => array(
			'ext' => 'jp'                      ,  //Japanese normal server, not co.jp!
			'nor' => 'http://www.amazon.co.jp' ,  //Japanese normal server
			'xml' => 'http://xml.amazon.com'   ,  //Japanese xml server
		  ),
		  'uk' => array(
			'ext' => 'co.uk'                   ,  //UK normal server
			'nor' => 'http://www.amazon.co.uk' ,  //UK normal server
			'xml' => 'http://xml-eu.amazon.com',  //UK xml server
		  ),
		  'us' => array(
			'ext' => 'com'                     ,  //USA normal server
			'nor' => 'http://www.amazon.com'   ,  //USA normal server
			'xml' => 'http://xml.amazon.com'   ,  //USA xml server
		  ),
		);
			
		$public_key ="AKIAJBXEHTNCU6LLFNIA";
		$private_key="Dgyv7aR6uGe3OtY95Dj6hHpDS/UEtyboMWpJchYA";

		//for all parameters see if the user has overruled it or use the default
		foreach ($Adefault as $i=>$d) {
		  $$i=isset($_GET[$i])?$_GET[$i]:$d;
		}

		  $parameters=array(
			'Operation'       =>$operation              ,
			'Keywords'        =>urlencode($search)      ,
			"$searchparameter"=>$searchparameterdata    ,
			'ItemPage'        =>$page                   ,  //which page?
			'AssociateTag'    =>$Aassociates_id[$locale],
			'ResponseGroup'   =>'ItemAttributes,Images,SalesRank,BrowseNodes'
		  );

		  if ($searchindex!='Books') {
		    // HST did this
		    // Used to be in $parameters init above, but
		    // that caused an error:
		    // If idType equals ASIN, SearchIndex cannot be present
		    //'SearchIndex'     =>$searchindex      ,  //Books for example.
		      $parameters['SearchIndex']=$searchindex;
		  }


		$ext=$Aserver[$locale]['ext'];  
		$file_data=$ext;
		ksort($parameters);
		foreach ($parameters as $i=>$d) {
		  $file_data.='&'.$i.'='.$d;
		}

		$url=aws_signed_request($ext,$parameters,$public_key,$private_key);  
		//echo $url;

		$crl = curl_init();
		$timeout = 5;
		curl_setopt ($crl, CURLOPT_URL,$url);
		curl_setopt ($crl, CURLOPT_ENCODING , "gzip"); 
		curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
		$out = curl_exec($crl);
		curl_close($crl);

		//echo $out;
		
		if (preg_match("<Error>",$out)) {
		  $xml = new SimpleXMLElement($out);	
		  $resName=$xml->getName();
		  $code=$xml->Error->Code;
		  file_put_contents('/var/ywww/debug/phpDebug',"Losing gBD: $resName, $code\n",FILE_APPEND);
		  if ($code=='RequestThrottled') {
		    usleep(200000); // Try to reduce throttling until we get a 
		    // principled solution in place
		  }
		  else {
		    file_put_contents('/var/ywww/debug/phpDebug',"parms bd: ".
				      print_r($parameters,TRUE)."\n",FILE_APPEND);
		    if ($code=="") {
		      file_put_contents('/var/ywww/debug/phpDebug',"error elt:\n$out\n",FILE_APPEND);
		    }
		  }
		}
		else {
		  $xml = new SimpleXMLElement($out);
		  //use this xml to pull out the necessary information and save it
		  set_error_handler(function () {
		      global $out,$isbn;
		      file_put_contents('/var/ywww/debug/phpDebug',
					"Caught one bd: ".$isbn,
					FILE_APPEND);
		      file_put_contents('/var/ywww/debug/phpDebug',
					print_r($out, TRUE)."\n",
					FILE_APPEND);
		    } );
	
		  $title="";
		  $author="";
		  $binding="";
		  $dewey="";
		  $imageURL="";
		  $salesRank="";
		  $pubDate="";
		  $publisher="";
	
		  $title = $xml->Items->Item->ItemAttributes->Title;
		  $author = $xml->Items->Item->ItemAttributes->Author;
		  $binding = $xml->Items->Item->ItemAttributes->Binding;
		  $dewey = $xml->Items->Item->ItemAttributes->DeweyDecimalNumber;
		  if($dewey == "")
		    $dewey = "null";
		  $imageURL = $xml->Items->Item->MediumImage->URL;
		  $salesRank = $xml->Items->Item->SalesRank;
		  $pubDate = $xml->Items->Item->ItemAttributes->PublicationDate;
		  $publisher = $xml->Items->Item->ItemAttributes->Publisher;
		  restore_error_handler();
		  /*echo $title;
		   echo $author;
		   echo $binding;
		   echo $dewey;
		   echo $imageURL;
		   echo $salesRank;
		   echo $pubDate;
		   echo $publisher;*/
		
		  $genreID = "";
		  $genre = "";		
		  $genArr = array();
		  $g1 = "null";
		  $g2 = "null";
		  $g3 = "null";
		  if(isset($xml->Items->Item->BrowseNodes->BrowseNode)){		
		    for($i=0;$i<sizeof($xml->Items->Item->BrowseNodes->BrowseNode);$i++){					
		      //sexy recursive function
		      findGenre($xml->Items->Item->BrowseNodes->BrowseNode[$i], $genreID, $genre);
			
		      if($genre != "")
			$genArr[strval($genreID)] = strval($genre);
		      //$genArr[$i] = array(strval($genreID) => strval($genre));

		      //echo $genre;
		      //echo $genreID;
			
		      $genre = "";
		      $genreID = "";
		    }
		
		    $g1 = "null";
		    $g2 = "null";
		    $g3 = "null";
		    $loop = 1;
		
		    foreach ($genArr as $key => $value) {
		      //echo "$key => $value";
		      $queryG = "CALL b_addBrowseNode($key,\"$value\")";	//add the name value pair for genre to new table	
		      //echo $queryG;
		      $resG = mysqli_query($link, $queryG);
			
		      switch ($loop) {
		      case 1:
			$g1 = $key;
			break;
		      case 2:
			$g2 = $key;
			break;
		      case 3:
			$g3 = $key;
			break;
		      }
			
		      $loop++;
		    }
		  }
		
		  if($salesRank == "")
		    $salesRank = "null";
		
		  mysqli_close($link);	//do not remove. reset is needed otherwise mysqli_fetch_array doesn't work after first loop
		  include "../../../private/db.php";
		
		  $title = strtr($title, '"', "'");	
		  $queryInsert = "CALL b_addNewBook(\"$isbn\",\"$title\", \"$author\",\"$binding\",\"$imageURL\", $dewey, $salesRank,\"$pubDate\",\"$publisher\",$g1,$g2,$g3,$loc)";	
		  //echo $queryInsert;
		
		  $resG = mysqli_query($link, $queryInsert) or exit( mysqli_error( $link ));
		  mysqli_close($link);	//do not remove. reset is needed otherwise mysqli_fetch_array doesn't work after first loop		

		
		  $output .=  "<ISBN>" . htmlspecialchars($isbn) . "</ISBN>";
		  $output .=  "<Title>" . htmlspecialchars($title) . "</Title>";
		  $output .=  "<Author>" . htmlspecialchars($author) . "</Author>";
		  $output .=  "<Binding>" . htmlspecialchars($binding) . "</Binding>";
		  $output .=  "<Dewey>" . htmlspecialchars($dewey) . "</Dewey>";
		  $output .=  "<ImageURL>" . htmlspecialchars($imageURL) . "</ImageURL>";
		  $output .=  "<SalesRank>" . htmlspecialchars($salesRank) . "</SalesRank>";
		  $output .=  "<PublicationDate>" . htmlspecialchars($pubDate) . "</PublicationDate>";
		  $output .=  "<Publisher>" . htmlspecialchars($publisher) . "</Publisher>";
		  $output .=  "<Genre1>" . htmlspecialchars($g1) . "</Genre1>";
		  $output .=  "<Genre2>" . htmlspecialchars($g2) . "</Genre2>";
		  $output .=  "<Genre3>" . htmlspecialchars($g3) . "</Genre3>";	
		  $output .=  "<ProductGroup>Book</ProductGroup>";
		}
	}
	
	$output .=  "</BookDetails>";
	
	echo $output;
}
?>