<?php

class IMWB_Zonpress_module_amazon {

   var $module_name = "amazon";
   var $options = Array();
   var $currency_symbols = Array();
   
   /**
    * The constructor is executed when the class is instatiated and the plugin gets loaded.
    * @return void
    */
   function IMWB_Zonpress_module_amazon($options, $currency_symbols) {
      $this->options = $options; 
      $this->currency_symbols = $currency_symbols;
   }
   
   function get_price($item) {
   
      $lowestnewprice = (string)$item->OfferSummary->LowestNewPrice->FormattedPrice;
      $listprice = (string)$item->ItemAttributes->ListPrice->Amount;
      $post_currency = (string)$item->ItemAttributes->ListPrice->CurrencyCode;

      if(empty($lowestnewprice) || $lowestnewprice == "Too low to display" || $lowestnewprice == "Price too low to display") 
      	$post_price = $listprice;
      else {
         $post_price = (string)$item->OfferSummary->LowestNewPrice->Amount;
         $post_currency = (string)$item->OfferSummary->LowestNewPrice->CurrencyCode;
      }
//echo "Price 1:".$post_currency.$post_price." ";   
      // Now see if there is an offer
      $totOffers = $item->Offers->TotalOffers;
      if(!empty($totOffers) && $totOffers > 0) {
         // Now find the New Condition Offer
         foreach ($item->Offers->Offer as $offer) {
            if($offer->OfferAttributes->Condition == 'New') {
               $offer_price = (string)$offer->OfferListing->Price->FormattedPrice;
               if($offer_price != "Too low to display") {
                  $offer_post_price = (string)$offer->OfferListing->Price->Amount;
                  if($offer_post_price < $post_price) $post_price = $offer_post_price;
                  $post_currency = (string)$offer->OfferListing->Price->CurrencyCode;
//echo "Price 2:".$post_currency.$post_price." ";                             
               }
               $offer_saleprice = $offer->OfferListing->SalePrice;
               if(!empty($offer_saleprice) && (string)$offer_saleprice->FormattedPrice != "Too Low to Display") {
                  $offer_sale_post_price = (string)$offer_saleprice->Amount;
                  if($offer_sale_post_price < $post_price) $post_price = $offer_sale_post_price;
                  $post_currency = (string)$offer_saleprice->CurrencyCode;
//echo "Price 3:".$post_currency.$post_price." ";                             
               }
            }
         }
      }
//echo "Price 4:".$post_currency.$post_price." ";           
      // If price is still not found then try to see if collectable price available
      if(empty($post_price)) {
         $Lowestcollectibleprice = (string)$item->OfferSummary->LowestCollectiblePrice->FormattedPrice;   
         if(!empty($Lowestcollectibleprice) && $Lowestcollectibleprice != "Too low to display" && $Lowestcollectibleprice != "Price too low to display") {
            $post_price = (string)$item->OfferSummary->LowestCollectiblePrice->Amount;
            $post_currency = (string)$item->OfferSummary->LowestCollectiblePrice->CurrencyCode;     
         }
      }
//echo "Price 5:".$post_currency.$post_price."<br>";
      if(empty($post_price) || $post_price == 0)
         return false;
      
      $return['post_price'] = $post_price /100;
      $return['post_currency'] = $this->currency_symbols[$post_currency];
      
      return $return;
   }
   
   function search($keyword, $numPosts = 0, $page = 1, $amzIndex) {
      global $wpdb;
      
      $existingProducts = false;
      $numCreated = 0;
      $keyword = str_replace('"', '', trim(stripslashes($keyword)));

      // Loop through the result pages until we create enough posts
      do {
      		
         $resultxml = $this->aws_request($this->options['amzregion'], array(
         	"Operation"=>"ItemSearch",
         	"AssociateTag"=>$this->options['amzaffid'],
         	"Keywords"=>$keyword,
         	"SearchIndex"=>$amzIndex,
         	"Availability" => 'Available',
         	"Condition"=>"New",
         	"ItemPage"=>$page,
         	"ReviewSort"=>"-HelpfulVotes",
         	"TruncateReviewsAt"=>"500",
         	"IncludeReviewsSummary"=>"False",
         	"ResponseGroup"=>"Large",
         	"MinimumPrice"=>$minPrice,
         	"MaximumPrice"=>$maxPrice
         	), $this->options['amzpubkey'], $this->options['amzprikey']);		      			
      
         if(!empty($resultxml["error"])) {return $resultxml;}
         
         // Check for errors
         $result = $resultxml->xpath("//Errors");
         if($result) {
         
         	$return["error"]["module"] = "Amazon";
            $return["error"]["message"] = __( 'The Following Errors Occured', 'imwb_zonpress' ).'<br>';
         	$return["error"]["reason"] = "API fail";         
   
            foreach ($result as $error) {
               $errorCode = (string)(string)$error->Error->Code;
               if($errorCode == "AWS.ParameterOutOfRange" && $page > 5) {
                   $message = __('Sorry, there are no more products for that search term. Please try using a different keyword or phrase to find more products.', 'imwb_zonpress' );
               }
               else if($errorCode == "AWS.ECommerceService.NoExactMatches") {
                  if($existingProducts)
                     $message = __('Sorry, there are no more products for that search term. Please try using a different keyword or phrase to find more products.', 'imwb_zonpress' );
                  else
                     $message = __('Sorry, we couldn\'t find any products for that search term. Please try using a different keyword or phrase', 'imwb_zonpress' );
               }
               else {
               	$message = 'There was a problem with your Amazon API request: <i><b>'.$errorCode.':</b> '.$error->Error->Message.'</i>';	
               }               
            }
            
            $return["error"]["message"] = $message."<br>";
            
            return $return;
         }

         foreach($resultxml->Items->Item as $item) {	

            // Get the unique ID
            $post_id = trim($item->ASIN);
    
            // Get the title
            $post_title = (string)$item->ItemAttributes->Title;
            
            // Check for exisintg post         
   			$results = $wpdb->get_row( $wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s", 'imwb_cc_amazon_asin', $post_id) );
   			
   			if(count($results) > 0) {
      			$existingProducts = true;
   			   continue;			   
   			}
            
            // Get the description
            $post_desc = "";
            if (isset($item->EditorialReviews->EditorialReview)) {
   				foreach($item->EditorialReviews->EditorialReview as $descs) {
   					$post_desc .= strip_tags((string)$descs->Content, "<img><p><br><br/><h1><h2><h3><h4>");
   				}		
   			}	
   			
   			// If select to have feature list then include it in the description
   			$featureList = "";
   			if($this->options['amzincfeatures'] == 'Y') {  		
   				if (isset($item->ItemAttributes->Feature)) {	
   					$featureList = "<h3>".__( 'Product Features', 'imwb_zonpress' )."</h3><ul>";
   					foreach($item->ItemAttributes->Feature as $feature) {
   						$posx = strpos($feature, "href=");
   						if ($posx === false) {
   							$featureList .= "<li>".$feature."</li>";		
   						}
   					}	
   					$featureList .= "</ul>";				
   					$post_desc.=$featureList;
   				}
   			}
   			   			            
            // Get the image
            $post_image = $item->SmallImage->URL;
            if($post_image == "") {$post_image = $item->MediumImage->URL;}	
            if($post_image == "") {$post_image = $item->LargeImage->URL;}	
//echo "ASIN: ".$post_id." ";                        
            // Get the Price
            $itemPrice = $this->get_price($item);
            if($itemPrice === false)
               continue;
               
            $post_price =  $itemPrice['post_currency'].number_format($itemPrice['post_price'],2);
            
//            $lowestnewprice = (string)$item->OfferSummary->LowestNewPrice->FormattedPrice;
//            $listprice = (string)$item->ItemAttributes->ListPrice->FormattedPrice;
//            
//            if(empty($lowestnewprice) || $lowestnewprice == "Too low to display" || $lowestnewprice == "Price too low to display") 
//            	$post_price = $listprice;
//            else 
//               $post_price = $lowestnewprice;
                                    
            // Now see if there is an offer
//            $totOffers = $item->Offers->TotalOffers;
//
//            if(!empty($totOffers) && $totOffers > 0) {
               // Now find the New Condition Offer
//               foreach ($item->Offers->Offer as $offer) {
//                  if($offer->OfferAttributes->Condition == 'New') {
//                     $offer_price = (string)$offer->OfferListing->Price->FormattedPrice;
//                     $post_price = $offer_price == "Too low to display" ? $post_price : $offer_price;
//                     $offer_saleprice = $offer->OfferListing->SalePrice;
//                     if(!empty($offer_saleprice) && (string)$offer_saleprice->FormattedPrice != "Too Low to Display") {
//                        $post_price = (string)$offer_saleprice->FormattedPrice;
//                     }
//                  }
//               }
//            }
            
            // If price is still not found then try to see if collectable price available
//            if(empty($post_price)) {
//               $Lowestcollectibleprice = (string)$item->OfferSummary->LowestCollectiblePrice->FormattedPrice;   
//               if(!empty($Lowestcollectibleprice) && $Lowestcollectibleprice != "Too low to display" && $Lowestcollectibleprice != "Price too low to display") 
//                  $post_price = $Lowestcollectibleprice;
//            }
                        
            // If still no price then bail
//            if(empty($post_price)) 
//               continue;
                           
//           echo "Title: $post_title<br>Price:$post_price<br><br>";

            $return["results"][$post_id] = Array('network' => 'Amazon', 'title' => $post_title, 'desc' => $post_desc, 'image' => $post_image, 'price' => $post_price, 'sourceUrl' => $item->DetailPageURL);
            
            $numCreated++;
                        
            if( $numCreated == $numPosts)
               break;
         }

         // Page Loop
         if( $numCreated == $numPosts)
            break;         
            
         $page++;
                     
      } while($page <= 5);   
      
       $return["num_posts"] = $numCreated;
//       $return["next_page"] = $page < 5 ? $page+1 : 1;
      $return["next_page"] = $page+1;
             
      return $return;
   }
   
   function import_items($itemids, $poststatus, $postcat) {
   
      $errors = Array();
      foreach ($itemids as $ASIN) {
         $result = $this->import_item($ASIN, $poststatus, $postcat);
         if(is_array($result)) {
            $errors[] = $result["error"]["module"].": ".$result["error"]["message"]."<br>";  
         }
      }
      
      return $errors;
   
   }
   
   function import_item($ASIN, $poststatus, $postcat) {
      global $wpdb;

      $resultxml = $this->aws_request($this->options['amzregion'], array(
   		"Operation"=>"ItemLookup",
   		"AssociateTag"=>$this->options['amzaffid'],
   		"IdType"=>'ASIN',
   		"ItemId"=>$ASIN,
   		"Condition"=>"New",
   		"ReviewSort"=>"-HelpfulVotes",
   		"TruncateReviewsAt"=>"1000",
   		"IncludeReviewsSummary"=>"True",
   		"ResponseGroup"=>"Large"
   		), $this->options['amzpubkey'], $this->options['amzprikey']);	
   
      if(!empty($resultxml["error"])) {return $resultxml;}
         
      if (isset($resultxml->Error)) {
      	$message = 'There was a problem with your Amazon API request: <i><b>'.$resultxml->Error->Code.':</b> '.$resultxml->Error->Message.'</i>';	
      	$return["error"]["module"] = "Amazon";
      	$return["error"]["reason"] = "API fail";
      	$return["error"]["message"] = $message;	
      	return $return;
      }
      
      if (isset($resultxml->Items->Error)) {
      	$message = 'There was a problem with your Amazon API request: <i><b>'.$resultxml->Items->Error->Code.':</b> '.$resultxml->Items->Error->Message.'</i>';	
      	$return["error"]["module"] = "Amazon";
      	$return["error"]["reason"] = "API fail";
      	$return["error"]["message"] = $message;	
      	return $return;
      }
      
      if (isset($resultxml->Items->Request->Errors)) {
         $message = 'There was a problem with your Amazon API request: <i><b>'.$resultxml->Items->Request->Errors->Error->Code.':</b> '.$resultxml->Items->Request->Errors->Error->Message.'</i> ';	
         $return["error"]["module"] = "Amazon";
         $return["error"]["reason"] = "API fail";
         $return["error"]["message"] = $message;	
         return $return;
      }
         
      $item = $resultxml->Items->Item;
      
      $post_asin = trim((string)$item->ASIN);
      // Get the title
      $post_title = (string)$item->ItemAttributes->Title;
      
      // Check for exisintg post         
		$results = $wpdb->get_row( $wpdb->prepare("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s", 'imwb_cc_amazon_asin', $post_asin) );
		
		if(count($results) > 0) 
		   return true;
		   
	   $post_link = trim((string)$item->DetailPageURL);
      
      // Get the description
      $desc = "";
      if (isset($item->EditorialReviews->EditorialReview)) {
			foreach($item->EditorialReviews->EditorialReview as $descs) {
		      $desc .= strip_tags((string)$descs->Content, "<img><p><br><br/><h1><h2><h3><h4>");
			}		
		}	
		
		// If select to have feature list then include it in the description
		$featureList = "";
		if($this->options['amzincfeatures'] == 'Y') {  		
			if (isset($item->ItemAttributes->Feature)) {	
				$featureList = "<h3>Product Features</h3><ul>";
				foreach($item->ItemAttributes->Feature as $feature) {
					$posx = strpos($feature, "href=");
					if ($posx === false) {
						$featureList .= "<li>".$feature."</li>";		
					}
				}	
				$featureList .= "</ul>";				
			}
		}
		   			
      // set category
      $post_category = $postcat;
      
      // Get the Price
      $itemPrice = $this->get_price($item);
      if($itemPrice === false)
         continue;
         
      $post_price =  $itemPrice['post_price'];
      $post_currency = $itemPrice['post_currency'];
      
      // Get the Price & Currency
//      $lowestnewprice = (string)$item->OfferSummary->LowestNewPrice->FormattedPrice;
//      $listprice = (string)$item->ItemAttributes->ListPrice->Amount;
//      $post_currency = (string)$item->ItemAttributes->ListPrice->CurrencyCode;
//      $post_currency = $this->currency_symbols[$post_currency];
//      
//      if(empty($lowestnewprice) || $lowestnewprice == "Too low to display" || $lowestnewprice == "Price too low to display") 
//      	$post_price = $listprice;
//      else {
//         $post_price = (string)$item->OfferSummary->LowestNewPrice->Amount;
//         $post_currency = (string)$item->OfferSummary->LowestNewPrice->CurrencyCode;
//         $post_currency = $this->currency_symbols[$post_currency];
//      }
      
      // Now see if there is an offer
//      $totOffers = $item->Offers->TotalOffers;
//      if(isset($totOffers) && $totOffers > 0) {
         // Now find the New Condition Offer
//         foreach ($item->Offers->Offer as $offer) {
//            if($offer->OfferAttributes->Condition == 'New') {
//               $offer_price = (string)$offer->OfferListing->Price->FormattedPrice;
//               if($offer_price != "Too low to display") {
//                  $post_price = (string)$offer->OfferListing->Price->Amount;
//                  $post_currency = (string)$offer->OfferListing->Price->CurrencyCode;
//                  $post_currency = $this->currency_symbols[$post_currency]; 
//               }
//               $offer_saleprice = $offer->OfferListing->SalePrice;
//               if(isset($offer_saleprice) && (string)$offer_saleprice->FormattedPrice != "Too Low to Display") {
//                  $post_price = (string)$offer_saleprice->Amount;
//                  $post_currency = (string)$offer_saleprice->CurrencyCode;
//                  $post_currency = $this->currency_symbols[$post_currency]; 
//               }
//            }
//         }
//      }
      
      // If price is still not found then try to see if collectable price available
//      if(empty($post_price)) {
//         $Lowestcollectibleprice = (string)$item->OfferSummary->LowestCollectiblePrice->FormattedPrice;   
//         if(!empty($Lowestcollectibleprice) && $Lowestcollectibleprice != "Too low to display" && $Lowestcollectibleprice != "Price too low to display") {
//            $post_price = (string)$item->OfferSummary->LowestCollectiblePrice->Amount;
//            $post_currency = (string)$item->OfferSummary->LowestCollectiblePrice->CurrencyCode;
//            $post_currency = $this->currency_symbols[$post_currency];            
//         }
//      }
//      
//      $post_price = $post_price /100;
      
      // Get The Tags
      $post_tags = array();	
      if($this->options['createtags'] == 'Y') {
         $post_tags = imwb_zonpress_theme_products_get_tags($post_title, $this->options['badtags']);
      }

      // Save Post
      $post_content = wpautop($desc.$featureList);
      $post_type = "post";
      $post_date = current_time('mysql');
      $post_date_gmt = current_time('mysql', 1);
      $post_author = 1;
      $post_status =  $poststatus;

//     echo "Title: $post_title<br>Content: $post_content<br>CatId:$post_category<br>AuthorId:$post_author<br>Post Price:$post_price<br>Post Currency:$post_currency<br>";

     	$post_data = compact('post_content','post_title','post_date','post_date_gmt','post_author','post_category', 'post_status', 'post_type');		
      $post_data['tags_input'] = implode(',', $post_tags);
      $post_data = add_magic_quotes($post_data);
      $postId = wp_insert_post($post_data);
      if (is_wp_error($postId)) {
         $return["error"]["module"] = "Amazon ($keyword)";
         $return["error"]["reason"] = "Error Inserting Post";
         $return["error"]["message"] = $postId->get_error_message();	
         return $return;
      }
      
      // Store the product ID so we don't post duplicates
      update_post_meta( $postId , 'imwb_cc_amazon_asin', $post_asin );
      
      // Set the last updated time to now
      update_post_meta( $postId, '_imwb_cc_amazon_asin_updated', time());
      
      // Update Featured image
      $post_image = $item->LargeImage->URL;
      if($post_image == "") {$post_image = $item->MediumImage->URL;}	
      // Try the image sets
      if($post_image == "") {$post_image = $item->ImageSets->ImageSet->LargeImage->URL;}
      if($post_image == "") {$post_image = $item->ImageSets->ImageSet->MediumImage->URL;}	                  
      if($post_image != "") 
         imwb_zonpress_theme_products_set_featured_image($postId, $post_image);
      
      // Set CSB Metadata fields
      update_post_meta( $postId, 'imwb_zonpress_post_producturl', $post_link);
      update_post_meta( $postId, 'imwb_zonpress_post_price', $post_price);
      update_post_meta( $postId, 'imwb_zonpress_post_currency', $post_currency);
      update_post_meta( $postId, '_imwb_zonpress_post_imp', 0 );
      update_post_meta( $postId, '_imwb_zonpress_post_clicks', 0);
      update_post_meta( $postId, '_imwb_zonpress_post_ctr', 0); 
      
      // Set other IMWB plugins/themes metadata
      update_post_meta( $postId, 'imwb_interest_post_link_url', $post_link);
      update_post_meta( $postId, 'imwb_interest_post_link_text', 'From Amazon');
      
      // Comments
      if($this->options['addcomments'] == 'Y') {
         $CustomerReviewsURL = $item->CustomerReviews->IFrameURL;
         $response = wp_remote_get( $CustomerReviewsURL);
         if( !is_wp_error( $response ) ) {
            $content = $response['body'];
            if (preg_match('#<body[^>]*>(.*?)</body>#si', $content, $body)) 
               $this->do_comments($postId, $body[1]); 
         }            
      }     
               
      return true;
   }
   
   function update_item($postId, $ASIN) {
      global $wpdb;

      $resultxml = $this->aws_request($this->options['amzregion'], array(
   		"Operation"=>"ItemLookup",
   		"AssociateTag"=>$this->options['amzaffid'],
   		"IdType"=>'ASIN',
   		"ItemId"=>$ASIN,
   		"Condition"=>"New",
   		"ReviewSort"=>"-HelpfulVotes",
   		"TruncateReviewsAt"=>"1000",
   		"IncludeReviewsSummary"=>"True",
   		"ResponseGroup"=>"Large"
   		), $this->options['amzpubkey'], $this->options['amzprikey']);	
   
      if(!empty($resultxml["error"])) {return $resultxml;}
      
      // Check for errors
      $result = $resultxml->xpath("//Errors");
      if($result) {
      
      	$return["error"]["module"] = "Amazon";
         $return["error"]["message"] = __( 'The Following Errors Occured', 'imwb_zonpress' ).'<br>';
      	$return["error"]["reason"] = "API fail";         

         foreach ($result as $error) {
            // See if the item is no longer valiv
            if((string)$error->Error->Code == 'AWS.InvalidParameterValue') {
               wp_delete_post($postId);
               return true;
            }
            $return["error"]["message"].= " Error: ".$error->Error->Code." - ".$error->Error->Message."<br>";
         }

         return $return;
      }
                  
      $item = $resultxml->Items->Item;
      
      // Get the Price
      $itemPrice = $this->get_price($item);
      if($itemPrice === false){
         update_post_meta( $postId, '_imwb_cc_amazon_asin_updated', time());
         return;
      }
               
      $post_price =  $itemPrice['post_price'];
      $post_currency = $itemPrice['post_currency'];
      
      // Get the Price & Currency
//      $lowestnewprice = (string)$item->OfferSummary->LowestNewPrice->FormattedPrice;
//      $listprice = (string)$item->ItemAttributes->ListPrice->Amount;
//      $post_currency = (string)$item->ItemAttributes->ListPrice->CurrencyCode;
//      $post_currency = $this->currency_symbols[$post_currency];
//      
//      if(empty($lowestnewprice) || $lowestnewprice == "Too low to display" || $lowestnewprice == "Price too low to display") 
//      	$post_price = $listprice;
//      else {
//         $post_price = (string)$item->OfferSummary->LowestNewPrice->Amount;
//         $post_currency = (string)$item->OfferSummary->LowestNewPrice->CurrencyCode;
//         $post_currency = $this->currency_symbols[$post_currency];
//      }
      
      // Now see if there is an offer
//      $totOffers = $item->Offers->TotalOffers;
//      if(isset($totOffers) && $totOffers > 0) {
         // Now find the New Condition Offer
//         foreach ($item->Offers->Offer as $offer) {
//            if($offer->OfferAttributes->Condition == 'New') {
//               $offer_price = (string)$offer->OfferListing->Price->FormattedPrice;
//               if($offer_price != "Too low to display") {
//                  $post_price = (string)$offer->OfferListing->Price->Amount;
//                  $post_currency = (string)$offer->OfferListing->Price->CurrencyCode;
//                  $post_currency = $this->currency_symbols[$post_currency]; 
//               }
//               $offer_saleprice = $offer->OfferListing->SalePrice;
//               if(isset($offer_saleprice) && (string)$offer_saleprice->FormattedPrice != "Too Low to Display") {
//                  $post_price = (string)$offer_saleprice->Amount;
//                  $post_currency = (string)$offer_saleprice->CurrencyCode;
//                  $post_currency = $this->currency_symbols[$post_currency]; 
//               }
//            }
//         }
//      }
      
      // If price is still not found then try to see if collectable price available
//      if(empty($post_price)) {
//         $Lowestcollectibleprice = (string)$item->OfferSummary->LowestCollectiblePrice->FormattedPrice;   
//         if(!empty($Lowestcollectibleprice) && $Lowestcollectibleprice != "Too low to display" && $Lowestcollectibleprice != "Price too low to display") {
//            $post_price = (string)$item->OfferSummary->LowestCollectiblePrice->Amount;
//            $post_currency = (string)$item->OfferSummary->LowestCollectiblePrice->CurrencyCode;
//            $post_currency = $this->currency_symbols[$post_currency];            
//         }
//      }
      
//      if(empty($post_price) || $post_price == 0) {
//         update_post_meta( $postId, '_imwb_cc_amazon_asin_updated', time());
//         return;
//      }
//      echo "Updating Price of post ID ".$postId." to ".$post_currency.'::'.$post_price.'::';
   
//      $post_price = $post_price /100;
                        
      // Set the last updated time to now
      update_post_meta( $postId, '_imwb_cc_amazon_asin_updated', time());
      
      // Set CSB Metadata fields
      update_post_meta( $postId, 'imwb_zonpress_post_price', $post_price);
      update_post_meta( $postId, 'imwb_zonpress_post_currency', $post_currency); 
               
      return true;
   }

    function do_comments($postId, $commentsHTML) {
   
         $dom = new DOMDocument();
         $dom->preserveWhiteSpace = false;
         $dom->loadHTML($commentsHTML);	
    
      	$xpath = new DOMXPath($dom);
      	
         $comments = array();
         
         $nodes = $xpath->query("//table[@class='crIFrameReviewList']//tr/td/div");		
         $y=0;
         foreach($nodes as $node) {
            $title = $xpath->query("div/b", $node)->item(0);
            $comments[$y]["title"] = $title->textContent;
            $desc = $xpath->query("div[@class='reviewText']", $node)->item(0);
            if($desc === NULL) 
               $comments[$y]["content"] = trim(strip_tags(preg_replace('/<([\w]+)[^>]*>(.*?)<\/\1>/s', '', $dom->saveHTML($node))));
            else
               $comments[$y]["content"] = $desc->textContent;
            $author = $xpath->query("div/div/div/a/span", $node)->item(0);
            $comments[$y]["author"] = $author->textContent;
            
            $y++;
         }
               
         // Add comment is any found
         if(count($comments) == 0)
            return;
            
         if($this->options['randcomments'] == 'Y') {
         	$totCount = count($comments);
         	$half = ceil($totCount / 2);
         	$cnum = rand($half,$totCount);
         } else {
         	$cnum = count($comments);
         }   
   
      	$comment_ts = current_time('timestamp');	
      	
         $i = 0;
   		foreach ($comments as $comment) {
   			if($i == $cnum) 
   			   break;
   			   
   			$comment_post_ID=$postId;
   			$comment_ts = $comment_ts + (rand(0, 30) * 60 + rand(0, 59));
            $comment_date = date('Y-m-d H:i:s', $comment_ts);
   			$rnd= rand(1,9999);
   			$comment_author_email="noreply$rnd@yourdomain.com";
   			$comment_author=$comment["author"];
   			$comment_author_url='';  
   			$comment_content='<strong>'.$comment["title"].'</strong> '.$comment["content"];			
   			$comment_type='';
   			$user_ID='';
   			$comment_approved = 1;
   			$commentdata = compact('comment_post_ID', 'comment_date', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'user_ID', 'comment_approved');
   			$comment_id = wp_insert_comment( $commentdata );
   			$i++;
   		}
      }
   
   
   function aws_request($region, $params, $public_key, $private_key) {
   	libxml_use_internal_errors(true);
   	$method = "GET";
//   	$host = "ecs.amazonaws.".$region;
   	$host = "webservices.amazon.".$region;
   	$uri = "/onca/xml";
   
   	$params["Service"] = "AWSECommerceService";
   	$params["AWSAccessKeyId"] = $public_key;
   	
   	$t = time() + 10000;
   	$params["Timestamp"] = gmdate("Y-m-d\TH:i:s\Z",$t);	
   	$params["Version"] = "2011-08-01";
   	ksort($params);
   	
   	$canonicalized_query = array();
   	foreach ($params as $param=>$value) {
   		$param = str_replace("%7E", "~", rawurlencode($param));
   		$value = str_replace("%7E", "~", rawurlencode($value));
   		$canonicalized_query[] = $param."=".$value;
   	}

   	$canonicalized_query = implode("&", $canonicalized_query);
   	$string_to_sign = $method."\n".$host."\n".$uri."\n".$canonicalized_query;   
   	$signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));  
   	$signature = str_replace("%7E", "~", rawurlencode($signature));  
   	$request = "http://".$host.$uri."?".$canonicalized_query."&Signature=".$signature; 
//   echo $request."<br><br>";
   	
   	$response = wp_remote_get($request);
      if( is_wp_error( $response ) ) {
  	      $return["error"]["module"] = "Amazon";
  	      $return["error"]["reason"] = "Error Connecting to Amazon API";
  	      $return["error"]["message"] = $response->get_error_message();	
  	      return $return;
     }	 	
// echo '<br><br>Response:<pre>';
//   print_r( $response['body'] );
//   echo '</pre>';
     $xmlString = str_replace('xmlns=', 'ns=', $response['body']); 
     $pxml = simplexml_load_string($xmlString);
     if ($pxml === False) {
   		$emessage = "Failed loading XML, errors returned: ";
   		foreach(libxml_get_errors() as $error) {
   			$emessage .= $error->message . ", ";
   		}	
   		libxml_clear_errors();
   		$return["error"]["module"] = "Amazon";
   		$return["error"]["reason"] = "XML Error";
   		$return["error"]["message"] = $emessage;	
   		return $return;			
   	} else {

   		return $pxml;
   	}
   } 
}


?>