<?php

if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__)
  .' is not allowed.' );

/**
 *
 * @package  MediaLibrary
 * @copyright 2021 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); Rob de Cleen(rob@decleen.com);
 * Homepage: https://ordasoft.com
 * @version: 4.6 Free
 * @license GNU General Public license version 2 or later; see LICENSE.txt
 *
 */

class SearchItemsRequest {
    public $PartnerType;
    public $PartnerTag;
    public $Keywords;
    public $SearchIndex;
    public $Resources;
}

class GetItemsRequest {
    public $PartnerType;
    public $PartnerTag;
    public $ItemIds;
    public $ItemIdType;
    public $Resources;
}


class AwsV4 {

    private $accessKeyID = null;
    private $secretAccessKey = null;
    private $path = null;
    private $regionName = null;
    private $serviceName = null;
    private $httpMethodName = null;
    private $queryParametes = array ();
    private $awsHeaders = array ();
    private $payload = "";

    private $HMACAlgorithm = "AWS4-HMAC-SHA256";
    private $aws4Request = "aws4_request";
    private $strSignedHeader = null;
    private $xAmzDate = null;
    private $currentDate = null;

    public function __construct($accessKeyID, $secretAccessKey) {
        $this->accessKeyID = $accessKeyID;
        $this->secretAccessKey = $secretAccessKey;
        $this->xAmzDate = $this->getTimeStamp ();
        $this->currentDate = $this->getDate ();
    }

    function setPath($path) {
        $this->path = $path;
    }

    function setServiceName($serviceName) {
        $this->serviceName = $serviceName;
    }

    function setRegionName($regionName) {
        $this->regionName = $regionName;
    }

    function setPayload($payload) {
        $this->payload = $payload;
    }

    function setRequestMethod($method) {
        $this->httpMethodName = $method;
    }

    function addHeader($headerName, $headerValue) {
        $this->awsHeaders [$headerName] = $headerValue;
    }

    private function prepareCanonicalRequest() {
        $canonicalURL = "";
        $canonicalURL .= $this->httpMethodName . "\n";
        $canonicalURL .= $this->path . "\n" . "\n";
        $signedHeaders = '';
        foreach ( $this->awsHeaders as $key => $value ) {
            $signedHeaders .= $key . ";";
            $canonicalURL .= $key . ":" . $value . "\n";
        }
        $canonicalURL .= "\n";
        $this->strSignedHeader = substr ( $signedHeaders, 0, - 1 );
        $canonicalURL .= $this->strSignedHeader . "\n";
        $canonicalURL .= $this->generateHex ( $this->payload );
        return $canonicalURL;
    }

    private function prepareStringToSign($canonicalURL) {
        $stringToSign = '';
        $stringToSign .= $this->HMACAlgorithm . "\n";
        $stringToSign .= $this->xAmzDate . "\n";
        $stringToSign .= $this->currentDate . "/" . $this->regionName . "/" . $this->serviceName . "/" . $this->aws4Request . "\n";
        $stringToSign .= $this->generateHex ( $canonicalURL );
        return $stringToSign;
    }

    private function calculateSignature($stringToSign) {
        $signatureKey = $this->getSignatureKey ( $this->secretAccessKey, $this->currentDate, $this->regionName, $this->serviceName );
        $signature = hash_hmac ( "sha256", $stringToSign, $signatureKey, true );
        $strHexSignature = strtolower ( bin2hex ( $signature ) );
        return $strHexSignature;
    }

    public function getHeaders() {
        $this->awsHeaders ['x-amz-date'] = $this->xAmzDate;
        ksort ( $this->awsHeaders );
        $canonicalURL = $this->prepareCanonicalRequest ();
        $stringToSign = $this->prepareStringToSign ( $canonicalURL );
        $signature = $this->calculateSignature ( $stringToSign );
        if ($signature) {
            $this->awsHeaders ['Authorization'] = $this->buildAuthorizationString ( $signature );
            return $this->awsHeaders;
        }
    }

    private function buildAuthorizationString($strSignature) {
        return $this->HMACAlgorithm . " " . "Credential=" . $this->accessKeyID . "/" . $this->getDate () . "/" . $this->regionName . "/" . $this->serviceName . "/" . $this->aws4Request . "," . "SignedHeaders=" . $this->strSignedHeader . "," . "Signature=" . $strSignature;
    }

    private function generateHex($data) {
        return strtolower ( bin2hex ( hash ( "sha256", $data, true ) ) );
    }

    private function getSignatureKey($key, $date, $regionName, $serviceName) {
        $kSecret = "AWS4" . $key;
        $kDate = hash_hmac ( "sha256", $date, $kSecret, true );
        $kRegion = hash_hmac ( "sha256", $regionName, $kDate, true );
        $kService = hash_hmac ( "sha256", $serviceName, $kRegion, true );
        $kSigning = hash_hmac ( "sha256", $this->aws4Request, $kService, true );

        return $kSigning;
    }

    private function getTimeStamp() {
        return gmdate ( "Ymd\THis\Z" );
    }

    private function getDate() {
        return gmdate ( "Ymd" );
    }
}






class mosMedialibraryWS{

  /**
   * Catching information from array - in the correct language
   * @return array that contains all Output from getWSArray() including the
   * possibility for user to input the information directly
   */
  static function getArray(){
    $help = mosMedialibraryWS::getWSArray();
    $help1 = array();
    array_push($help1, array(0, _MEDIALIBRARY_WS_NO, ""));
    return array_merge($help1, $help);
  }


  /**
   * Catching WS Informations array
   * @return array containing all possible WS and their settings
   */
   
  static function getWSArray(){
    $retVal = array();
    array_push($retVal, array(1, _MEDIALIBRARY_AMAZON_COM, "COM"));
    array_push($retVal, array(2, _MEDIALIBRARY_AMAZON_UK, "UK"));
    array_push($retVal, array(3, _MEDIALIBRARY_AMAZON_DE, "DE"));
    array_push($retVal, array(4, _MEDIALIBRARY_AMAZON_JP, "JP"));
    array_push($retVal, array(5, _MEDIALIBRARY_AMAZON_FR, "FR"));
    array_push($retVal, array(6, _MEDIALIBRARY_AMAZON_CA, "CA"));
    array_push($retVal, array(7, _MEDIALIBRARY_AMAZON_IT, "IT"));
    array_push($retVal, array(8, _MEDIALIBRARY_AMAZON_ES, "ES"));
    array_push($retVal, array(9, _MEDIALIBRARY_AMAZON_CN, "CN"));
    array_push($retVal, array(10, _MEDIALIBRARY_AMAZON_US, "US"));
    array_push($retVal, array(11, _MEDIALIBRARY_AMAZON_IN, "IN"));
    array_push($retVal, array(12, _MEDIALIBRARY_AMAZON_BR, "BR"));
    return $retVal;
  }
  
  /**
   * fetch the information from a webservice depending on the $informationFrom
   * variable set in the $book
   * @param medialibrary.class.php store the information that is already
   * known of this book - $informationFrom must be set at least
   * @return medialibrary.class.php including all information that should be
   * added by webservices
   * @global string $medialibrary_configuration
   */

//***********************   add in function 'books'   *************************

  static function fetchAmazonInfosForBook($media,$book) {
      global $medialibrary_configuration,$my,$acl;


//******************************   Added by OrdaSoft   **********************************

      $param_ws = mosMedialibraryWS::getWsParamById($media->informationFrom);
      $Timestamp=date("Y-m-d")."T".date("H:i:s")."Z";

      //if amazon.com
      if (($param_ws == "COM") || ($param_ws == "UK") || ($param_ws == "CA")) {
        try{
       if (($param_ws == "UK") || ($param_ws == "CA")) {
          $client = new soapclient(
          "https://webservices.amazon.com/AWSECommerceService/".$param_ws."/AWSECommerceService.wsdl",
           array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
          'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
          'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
          'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
       } else if (($param_ws == "COM")) {
        $client = new soapclient(
          "https://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl",
          array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
          'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
          'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
          'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
              }
      $client->xml_encoding = "UTF-8";
      $params = array(
          'Request' => array(
                'SearchIndex' => 'Books',//add for isbn-13
                'IdType'=> 'ISBN',//ISBN - for isbn-13  'ASIN' - for isbn-10
                'ItemId' => $book->isbn, //'0596005431',
                'ResponseGroup' =>'Large'),//Medium
//old valid        'AWSAccessKeyId' => '1Z21K9KD9G8MAN3VWV82'
          'AWSAccessKeyId' => $medialibrary_configuration['ws']['amazon']['devtag'],
          'AssociateTag' => $medialibrary_configuration['ws']['amazon']['tag'],
          'Timestamp' => $Timestamp,
          'Signature' => "ItemLookup".$Timestamp
          );
      $result = $client->ItemLookup($params);
        }
        catch (SoapFault $fault) {
      $retVal = "SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})";
      return $retVal;
        }
      }

      //if amazon. UK--yes DE--yes JP--yes(not reviews) FR--yes CA--yes
      else {

        try{
      $client = new soapclient(
      "https://webservices.amazon.com/AWSECommerceService/" . $param_ws . "/AWSECommerceService.wsdl",
      array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
          'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
          'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
          'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
      $client->xml_encoding = "UTF-8";
      $params = array(
          'Request' => array(
                'IdType'=> 'ASIN',
                'ItemId' => $book->isbn, //'0596005431',
                'ResponseGroup' =>'Large'),//Medium
//old valid        'AWSAccessKeyId' => '1Z21K9KD9G8MAN3VWV82'
          'AWSAccessKeyId' => $medialibrary_configuration['ws']['amazon']['devtag'],
          'AssociateTag' => $medialibrary_configuration['ws']['amazon']['tag'],
          'Timestamp' => $Timestamp,
          'Signature' => "ItemLookup".$Timestamp
          );
      $result = $client->ItemLookup($params);
        }
        catch (SoapFault $fault) {
      $retVal = "SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})";
      return $retVal;
        }
      }

      //Errors test -- 1
      if (array_key_exists('Errors', $result->OperationRequest)) {
         $retVal = "SOAP Fault: (faultcode: {$result->OperationRequest->Errors->Error->Code}, faultstring:   
                    {$result->OperationRequest->Errors->Error->Message})";
         return $retVal;
      }



      //Errors test -- 2
      if (array_key_exists('Errors', $result->Items->Request)) {
    $retVal = "SOAP Fault: (faultcode: {$result->Items->Request->Errors->Error->Code}, faultstring:  
                     {$result->Items->Request->Errors->Error->Message})";
    return $retVal;
      }

      //Body -- Output in joomla form
      //ProductName
      $book->title = $result->Items->Item->ItemAttributes->Title;

      //ImageUrlMedium
      $book->imageURL = $result->Items->Item->MediumImage->URL;

      //URL
      $book->URL = $result->Items->Item->DetailPageURL;

      //Manufacturer
      if (array_key_exists('Manufacturer', $result->Items->Item->ItemAttributes)) {
         $book->manufacturer = $result->Items->Item->ItemAttributes->Manufacturer;
      }


      //Author
      $book->authors = "";
      if ( is_array($result->Items->Item->ItemAttributes->Author) ) {    //Authors array
         foreach ($result->Items->Item->ItemAttributes->Author as $Author) {
           if (strlen($book->authors) > 0) {
        $book->authors = $book->authors . ", " . $Author;
           }
           else { $book->authors = $Author; }
         }
      }
      else {
      $book->authors = $result->Items->Item->ItemAttributes->Author;    //Authors not array
      }

      //Rating
      if (array_key_exists('CustomerReviews', $result->Items->Item)) {
         $book->rating = ($result->Items->Item->CustomerReviews->AverageRating * 2);
      }

      //PublicationDate
      if (array_key_exists('PublicationDate', $result->Items->Item->ItemAttributes)) {
         $book->release_date = $result->Items->Item->ItemAttributes->PublicationDate;
      }

      //ReleaseDate
      if (array_key_exists('ReleaseDate', $result->Items->Item->ItemAttributes)) {
         $book->release_date = $result->Items->Item->ItemAttributes->ReleaseDate;
      }

      //Edition
      if ( array_key_exists('Edition', $result->Items->Item->ItemAttributes) ) {
         $book->edition = $result->Items->Item->ItemAttributes->Edition;
      }

 //Price no partner
      if ( array_key_exists('Offer', $result->Items->Item->Offers) && array_key_exists('FormattedPrice',  
                     $result->Items->Item->Offers->Offer->OfferListing->Price)) {
         $book->price = substr_replace((string)$result->Items->Item->Offers->Offer->OfferListing->Price->Amount
              ,'.',-2,0);
         $book->priceunit = (string)$result->Items->Item->Offers->Offer->OfferListing->Price->CurrencyCode;
         $mas = $book->price;
         $book->price = $mas;
      }else if ( array_key_exists('ListPrice', $result->Items->Item->ItemAttributes) &&       
          array_key_exists('Amount', $result->Items->Item->ItemAttributes->ListPrice)) {

         $book->price = substr_replace((string)$result->Items->Item->ItemAttributes->ListPrice->Amount,'.',-2,0);
         $book->priceunit = (string)$result->Items->Item->ItemAttributes->ListPrice->CurrencyCode;
      }
      else {
        $book->price = "Does not exist anymore!";
      }
//************************   begin add for  Description   *********************
      if(($medialibrary_configuration['merge_description']['use'])){

              if (checkAccess_ML( $medialibrary_configuration['merge_description']['registrationlevel']
                    ,'RECURSE',   
                    userGID_ML($my->id), $acl)) {

                      $book->comment = $book->comment . "<br /><p></p> ";
              } else $book->comment = "";
      } else $book->comment = "";
      
      if ((array_key_exists('EditorialReviews', $result->Items->Item)) && (array_key_exists('EditorialReview',  
                     $result->Items->Item->EditorialReviews))) {
    if (count($result->Items->Item->EditorialReviews->EditorialReview) == 1) {
       $book->comment .= "<strong>".$result->Items->Item->EditorialReviews->EditorialReview->Source
        ."</strong><br />";
       $book->comment .= $result->Items->Item->EditorialReviews->EditorialReview->Content;
    } else if (count($result->Items->Item->EditorialReviews->EditorialReview) >= 1) {
        for ($i = 0; $i < count($result->Items->Item->EditorialReviews->EditorialReview); $i++ ) {
        $book->comment .= "<strong>".$result->Items->Item->EditorialReviews->EditorialReview[$i]->Source
            ."</strong><br />";
        $book->comment .= $result->Items->Item->EditorialReviews->EditorialReview[$i]->Content."<br />";
        }//end for
           }//end if    
      }
//************************   end add for Book Description   ************************
      return $book;
  }

//****************************   End of Added by Orda   *****************************


  
  /**
   * Get the name of the WS by the id
   * @param int $id the id of the WS-Name that should be returned
   * @return string the name of the WS or null if it can't be found
   */  
  static function getWsNameById($id){  
    $services = mosMedialibraryWS::getArray();
    for($i=0, $n=count($services); $i < $n; $i++){
      if(intval($services[$i][0]) == intval($id)){
        return $services[$i][1];
      }    
    }  
    return null;    
  }

  /**
   * Get the parameter of the WS by the id
   * @param int $id the id of the WS-pram that should be returned
   * @return string the parameter of the WS or null if it can't be found
   */    
  static function getWsParamById($id){
    $services = mosMedialibraryWS::getArray();
    for($i=0, $n=count($services); $i < $n; $i++){
      if(intval($services[$i][0]) == intval($id)){
        return $services[$i][2];
      }    
    }  
    return null;  
  }
//***********************   add in function 'music'   *************************

static function fetchAmazonInfosForMusic($media,$music) {
//******************************   Added by OrdaSoft   **********************************
      global $medialibrary_configuration,$my,$acl ;
  
//______________________________   Added by OrdaSoft  _____________________________

      $param_ws = mosMedialibraryWS::getWsParamById($media->informationFrom);
      $Timestamp=date("Y-m-d")."T".date("H:i:s")."Z";
      //if amazon.com
      if (($param_ws == "COM") || ($param_ws == "UK") || ($param_ws == "CA")) {
        try{
            if (($param_ws == "UK") || ($param_ws == "CA")) {
                $client = new soapclient(
                "https://webservices.amazon.com/AWSECommerceService/".$param_ws."/AWSECommerceService.wsdl",
                array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
                'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
                'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
                'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
            } else if (($param_ws == "COM")) {
              $client = new soapclient(
                "https://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl",
                array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
                'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
                'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
                'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
            }
            $client->xml_encoding = "UTF-8";
            $params = array('Request' => array('IdType'=> 'ASIN',
                  'ItemId' => $music->asin,
                  'ResponseGroup' =>'Large'
                ),
  //old valid        'AWSAccessKeyId' => '1Z21K9KD9G8MAN3VWV82'
                'AWSAccessKeyId' => $medialibrary_configuration['ws']['amazon']['devtag'],
                'AssociateTag' => $medialibrary_configuration['ws']['amazon']['tag'],
                'Timestamp' => $Timestamp,
                'Signature' => "ItemLookup".$Timestamp
               );         
                    
            $result = $client->ItemLookup($params);

          } catch (SoapFault $fault) {
            $retVal = "SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})";
            return $retVal;
            trigger_error("SOAP Fault: (faultcode: {$fault->faultcode},".
              " faultstring: {$fault->faultstring})", E_USER_ERROR);
          }
      }
      //if amazon. UK--yes DE--yes JP--yes(not reviews) FR--yes CA--yes
      else {
        try{
          $client = new soapclient(
          "https://webservices.amazon.com/AWSECommerceService/" . $param_ws . "/AWSECommerceService.wsdl",
          array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
              'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
              'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
              'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
          $client->xml_encoding = "UTF-8";
          $params = array(
                'Request' => array(
                    'IdType'=> 'ASIN',
                    'ItemId' => $music->asin, //'0596005431',
                    'ResponseGroup' =>'Large'),//Medium
//old valid        'AWSAccessKeyId' => '1Z21K9KD9G8MAN3VWV82'
                'AWSAccessKeyId' => $medialibrary_configuration['ws']['amazon']['devtag'],
                'AssociateTag' => $medialibrary_configuration['ws']['amazon']['tag'],
                'Timestamp' => $Timestamp,
                'Signature' => "ItemLookup".$Timestamp
                );
          $result = $client->ItemLookup($params);
        }
        catch (SoapFault $fault) {
            $retVal = "SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})";
            return $retVal;
            trigger_error("SOAP Fault: (faultcode: {$fault->faultcode},"
              ." faultstring: {$fault->faultstring})", E_USER_ERROR);
        }
      }

      //Errors test -- 1
      if (array_key_exists('Errors', $result->OperationRequest)) {
          $retVal = "SOAP Fault: (faultcode: {$result->OperationRequest->Errors->Error->Code},"
            ." faultstring: {$result->OperationRequest->Errors->Error->Message})";
         return $retVal;
      }
      

      //Errors test -- 2
      if (array_key_exists('Errors', $result->Items->Request)) {
        $retVal = "SOAP Fault: (faultcode: {$result->Items->Request->Errors->Error->Code},".
          " faultstring: {$result->Items->Request->Errors->Error->Message})";
        return $retVal;
      }

//      get tracks
      $TrackTitle = '';
      // one cd
//      if ($result->Items->Item->ItemAttributes->NumberOfDiscs == 1)
      if ( !is_array($result->Items->Item->Tracks->Disc) )
      {
        for ($track = 1; $track < count ($result->Items->Item->Tracks->Disc->Track); $track++)
        {
          $TrackTitle .= $result->Items->Item->Tracks->Disc->Track[$track]->_;
          $TrackTitle .= ";";  
        }
      }
      //array cd
      else
      {

//if we see that echo - need some check
//echo "if we see that echo - need some check";

        for ($cd = 0; $cd < $result->Items->Item->ItemAttributes->NumberOfDiscs; $cd++)
        {
          $TrackTitle .="CD ".($cd+1).';';
          for ($track = 1; $track < count ($result->Items->Item->Tracks->Disc[$cd]->Track);$track++)
          {
            $TrackTitle .= $result->Items->Item->Tracks->Disc[$cd]->Track[$track]->_;
            $TrackTitle .= ';';
          }
        }
      }

      //track list
      $music->tracklist = $TrackTitle;

      if ( array_key_exists('Offer', $result->Items->Item->Offers) && array_key_exists('FormattedPrice',  
                     $result->Items->Item->Offers->Offer->OfferListing->Price)) {
         $music->price = substr_replace((string)$result->Items->Item->Offers->Offer->OfferListing->Price->Amount,
            '.',-2,0);
         $music->priceunit = (string)$result->Items->Item->Offers->Offer->OfferListing->Price->CurrencyCode;
         $mas = $music->price;
         $music->price = $mas;
      }else if ( array_key_exists('ListPrice', $result->Items->Item->ItemAttributes) &&       
          array_key_exists('Amount', $result->Items->Item->ItemAttributes->ListPrice)) {

         $music->price = substr_replace((string)$result->Items->Item->ItemAttributes->ListPrice->Amount,'.',-2,0);
         $music->priceunit = (string)$result->Items->Item->ItemAttributes->ListPrice->CurrencyCode;
      }
      else {
        $music->price = "Does not exist anymore!";
      }
    //Rating
    if (array_key_exists('CustomerReviews', $result->Items->Item)) {
      $music->rating = ($result->Items->Item->CustomerReviews->AverageRating * 2);
    }
    //datetime
    //ReleaseDate
    if (array_key_exists('ReleaseDate', $result->Items->Item->ItemAttributes)) {
      $music->release_date = $result->Items->Item->ItemAttributes->ReleaseDate;
    }
    //binding
    $music->binding = $result->Items->Item->ItemAttributes->Binding;
    //ImageUrlMedium
    $music->imageURL = $result->Items->Item->MediumImage->URL;
    //URL
    $music->URL = $result->Items->Item->DetailPageURL;
      //add artisi
    $music->artist = $result->Items->Item->ItemAttributes->Artist;
      //add title
    $music->title = $result->Items->Item->ItemAttributes->Title;
      //add  number_of_discs
    $music->number_of_discs = $result->Items->Item->ItemAttributes->NumberOfDiscs;
      //add label
    $music->label = $result->Items->Item->ItemAttributes->Label;
      //Rating
    if (array_key_exists('CustomerReviews', $result->Items->Item)) {
      $music->rating = ($result->Items->Item->CustomerReviews->AverageRating * 2);
    }
//************************   begin add for music Description   *********************
    if(($medialibrary_configuration['merge_description']['use'])){
        if (checkAccess_ML( $medialibrary_configuration['merge_description']['registrationlevel'],'RECURSE',
         userGID_ML($my->id), $acl)) {
                $music->comment = $music->comment . "<br /><p></p> ";
        } else $music->comment = "";
    } else $music->comment = "";

    if ((array_key_exists('EditorialReviews', $result->Items->Item)) &&
       (array_key_exists('EditorialReview', $result->Items->Item->EditorialReviews))) {
      if (count($result->Items->Item->EditorialReviews->EditorialReview) == 1) {
       $music->comment .= "<strong>".
        $result->Items->Item->EditorialReviews->EditorialReview->Source."</strong><br />";
       $music->comment .= $result->Items->Item->EditorialReviews->EditorialReview->Content;
      } else if (count($result->Items->Item->EditorialReviews->EditorialReview) >= 1) {
        for ($i = 0; $i < count($result->Items->Item->EditorialReviews->EditorialReview); $i++ ) {
          $music->comment .= "<strong>".
            $result->Items->Item->EditorialReviews->EditorialReview[$i]->Source."</strong><br />";
          $music->comment .= $result->Items->Item->EditorialReviews->EditorialReview[$i]->Content."<br />";
        }//end for
      }//end if    
    }
//***************************** end add description  ***************************

    return $music;
  }



//***********************   add in function 'video'   *************************

static function fetchAmazonInfosForVideo($media,$video) {
     
//******************************   Added by OrdaSoft   **************************
      global $medialibrary_configuration,$my,$acl ;
  
//______________________________   Added by OrdaSoft  _____________________________

      $param_ws = mosMedialibraryWS::getWsParamById($media->informationFrom);
      $Timestamp=date("Y-m-d")."T".date("H:i:s")."Z";
      if (($param_ws == "COM") || ($param_ws == "UK") || ($param_ws == "CA")) {
        try{
       if (($param_ws == "UK") || ($param_ws == "CA")) {
          $client = new soapclient(
          "https://webservices.amazon.com/AWSECommerceService/".$param_ws."/AWSECommerceService.wsdl",
           array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
          'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
          'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
          'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
       } else if (($param_ws == "COM")) {
        $client = new soapclient(
          "https://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl",
          array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
          'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
          'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
          'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
              }
      $client->xml_encoding = "UTF-8";
                                $params = array('Request' => array('IdType'=> 'ASIN',
                'ItemId' => $video->asin,
                'ResponseGroup' =>'Large'
                                                            ),
  //old valid        'AWSAccessKeyId' => '1Z21K9KD9G8MAN3VWV82'
          'AWSAccessKeyId' => $medialibrary_configuration['ws']['amazon']['devtag'],
          'AssociateTag' => $medialibrary_configuration['ws']['amazon']['tag'],
          'Timestamp' => $Timestamp,
          'Signature' => "ItemLookup".$Timestamp
                                     );         
                    
             $result = $client->ItemLookup($params);

       } catch (SoapFault $fault) {
      $retVal = "SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})";
      return $retVal;
              trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})",
               E_USER_ERROR);
      }
  }
      //if amazon. UK--yes DE--yes JP--yes(not reviews) FR--yes CA--yes
     else {
        try{
      $client = new soapclient(
      "https://webservices.amazon.com/AWSECommerceService/" . $param_ws . "/AWSECommerceService.wsdl",
      array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
          'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
          'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
          'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
      $client->xml_encoding = "UTF-8";
      $params = array(
          'Request' => array(
                'IdType'=> 'ASIN',
                'ItemId' => $video->asin, //'0596005431',
                'ResponseGroup' =>'Large'),//Medium
//old valid        'AWSAccessKeyId' => '1Z21K9KD9G8MAN3VWV82'
          'AWSAccessKeyId' => $medialibrary_configuration['ws']['amazon']['devtag'],
          'AssociateTag' => $medialibrary_configuration['ws']['amazon']['tag'],
          'Timestamp' => $Timestamp,
          'Signature' => "ItemLookup".$Timestamp
          );
      $result = $client->ItemLookup($params);
        }
        catch (SoapFault $fault) {
      $retVal = "SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})";
      return $retVal;
              trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})",
               E_USER_ERROR);
        }

    }

      //Errors test -- 1
      if (array_key_exists('Errors', $result->OperationRequest)) {
  $retVal = "SOAP Fault: (faultcode: {$result->OperationRequest->Errors->Error->Code}, faultstring:   
                    {$result->OperationRequest->Errors->Error->Message})";
         return $retVal;
      }
      

      //Errors test -- 2
      if (array_key_exists('Errors', $result->Items->Request)) {
    $retVal = "SOAP Fault: (faultcode: {$result->Items->Request->Errors->Error->Code}, faultstring:   
                    {$result->Items->Request->Errors->Error->Message})";
    return $retVal;
      }


    //Title
  $video->title = $result->Items->Item->ItemAttributes->Title;

    //imageURL
  $video->imageURL = $result->Items->Item->MediumImage->URL;

    //URL
  $video->URL = $result->Items->Item->DetailPageURL;

    //Rating
  $video->rating = ($result->Items->Item->CustomerReviews->AverageRating * 2);

    //Actors
  $Actor = '';
  if (is_array($result->Items->Item->ItemAttributes->Actor))
  {
    for ($i = 0; $i<count($result->Items->Item->ItemAttributes->Actor); $i++)
    {
      if ($i) $Actor.=',';
      $Actor.=$result->Items->Item->ItemAttributes->Actor[$i];
    }
  }
  else 
  {
    $Actor = $result->Items->Item->ItemAttributes->Actor;
  }
  if ($Actor != '')$video->actors = $Actor;

  //comments
  $comment = "";
  if(($medialibrary_configuration['merge_description']['use'])){
    if (checkAccess_ML( $medialibrary_configuration['merge_description']['registrationlevel'],'RECURSE', 
        userGID_ML($my->id), $acl)) {
            $comment = $video->comment . "<br /><p></p> ";
    } else $comment = "";
} else $comment = "";

  if(IS_ARRAY($result->Items->Item->EditorialReviews->EditorialReview))
  {
    for ($i = 0; $i < count($result->Items->Item->EditorialReviews->EditorialReview); $i++)
    {
      $comment.="<strong>".$result->Items->Item->EditorialReviews->EditorialReview[$i]->Source."</strong><br />";
      $comment.=$result->Items->Item->EditorialReviews->EditorialReview[$i]->Content."<br />";
    }
  }
  else 
  {
    $comment .= "<strong>".$result->Items->Item->EditorialReviews->EditorialReview->Source."</strong><br />";
    $comment .= $result->Items->Item->EditorialReviews->EditorialReview->Content;
  }
  $video->comment = $comment;

    //ReleaseDate
  $video->release_date = $result->Items->Item->ItemAttributes->ReleaseDate;

  if ( array_key_exists('Offer', $result->Items->Item->Offers) && array_key_exists('FormattedPrice',  
                     $result->Items->Item->Offers->Offer->OfferListing->Price)) {
        $video->price = substr_replace((string)$result->Items->Item->Offers->Offer->OfferListing->Price->Amount,
            '.',-2,0);
         $video->priceunit = (string)$result->Items->Item->Offers->Offer->OfferListing->Price->CurrencyCode;
         $mas = $video->price;
         $video->price = $mas;
      } else if ( array_key_exists('ListPrice', $result->Items->Item->ItemAttributes) &&       
          array_key_exists('Amount', $result->Items->Item->ItemAttributes->ListPrice)) {

         $video->price = substr_replace((string)$result->Items->Item->ItemAttributes->ListPrice->Amount,'.',-2,0);
         $video->priceunit = (string)$result->Items->Item->ItemAttributes->ListPrice->CurrencyCode;
      }
      else {
        $video->price = "Does not exist anymore!";
      }
    //NumberOfItems
  if ($result->Items->Item->ItemAttributes->NumberOfItems)
  {
    $video->number_of_discs = $result->Items->Item->ItemAttributes->NumberOfItems;
  }

    //RunningTime
  if ($result->Items->Item->ItemAttributes->RunningTime)
  {
    $video->run_time = $result->Items->Item->ItemAttributes->RunningTime->_.' '
        .$result->Items->Item->ItemAttributes->RunningTime->Units;
  }
  
    //Studio
  if ($result->Items->Item->ItemAttributes->Studio)
  {
    $video->studio = $result->Items->Item->ItemAttributes->Studio;
  }

    //producers
  $Producers = '';
  $first = 0;
  if ( array_key_exists('Creator', $result->Items->Item->ItemAttributes ) ) {
    if (IS_ARRAY($result->Items->Item->ItemAttributes->Creator))
    {
      for($i = 0; $i < count ($result->Items->Item->ItemAttributes->Creator);$i++)
      {
        if ($result->Items->Item->ItemAttributes->Creator[$i]->Role=='Producer')
        {
          if (!$first) $first = 1;
          else $Producers.=',';
          $Producers .= $result->Items->Item->ItemAttributes->Creator[$i]->_;
        }
      }
    }
    else if ($result->Items->Item->ItemAttributes->Creator->Role=='Producer')
    {
      $Producers = $result->Items->Item->ItemAttributes->Creator->_;
    }
    if ($Producers != '') $video->producers = $Producers;
  }
    //directors
  $Directors = '';
  if ( array_key_exists('Director', $result->Items->Item->ItemAttributes ) ) 
  {
    if (IS_ARRAY($result->Items->Item->ItemAttributes->Director))
    {
      $Directors = implode(',', $Directors = $result->Items->Item->ItemAttributes->Director);
    }
    else
    {
      $Directors = $result->Items->Item->ItemAttributes->Director;  
    }
  }
  $video->directors = $Directors;

    //format
  if ($result->Items->Item->ItemAttributes->Format)
  {
    $format = '';
    if (is_array($result->Items->Item->ItemAttributes->Format))
    {
      for ($i = 0; $i < count ($result->Items->Item->ItemAttributes->Format); $i++)
      {
        if ($i) {$format.=', ';}
        $format.=$result->Items->Item->ItemAttributes->Format[$i];
      }
    }
    else
    {
      $format = $result->Items->Item->ItemAttributes->Format;
    }
    $video->format = $format;
  }
    //Region code\
  $region = "" ;
  if ($result->Items->Item->ItemAttributes->RegionCode)
  {
    $region = $result->Items->Item->ItemAttributes->RegionCode;
    switch ($region)
    {
    case 0:
      $region.=' ('._REGION0.')';
      break;
    case 1:
      $region.=' ('._REGION1.')';
      break;
    case 2:
      $region.=' ('._REGION2.')';
      break;
    case 3:
      $region.=' ('._REGION3.')';
      break;
    case 4:
      $region.=' ('._REGION4.')';
      break;
    case 5:
      $region.=' ('._REGION5.')';
      break;
    case 6:
      $region.=' ('._REGION6.')';
      break;
    case 8:
      $region.=' ('._REGION8.')';
      break;
    }
  }
  $video->region = $region;
  return $video;
  }


  //***********************   add in function 'games'   *************************

  static function fetchAmazonInfosForGame($media,$game) {
     
  //******************************   Added by OrdaSoft   **************************
      global $medialibrary_configuration,$my,$acl ;
  
//______________________________   Added by OrdaSoft  _____________________________

      $param_ws = mosMedialibraryWS::getWsParamById($media->informationFrom);
      $Timestamp=date("Y-m-d")."T".date("H:i:s")."Z";
      if (($param_ws == "COM") || ($param_ws == "UK") || ($param_ws == "CA")) {
        try{
       if (($param_ws == "UK") || ($param_ws == "CA")) {
          $client = new soapclient(
          "https://webservices.amazon.com/AWSECommerceService/".$param_ws."/AWSECommerceService.wsdl",
           array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
          'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
          'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
          'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
       } else if (($param_ws == "COM")) {
        $client = new soapclient(
          "https://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl",
          array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
          'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
          'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
          'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
              }
      $client->xml_encoding = "UTF-8";
                                $params = array('Request' => array('IdType'=> 'ASIN',
                'ItemId' => $game->asin,
                'ResponseGroup' =>'Large'
                                                            ),
  //old valid        'AWSAccessKeyId' => '1Z21K9KD9G8MAN3VWV82'
          'AWSAccessKeyId' => $medialibrary_configuration['ws']['amazon']['devtag'],
          'AssociateTag' => $medialibrary_configuration['ws']['amazon']['tag'],
          'Timestamp' => $Timestamp,
          'Signature' => "ItemLookup".$Timestamp
                                     );         
                    
             $result = $client->ItemLookup($params);

       } catch (SoapFault $fault) {
      $retVal = "SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})";
      return $retVal;
              trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})",
               E_USER_ERROR);
      }
  }
      //if amazon. UK--yes DE--yes JP--yes(not reviews) FR--yes CA--yes
     else {
        try{
      $client = new soapclient(
      "https://webservices.amazon.com/AWSECommerceService/" . $param_ws . "/AWSECommerceService.wsdl",
      array('proxy_host' => $medialibrary_configuration['proxy_server']['address'],
          'proxy_port' => $medialibrary_configuration['port_proxy_server']['address'],
          'proxy_login'=> $medialibrary_configuration['login_proxy_server']['address'],
          'proxy_password' => $medialibrary_configuration['password_proxy_server']['address']));
      $client->xml_encoding = "UTF-8";
      $params = array(
          'Request' => array(
                'IdType'=> 'ASIN',
                'ItemId' => $game->asin, //'0596005431',
                'ResponseGroup' =>'Large'),//Medium
//old valid        'AWSAccessKeyId' => '1Z21K9KD9G8MAN3VWV82'
          'AWSAccessKeyId' => $medialibrary_configuration['ws']['amazon']['devtag'],
          'AssociateTag' => $medialibrary_configuration['ws']['amazon']['tag'],
          'Timestamp' => $Timestamp,
          'Signature' => "ItemLookup".$Timestamp
          );
      $result = $client->ItemLookup($params);
        }
        catch (SoapFault $fault) {
      $retVal = "SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})";
      return $retVal;
              trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})",
               E_USER_ERROR);
        }

    }

      //Errors test -- 1
      if (array_key_exists('Errors', $result->OperationRequest)) {
  $retVal = "SOAP Fault: (faultcode: {$result->OperationRequest->Errors->Error->Code}, faultstring:   
                    {$result->OperationRequest->Errors->Error->Message})";
         return $retVal;
      }
      

      //Errors test -- 2
      if (array_key_exists('Errors', $result->Items->Request)) {
    $retVal = "SOAP Fault: (faultcode: {$result->Items->Request->Errors->Error->Code}, faultstring:  
                     {$result->Items->Request->Errors->Error->Message})";
    return $retVal;
      }

      if ( array_key_exists('Offer', $result->Items->Item->Offers) && array_key_exists('FormattedPrice',   
                    $result->Items->Item->Offers->Offer->OfferListing->Price)) {
         $game->price = substr_replace((string)$result->Items->Item->Offers->Offer->OfferListing->Price->Amount,
            '.',-2,0);
         $game->priceunit = (string)$result->Items->Item->Offers->Offer->OfferListing->Price->CurrencyCode;
         $mas = $game->price;
         $game->price = $mas;
      } else if ( array_key_exists('ListPrice', $result->Items->Item->ItemAttributes) &&       
          array_key_exists('Amount', $result->Items->Item->ItemAttributes->ListPrice)) {

         $game->price = substr_replace((string)$result->Items->Item->ItemAttributes->ListPrice->Amount,'.',-2,0);
         $game->priceunit = (string)$result->Items->Item->ItemAttributes->ListPrice->CurrencyCode;
      }
      else {
        $game->price = "Does not exist anymore!";
      }

    //Rating
  if ($result->Items->Item->CustomerReviews->AverageRating)
  {
    $game->rating = ($result->Items->Item->CustomerReviews->AverageRating * 2);
  }
      //ProductName
      $game->title = $result->Items->Item->ItemAttributes->Title;

      //ImageUrlMedium
      $game->imageURL = $result->Items->Item->MediumImage->URL;

      //URL
      $game->URL = $result->Items->Item->DetailPageURL;

    //comment
  $comment = "";
  if(($medialibrary_configuration['merge_description']['use'])){
    if (checkAccess_ML( $medialibrary_configuration['merge_description']['registrationlevel'],'RECURSE', 
        userGID_ML($my->id), $acl)) {
            $comment = $game->comment . "<br /><p></p> ";
    } else $comment = "";
  } else $comment = "";
  
  if(IS_ARRAY($result->Items->Item->EditorialReviews->EditorialReview))
  {
    for ($i = 0; $i < count($result->Items->Item->EditorialReviews->EditorialReview); $i++)
    {
      $comment.="<strong>".$result->Items->Item->EditorialReviews->EditorialReview[$i]->Source."</strong><br />";
      $comment.=$result->Items->Item->EditorialReviews->EditorialReview[$i]->Content."<br />";
    }
  }
  else 
  {
    $comment .= "<strong>".$result->Items->Item->EditorialReviews->EditorialReview->Source."</strong><br />";
    $comment .= $result->Items->Item->EditorialReviews->EditorialReview->Content;
  }
  $game->comment = $comment;

    //ReleaseDate
  $game->release_date = $result->Items->Item->ItemAttributes->ReleaseDate;

    //studio
  $game->studio = $result->Items->Item->ItemAttributes->Studio;
  
    //binding
  $game->binding = $result->Items->Item->ItemAttributes->Binding;

      //Platform
  $Platform = '';
  if (IS_ARRAY($result->Items->Item->ItemAttributes->Platform))
  {
    $Platform = implode(', ', $result->Items->Item->ItemAttributes->Platform);
  }
  else if ($result->Items->Item->ItemAttributes->Platform)
  {
    $Platform = $result->Items->Item->ItemAttributes->Platform;
  }
  $game->platform = $Platform;
  return $game;
  }




//***********************   add in function 'books'   *************************

 static function fetchAmazonInfosForBookRest($media,$book,$version = '2011-08-01') {
      global $medialibrary_configuration,$my,$acl;


//******************************   Added by OrdaSoft   **********************************
      
    $param_ws = mosMedialibraryWS::getWsParamById($media->informationFrom);
    $endpoint = "";
    if ($param_ws == "COM") $endpoint ="http://ecs.amazonaws.com/onca/xml";
    else if ($param_ws == "UK") $endpoint = "http://ecs.amazonaws.co.uk/onca/xml";
    else if ($param_ws == "CA") $endpoint = "http://ecs.amazonaws.ca/onca/xml";
    else if ($param_ws == "DE") $endpoint = "http://ecs.amazonaws.de/onca/xml";
    else if ($param_ws == "JP") $endpoint = "http://ecs.amazonaws.jp/onca/xml";
    else if ($param_ws == "FR") $endpoint = "http://ecs.amazonaws.fr/onca/xml";
    else if ($param_ws == "ES") $endpoint = "http://webservices.amazon.es/onca/xml";
    else if ($param_ws == "IT") $endpoint = "http://webservices.amazon.it/onca/xml";
    else if ($param_ws == "CN") $endpoint = "http://webservices.amazon.cn/onca/xml";
    else if ($param_ws == "US") $endpoint = "http://webservices.amazon.com/onca/xml";

    // if($medialibrary_configuration['ws']['amazon']['secret_key'] == "")
    //   $secret_key = "ooTVCJy06UNXeMujmlyso9Wj4VD1flgEPsCx5HYY"; 
    // else 
    $secret_key = $medialibrary_configuration['ws']['amazon']['secret_key']; 
    
    $request = "$endpoint?" .
          "Service=AWSECommerceService" . 
          "&Operation=ItemLookup" . 
          "&Condition=All" . 
          "&Version={$version}" . 
          "&AWSAccessKeyId=" . $medialibrary_configuration['ws']['amazon']['devtag'] .
          "&AssociateTag=" . $medialibrary_configuration['ws']['amazon']['tag'] . 
          "&SearchIndex=Books" . //add for isbn-13
          "&ResponseGroup=Large" .
          "&IdType=ISBN" . //ISBN - for isbn-13  'ASIN' - for isbn-10
          "&ItemId=$book->isbn";

    // Get a nice array of elements to work with
    $uri_elements = parse_url($request);

    // Grab our request elements
    $request = $uri_elements['query'];
 
    // Throw them into an array
    parse_str($request, $parameters);
 
    // Add the new required paramters
    $parameters['Timestamp'] = gmdate("Y-m-d\TH:i:s\Z");
    $parameters['Version'] = $version;
 
    // The new authentication requirements need the keys to be sorted
    ksort($parameters);
 
    // Create our new request
    foreach ($parameters as $parameter => $value) {
        // We need to be sure we properly encode the value of our parameter
        $parameter = str_replace("%7E", "~", rawurlencode($parameter));
        $value = str_replace("%7E", "~", rawurlencode($value));
        $request_array[] = $parameter . '=' . $value;
    }   
 
    // Put our & symbol at the beginning of each of our request variables and put it in a string
    $new_request = implode('&', $request_array);
 
    // Create our signature string
    $signature_string = "GET\n{$uri_elements['host']}\n{$uri_elements['path']}\n{$new_request}";
 
    // Create our signature using hash_hmac
    if (function_exists("hash_hmac")){
      $signature = urlencode(base64_encode(hash_hmac('sha256', $signature_string, $secret_key, true)));
    }
    elseif(function_exists("mhash")){
      $signature = urlencode(base64_encode(mhash(MHASH_SHA256, $signature_string, $secret_key)));
    }
    else{
      return "No hash function available!";
    }    // new request

    // new request
    $request =  "http://{$uri_elements['host']}{$uri_elements['path']}?{$new_request}&Signature={$signature}";

    // Load the call and capture the document returned by the Shopping API
    $ch = curl_init();

    // set URL and other appropriate options
    curl_setopt($ch, CURLOPT_URL, $request);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT,
         'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');

    // grab URL and pass it to the browser
    $result = curl_exec($ch);

    // close cURL resource, and free up system resources
    curl_close($ch);

    $result = simplexml_load_string($result);
    if (array_key_exists('Errors', $result)) { 
            echo "<script> alert('Sorry, ".$result->Items->Request->Errors->Error->Message." '); window.history.go(-1);
                  </script>\n";
            exit;
        }

    if (array_key_exists('Error', $result)) { 
            echo "<script> alert('Sorry, ".$result->Error->Message." '); window.history.go(-1);
                  </script>\n";
            exit;
    }
    //Errors test -- 1
    if (array_key_exists('Errors', $result->OperationRequest)) {
        $retVal = "faultcode: {$result->OperationRequest->Errors->Error->Code}, faultstring:  
                     {$result->OperationRequest->Errors->Error->Message}";
        return $retVal;
    }

    //Errors test -- 2
    if (array_key_exists('Errors', $result->Items->Request)) {
      $retVal = "faultcode: {$result->Items->Request->Errors->Error->Code}, "
                ."faultstring: {$result->Items->Request->Errors->Error->Message}";
      return $retVal;
    }

    //Body -- Output in joomla form
    //ProductName
    $book->title = (string)$result->Items->Item->ItemAttributes->Title;

    //ImageUrlMedium
    $book->imageURL = (string)$result->Items->Item->MediumImage->URL;

    //URL
    $book->URL = (string)$result->Items->Item->DetailPageURL;

    //Number Of Pages
    $book->numberOfPages = (int)$result->Items->Item->ItemAttributes->NumberOfPages;
    
    //Manufacturer
    if (array_key_exists('Manufacturer', $result->Items->Item->ItemAttributes)) {
       $book->manufacturer = (string)$result->Items->Item->ItemAttributes->Manufacturer;
    }

      
    //Author
    $book->authors = array();
    foreach($result->Items->Item->ItemAttributes->Author as $item){
        if(isset($item)){
          $book->authors[]= (string)$item;
        }
    }
     //Rating
     if (array_key_exists('CustomerReviews', $result->Items->Item)) {
        $book->rating = (string)($result->Items->Item->CustomerReviews->AverageRating * 2);
     }

    //PublicationDate
    if (array_key_exists('PublicationDate', $result->Items->Item->ItemAttributes)) {
       $book->release_date = (string)$result->Items->Item->ItemAttributes->PublicationDate;
    }

    //ReleaseDate
    if (array_key_exists('ReleaseDate', $result->Items->Item->ItemAttributes)) {
       $book->release_date = (string)$result->Items->Item->ItemAttributes->ReleaseDate;
    }

    //Edition
    if ( array_key_exists('Edition', $result->Items->Item->ItemAttributes) ) {
       $book->edition = (string)$result->Items->Item->ItemAttributes->Edition;
    }

//Price no partner
    if ( array_key_exists('Offer', $result->Items->Item->Offers) && array_key_exists('FormattedPrice',   
                    $result->Items->Item->Offers->Offer->OfferListing->Price)) {
       $book->price = substr_replace((string)$result->Items->Item->Offers->Offer->OfferListing->Price->Amount,
            '.',-2,0);
       $book->priceunit = (string)$result->Items->Item->Offers->Offer->OfferListing->Price->CurrencyCode;
       $mas = $book->price;
       $book->price = $mas;
    }
    else {
      $book->price = "Does not exist anymore!";
    }

//************************   begin add for Book Description   *********************
    if(($medialibrary_configuration['merge_description']['use'])){
      if (checkAccess_ML( $medialibrary_configuration['merge_description']['registrationlevel'],'RECURSE', 
            userGID_ML($my->id), $acl)) {
              $book->comment = $book->comment . "<br /><p></p> ";
      } else $book->comment = "";
    } else $book->comment = "";        
    if( array_key_exists('EditorialReviews', $result->Items->Item ) && array_key_exists('EditorialReview',  
                     $result->Items->Item->EditorialReviews ) ) {
      foreach($result->Items->Item->EditorialReviews->EditorialReview as $item){
          $book->comment .= "<strong>".$item->Source ."</strong><br />";
          $book->comment .= $item->Content."<br />";
     }
    }
//************************   end add for Book Description   ************************
      return $book;
  }

//****************************   End of Added by Orda   *****************************



//***********************   add in function 'music'   *************************

 static function fetchAmazonInfosForMusicRest($media,$music,$version = '2011-08-01') {
//******************************   Added by OrdaSoft   **********************************
      global $medialibrary_configuration,$my,$acl ;
  
//______________________________   Added by OrdaSoft  _____________________________
      $param_ws=mosMedialibraryWS ::getWsParamById($media->informationFrom);

    if ($param_ws == "COM") $endpoint ="http://ecs.amazonaws.com/onca/xml";
    else if ($param_ws == "UK") $endpoint = "http://ecs.amazonaws.co.uk/onca/xml";
    else if ($param_ws == "CA") $endpoint = "http://ecs.amazonaws.ca/onca/xml";
    else if ($param_ws == "DE") $endpoint = "http://ecs.amazonaws.de/onca/xml";
    else if ($param_ws == "JP") $endpoint = "http://ecs.amazonaws.jp/onca/xml";
    else if ($param_ws == "FR") $endpoint = "http://ecs.amazonaws.fr/onca/xml";
    else if ($param_ws == "ES") $endpoint = "http://webservices.amazon.es/onca/xml";
    else if ($param_ws == "IT") $endpoint = "http://webservices.amazon.it/onca/xml";
    else if ($param_ws == "CN") $endpoint = "http://webservices.amazon.cn/onca/xml";
    else if ($param_ws == "US") $endpoint = "http://webservices.amazon.com/onca/xml";

    // if($medialibrary_configuration['ws']['amazon']['secret_key'] == "")
    //   $secret_key = "ooTVCJy06UNXeMujmlyso9Wj4VD1flgEPsCx5HYY"; 
    // else 
      $secret_key = $medialibrary_configuration['ws']['amazon']['secret_key']; 
    
    $request = "$endpoint?" .
          "Service=AWSECommerceService" . 
          "&Operation=ItemLookup" . 
          "&Condition=All" . 
          "&Version={$version}" . 
          "&AWSAccessKeyId=" . $medialibrary_configuration['ws']['amazon']['devtag'] .
          "&AssociateTag=" . $medialibrary_configuration['ws']['amazon']['tag'] . 
          "&ResponseGroup=Large" .
          "&IdType=ASIN" . //ISBN - for isbn-13  'ASIN' - for isbn-10
          "&ItemId=$music->asin";

    // Get a nice array of elements to work with
    $uri_elements = parse_url($request);

    // Grab our request elements
    $request = $uri_elements['query'];
 
    // Throw them into an array
    parse_str($request, $parameters);
 
    // Add the new required paramters
    $parameters['Timestamp'] = gmdate("Y-m-d\TH:i:s\Z");
    $parameters['Version'] = $version;
 
    // The new authentication requirements need the keys to be sorted
    ksort($parameters);
 
    // Create our new request
    foreach ($parameters as $parameter => $value) {
        // We need to be sure we properly encode the value of our parameter
        $parameter = str_replace("%7E", "~", rawurlencode($parameter));
        $value = str_replace("%7E", "~", rawurlencode($value));
        $request_array[] = $parameter . '=' . $value;
    }   
 
    // Put our & symbol at the beginning of each of our request variables and put it in a string
    $new_request = implode('&', $request_array);
 
    // Create our signature string
    $signature_string = "GET\n{$uri_elements['host']}\n{$uri_elements['path']}\n{$new_request}";
 
    // Create our signature using hash_hmac
    if (function_exists("hash_hmac")){
      $signature = urlencode(base64_encode(hash_hmac('sha256', $signature_string, $secret_key, true)));
    }
    elseif(function_exists("mhash")){
      $signature = urlencode(base64_encode(mhash(MHASH_SHA256, $signature_string, $secret_key)));
    }
    else{
      return "No hash function available!";
    }    // new request

     // new request
    $request =  "http://{$uri_elements['host']}{$uri_elements['path']}?{$new_request}&Signature={$signature}";

    // Load the call and capture the document returned by the Shopping API
    //$result = simplexml_load_file($request);
    
        $ch = curl_init();

      // set URL and other appropriate options
      curl_setopt($ch, CURLOPT_URL, $request);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_USERAGENT, 
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');

      // grab URL and pass it to the browser
      $result = curl_exec($ch);

      // close cURL resource, and free up system resources
      curl_close($ch);

      $result = simplexml_load_string($result);
    
    if (array_key_exists('Errors', $result)) { 
            echo "<script> alert('Sorry, ".$result->Items->Request->Errors->Error->Message." '); window.history.go(-1);
                  </script>\n";
            exit;
        }

    if (array_key_exists('Error', $result)) { 
            echo "<script> alert('Sorry, ".$result->Error->Message." '); window.history.go(-1);
                  </script>\n";
            exit;
    }
    //Errors test -- 1
    if (array_key_exists('Errors', $result->OperationRequest)) {
        $retVal = "faultcode: {$result->OperationRequest->Errors->Error->Code}, faultstring:   
                    {$result->OperationRequest->Errors->Error->Message}";
        return $retVal;
    }

    //Errors test -- 2
    if (array_key_exists('Errors', $result->Items->Request)) {
      $retVal = "faultcode: {$result->Items->Request->Errors->Error->Code}, "
        ."faultstring: {$result->Items->Request->Errors->Error->Message}";
      return $retVal;
    }

//      get tracks
/*($result->Items->Item->Tracks->Disc)*/
      $i = 0;  
      $music->tracklist = "";
      foreach($result as $item){
          $music->tracklist .= "CD".($i+1).': ';
          $j = 0;  
          foreach($item->Track as $track){
              if ($j > 0) $music->tracklist.=', ';
              $music->tracklist .= $track ;
              $j++;
          }
          $i++;
          $music->tracklist .= '; ';
      }

      //Price no partner
      if ( array_key_exists('Offer', $result->Items->Item->Offers) && array_key_exists('FormattedPrice',   
                    $result->Items->Item->Offers->Offer->OfferListing->Price)) {
         $music->price = substr_replace((string)$result->Items->Item->Offers->Offer->OfferListing->Price->Amount,
                '.',-2,0);
         $music->priceunit = (string)$result->Items->Item->Offers->Offer->OfferListing->Price->CurrencyCode;
         $mas = $music->price;
         $music->price = $mas;
      } else if ( array_key_exists('ListPrice', $result->Items->Item->ItemAttributes) &&       
          array_key_exists('Amount', $result->Items->Item->ItemAttributes->ListPrice)) {

         $music->price = substr_replace((string)$result->Items->Item->ItemAttributes->ListPrice->Amount,'.',-2,0);
         $music->priceunit = (string)$result->Items->Item->ItemAttributes->ListPrice->CurrencyCode;
      }
      else {
        $music->price = "Does not exist anymore!";
      }
    //Rating
    if (array_key_exists('CustomerReviews', $result->Items->Item)) {
      $music->rating = (string)($result->Items->Item->CustomerReviews->AverageRating * 2);
    }
    //datetime
    //ReleaseDate
    if (array_key_exists('ReleaseDate', $result->Items->Item->ItemAttributes)) {
      $music->release_date = (string)$result->Items->Item->ItemAttributes->ReleaseDate;
    }
    //binding
    $music->binding = (string)$result->Items->Item->ItemAttributes->Binding;
    //ImageUrlMedium
    $music->imageURL = (string)$result->Items->Item->MediumImage->URL;
    //URL
    $music->URL = (string)$result->Items->Item->DetailPageURL;
      //add artisi
    $music->artist = (string)$result->Items->Item->ItemAttributes->Artist;
    if(!$music->artist) $music->artist = (string)$result->Items->Item->ItemAttributes->Creator;
      //add title
    $music->title = (string)$result->Items->Item->ItemAttributes->Title;
      //add  number_of_discs
    $music->number_of_discs = (string)$result->Items->Item->ItemAttributes->NumberOfDiscs;
      //add label
    $music->label = (string)$result->Items->Item->ItemAttributes->Label;
      //Rating
    if (array_key_exists('CustomerReviews', $result->Items->Item)) {
      $music->rating = (string)($result->Items->Item->CustomerReviews->AverageRating * 2);
    }
//************************   begin add for music Description   *********************
  //comments
      if(($medialibrary_configuration['merge_description']['use'])){
        if (checkAccess_ML( $medialibrary_configuration['merge_description']['registrationlevel'],'RECURSE',   
                    userGID_ML($my->id), $acl)) {
                $music->comment = $music->comment . "<br /><p></p> ";
        } else $music->comment = "";
      } else $music->comment = "";  
      if( array_key_exists('EditorialReviews', $result->Items->Item ) && array_key_exists('EditorialReview',  
                     $result->Items->Item->EditorialReviews ) ) {
        foreach($result->Items->Item->EditorialReviews->EditorialReview as $item){
            $music->comment .= "<strong>".$item->Source ."</strong><br />";
            $music->comment .= $item->Content."<br />";
        }
      }
  
//***************************** end add description  ***************************

    return $music;
  }



//***********************   add in function 'video'   *************************

 static function fetchAmazonInfosForVideoRest($media,$video,$version = '2011-08-01') {
     
//******************************   Added by OrdaSoft   **************************
      global $medialibrary_configuration,$my,$acl ;
  
//______________________________   Added by OrdaSoft  _____________________________
    $param_ws=mosMedialibraryWS::getWsParamById($media->informationFrom);

    if ($param_ws == "COM") $endpoint ="http://ecs.amazonaws.com/onca/xml";
    else if ($param_ws == "UK") $endpoint = "http://ecs.amazonaws.co.uk/onca/xml";
    else if ($param_ws == "CA") $endpoint = "http://ecs.amazonaws.ca/onca/xml";
    else if ($param_ws == "DE") $endpoint = "http://ecs.amazonaws.de/onca/xml";
    else if ($param_ws == "JP") $endpoint = "http://ecs.amazonaws.jp/onca/xml";
    else if ($param_ws == "FR") $endpoint = "http://ecs.amazonaws.fr/onca/xml";
    else if ($param_ws == "ES") $endpoint = "http://webservices.amazon.es/onca/xml";
    else if ($param_ws == "IT") $endpoint = "http://webservices.amazon.it/onca/xml";
    else if ($param_ws == "CN") $endpoint = "http://webservices.amazon.cn/onca/xml";
    else if ($param_ws == "US") $endpoint = "http://webservices.amazon.com/onca/xml";
    // if($medialibrary_configuration['ws']['amazon']['secret_key'] == "")
    //   $secret_key = "ooTVCJy06UNXeMujmlyso9Wj4VD1flgEPsCx5HYY"; 
    // else 
      $secret_key = $medialibrary_configuration['ws']['amazon']['secret_key']; 
    
    $request = "$endpoint?" .
          "Service=AWSECommerceService" . 
          "&Operation=ItemLookup" . 
          "&Condition=All" . 
          "&Version={$version}" . 
          "&AWSAccessKeyId=" . $medialibrary_configuration['ws']['amazon']['devtag'] .
          "&AssociateTag=" . $medialibrary_configuration['ws']['amazon']['tag'] . 
          "&ResponseGroup=Large" .
          "&IdType=ASIN" . //ISBN - for isbn-13  'ASIN' - for isbn-10
          "&ItemId=$video->asin";

    // Get a nice array of elements to work with
    $uri_elements = parse_url($request);

    // Grab our request elements
    $request = $uri_elements['query'];
 
    // Throw them into an array
    parse_str($request, $parameters);
 
    // Add the new required paramters
    $parameters['Timestamp'] = gmdate("Y-m-d\TH:i:s\Z");
    $parameters['Version'] = $version;
 
    // The new authentication requirements need the keys to be sorted
    ksort($parameters);
 
    // Create our new request
    foreach ($parameters as $parameter => $value) {
        // We need to be sure we properly encode the value of our parameter
        $parameter = str_replace("%7E", "~", rawurlencode($parameter));
        $value = str_replace("%7E", "~", rawurlencode($value));
        $request_array[] = $parameter . '=' . $value;
    }   
 
    // Put our & symbol at the beginning of each of our request variables and put it in a string
    $new_request = implode('&', $request_array);
 
    // Create our signature string
    $signature_string = "GET\n{$uri_elements['host']}\n{$uri_elements['path']}\n{$new_request}";
 
    // Create our signature using hash_hmac
    
    if(function_exists("hash_hmac")){
      $signature = urlencode(base64_encode(hash_hmac('sha256', $signature_string, $secret_key, true)));
    }
    elseif(function_exists("mhash")){
      $signature = urlencode(base64_encode(mhash(MHASH_SHA256, $signature_string, $secret_key)));

    }
    else{
      return "No hash function available!";
    }    // new request

    // new request
    $request =  "http://{$uri_elements['host']}{$uri_elements['path']}?{$new_request}&Signature={$signature}";

    // Load the call and capture the document returned by the Shopping API
        $ch = curl_init();

      // set URL and other appropriate options
      curl_setopt($ch, CURLOPT_URL, $request);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_USERAGENT, 
            'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');

      // grab URL and pass it to the browser
      $result = curl_exec($ch);

      // close cURL resource, and free up system resources
      curl_close($ch);

      $result = simplexml_load_string($result);
      //print_r($result);       print_r(":1111111111:");       exit;
      
    if (array_key_exists('Errors', $result)) { 
            echo "<script> alert('Sorry, ".$result->Items->Request->Errors->Error->Message." '); window.history.go(-1);
                  </script>\n";
            exit;
        }

    if (array_key_exists('Error', $result)) { 
            echo "<script> alert('Sorry, ".$result->Error->Message." '); window.history.go(-1);
                  </script>\n";
            exit;
    }
    //Errors test -- 1
    if (array_key_exists('Errors', $result->OperationRequest)) {
        $retVal = "faultcode: {$result->OperationRequest->Errors->Error->Code}, faultstring:   
                    {$result->OperationRequest->Errors->Error->Message}";
        return $retVal;
    }

    //Errors test -- 2
    if (array_key_exists('Errors', $result->Items->Request)) {
      $retVal = "faultcode: {$result->Items->Request->Errors->Error->Code},"
        ." faultstring: {$result->Items->Request->Errors->Error->Message}";
      return $retVal;
    }

      //Title
    $video->title = (string)$result->Items->Item->ItemAttributes->Title;
  
  
      //imageURL
    $video->imageURL = (string)$result->Items->Item->MediumImage->URL;
  
      //URL
    $video->URL = (string)$result->Items->Item->DetailPageURL;
  
      //Rating
    $video->rating = (string)($result->Items->Item->CustomerReviews->AverageRating * 2);
  
    //Actors
    $i = 0;  
    $video->actors = "";
    foreach($result->Items->Item->ItemAttributes->Actor as $item){
        if ($i > 0) $video->actors.=',';
        $video->actors .= $item ;
        $i++;
    }


    //comments
    if(($medialibrary_configuration['merge_description']['use'])){
        if (checkAccess_ML( $medialibrary_configuration['merge_description']['registrationlevel'],'RECURSE',
         userGID_ML($my->id), $acl)){
            $video->comment = $video->comment . "<br /><p></p> ";
        } else{
            $video->comment = "";
        }
    } else{
        $video->comment = "";
    }

    if( array_key_exists('EditorialReviews', $result->Items->Item ) && array_key_exists('EditorialReview',   
                    $result->Items->Item->EditorialReviews ) ){
        foreach($result->Items->Item->EditorialReviews->EditorialReview as $item){
            $video->comment .= "<strong>".$item->Source ."</strong><br />";
            $video->comment .= $item->Content."<br />";
        }
    }

      //ReleaseDate
    $video->release_date = (string)$result->Items->Item->ItemAttributes->ReleaseDate;

    if ( array_key_exists('Offer', $result->Items->Item->Offers) && array_key_exists('FormattedPrice',   
                    $result->Items->Item->Offers->Offer->OfferListing->Price)) {
         $video->price = substr_replace((string)$result->Items->Item->Offers->Offer->OfferListing->Price->Amount,
            '.',-2,0);
         $video->priceunit = (string)$result->Items->Item->Offers->Offer->OfferListing->Price->CurrencyCode;
         $mas = $video->price;
         $video->price = $mas;
      } else if ( array_key_exists('ListPrice', $result->Items->Item->ItemAttributes) &&       
          array_key_exists('Amount', $result->Items->Item->ItemAttributes->ListPrice)) {

         $video->price = substr_replace((string)$result->Items->Item->ItemAttributes->ListPrice->Amount,'.',-2,0);
         $video->priceunit = (string)$result->Items->Item->ItemAttributes->ListPrice->CurrencyCode;
      }
      else {
        $video->price = "Does not exist anymore!";
      }
      //NumberOfItems
    if ($result->Items->Item->ItemAttributes->NumberOfItems)
    {
      $video->number_of_discs = (string)$result->Items->Item->ItemAttributes->NumberOfItems;
    }
  
      //RunningTime
    if ($result->Items->Item->ItemAttributes->RunningTime)
    {
      $video->run_time = (string)$result->Items->Item->ItemAttributes->RunningTime;
    }
    
      //Studio
    if ($result->Items->Item->ItemAttributes->Studio)
    {
      $video->studio = (string)$result->Items->Item->ItemAttributes->Studio;
    }

      //producers
    //$Producers = '';
    //$first = 0;
    //if ( array_key_exists('Creator', $result->Items->Item->ItemAttributes ) ) {
      //if (IS_ARRAY($result->Items->Item->ItemAttributes->Creator))
      //{
        //for($i = 0; $i < count ($result->Items->Item->ItemAttributes->Creator);$i++)
        //{
          //if ( (string)$result->Items->Item->ItemAttributes->Creator[$i]->Role=='Producer')
          //{
            //if (!$first) $first = 1;
            //else $Producers.=', ';
            //$Producers .= (string)$result->Items->Item->ItemAttributes->Creator[$i];
          //}
        //}
      //}
      //else if ($result->Items->Item->ItemAttributes->Creator->Role=='Producer')
      //{
        //$Producers = (string)$result->Items->Item->ItemAttributes->Creator;
      //}
      //if ($Producers != '') $video->producers = $Producers;
    //}
    $i = 0;  
    $video->producers = "";
    foreach($result->Items->Item->ItemAttributes->Creator as $item){
        if ($i > 0) $video->producers.=',';
        $video->producers .= $item ;
        $i++;
    }
    
      //print_r($result->Items->Item->ItemAttributes);       print_r(":1111111111:");       exit;
      //directors
    $i = 0;  
    $video->directors = "";
    foreach($result->Items->Item->ItemAttributes->Director as $item){
        if ($i > 0) $video->directors.=',';
        $video->directors .= $item ;
        $i++;
    }

      //format
    $i = 0;  
    $video->format = "";
    foreach($result->Items->Item->ItemAttributes->Format as $item){
        if ($i > 0) $video->format.=', ';
        $video->format .= $item ;
        $i++;
    }
  
      //Region code\
    $region = "";  
    if ($result->Items->Item->ItemAttributes->RegionCode)
    {
      $region = (string)$result->Items->Item->ItemAttributes->RegionCode;
      switch ($region)
      {
      case 0:
        $region.=' ('._MEDIALIBRARY_REGION0.')';
        break;
      case 1:
        $region.=' ('._MEDIALIBRARY_REGION1.')';
        break;
      case 2:
        $region.=' ('._MEDIALIBRARY_REGION2.')';
        break;
      case 3:
        $region.=' ('._MEDIALIBRARY_REGION3.')';
        break;
      case 4:
        $region.=' ('._MEDIALIBRARY_REGION4.')';
        break;
      case 5:
        $region.=' ('._MEDIALIBRARY_REGION5.')';
        break;
      case 6:
        $region.=' ('._MEDIALIBRARY_REGION6.')';
        break;
      case 8:
        $region.=' ('._MEDIALIBRARY_REGION8.')';
        break;
      }
    }
    $video->region = $region;
  
  
    return $video;
  }


  //***********************   add in function 'games'   *************************

 static function fetchAmazonInfosForGameRest($media,$game,$version = '2011-08-01') {
     
  //******************************   Added by OrdaSoft   **************************
      global $medialibrary_configuration,$my,$acl ;

//______________________________   Added by OrdaSoft  _____________________________

      $param_ws = mosMedialibraryWS::getWsParamById($media->informationFrom);

    if ($param_ws == "COM") $endpoint ="http://ecs.amazonaws.com/onca/xml";
    else if ($param_ws == "UK") $endpoint = "http://ecs.amazonaws.co.uk/onca/xml";
    else if ($param_ws == "CA") $endpoint = "http://ecs.amazonaws.ca/onca/xml";
    else if ($param_ws == "DE") $endpoint = "http://ecs.amazonaws.de/onca/xml";
    else if ($param_ws == "JP") $endpoint = "http://ecs.amazonaws.jp/onca/xml";
    else if ($param_ws == "FR") $endpoint = "http://ecs.amazonaws.fr/onca/xml";
    else if ($param_ws == "ES") $endpoint = "http://webservices.amazon.es/onca/xml";
    else if ($param_ws == "IT") $endpoint = "http://webservices.amazon.it/onca/xml";
    else if ($param_ws == "CN") $endpoint = "http://webservices.amazon.cn/onca/xml";
    else if ($param_ws == "US") $endpoint = "http://webservices.amazon.com/onca/xml";

    // if($medialibrary_configuration['ws']['amazon']['secret_key'] == "")
    //   $secret_key = "ooTVCJy06UNXeMujmlyso9Wj4VD1flgEPsCx5HYY"; 
    // else 
      $secret_key = $medialibrary_configuration['ws']['amazon']['secret_key']; 
    
    $request = "$endpoint?" .
          "Service=AWSECommerceService" . 
          "&Operation=ItemLookup" . 
          "&Condition=All" . 
          "&Version={$version}" . 
          "&AWSAccessKeyId=" . $medialibrary_configuration['ws']['amazon']['devtag'] .
          "&AssociateTag=" . $medialibrary_configuration['ws']['amazon']['tag'] . 
          "&ResponseGroup=Large" .
          "&IdType=ASIN" . //ISBN - for isbn-13  'ASIN' - for isbn-10
          "&ItemId=$game->asin";

    // Get a nice array of elements to work with
    $uri_elements = parse_url($request);

    // Grab our request elements
    $request = $uri_elements['query'];
 
    // Throw them into an array
    parse_str($request, $parameters);
 
    // Add the new required paramters
    $parameters['Timestamp'] = gmdate("Y-m-d\TH:i:s\Z");
    $parameters['Version'] = $version;
 
    // The new authentication requirements need the keys to be sorted
    ksort($parameters);
 
    // Create our new request
    foreach ($parameters as $parameter => $value) {
        // We need to be sure we properly encode the value of our parameter
        $parameter = str_replace("%7E", "~", rawurlencode($parameter));
        $value = str_replace("%7E", "~", rawurlencode($value));
        $request_array[] = $parameter . '=' . $value;
    }   
 
    // Put our & symbol at the beginning of each of our request variables and put it in a string
    $new_request = implode('&', $request_array);
 
    // Create our signature string
    $signature_string = "GET\n{$uri_elements['host']}\n{$uri_elements['path']}\n{$new_request}";
 
    // Create our signature using hash_hmac
   
    if (function_exists("hash_hmac")){
      $signature = urlencode(base64_encode(hash_hmac('sha256', $signature_string, $secret_key, true)));
    }
    elseif(function_exists("mhash")){
      $signature = urlencode(base64_encode(mhash(MHASH_SHA256, $signature_string, $secret_key)));
    }
    else{
      return "No hash function available!";
    }    // new request

 // new request
    $request =  "http://{$uri_elements['host']}{$uri_elements['path']}?{$new_request}&Signature={$signature}";

    // Load the call and capture the document returned by the Shopping API
        $ch = curl_init();

      // set URL and other appropriate options
      curl_setopt($ch, CURLOPT_URL, $request);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_USERAGENT, 
        'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');

      // grab URL and pass it to the browser
      $result = curl_exec($ch);

      // close cURL resource, and free up system resources
      curl_close($ch);

      $result = simplexml_load_string($result);

    if (array_key_exists('Errors', $result)) { 
            echo "<script> alert('Sorry, ".$result->Items->Request->Errors->Error->Message." '); window.history.go(-1);
                  </script>\n";
            exit;
        }

    if (array_key_exists('Error', $result)) { 
            echo "<script> alert('Sorry, ".$result->Error->Message." '); window.history.go(-1);
                  </script>\n";
            exit;
    }
    //Errors test -- 1
    if (array_key_exists('Errors', $result->OperationRequest)) {
        $retVal = "faultcode: {$result->OperationRequest->Errors->Error->Code}, faultstring:  
                     {$result->OperationRequest->Errors->Error->Message}";
        return $retVal;
    }

    //Errors test -- 2
    if (array_key_exists('Errors', $result->Items->Request)) {
      $retVal = "faultcode: {$result->Items->Request->Errors->Error->Code}, "
        ."faultstring: {$result->Items->Request->Errors->Error->Message}";
      return $retVal;
    }

      //Price no partner
      if ( array_key_exists('Offer', $result->Items->Item->Offers) && array_key_exists('FormattedPrice',  
                     $result->Items->Item->Offers->Offer->OfferListing->Price)) {
         $game->price = substr_replace((string)$result->Items->Item->Offers->Offer->OfferListing->Price->Amount,'.',-2,0);
         $game->priceunit = (string)$result->Items->Item->Offers->Offer->OfferListing->Price->CurrencyCode;
         $mas = $game->price;
         $game->price = $mas;
      } else if ( array_key_exists('ListPrice', $result->Items->Item->ItemAttributes) &&       
          array_key_exists('Amount', $result->Items->Item->ItemAttributes->ListPrice)) {

         $game->price = substr_replace((string)$result->Items->Item->ItemAttributes->ListPrice->Amount,'.',-2,0);
         $game->priceunit = (string)$result->Items->Item->ItemAttributes->ListPrice->CurrencyCode;
      }
      else {
        $game->price = "Does not exist anymore!";
      }

        //Rating
      if ($result->Items->Item->CustomerReviews->AverageRating)
      {
        $game->rating = (string)($result->Items->Item->CustomerReviews->AverageRating * 2);
      }

      //ProductName
      $game->title = (string)$result->Items->Item->ItemAttributes->Title;

      //ImageUrlMedium
      $game->imageURL = (string)$result->Items->Item->MediumImage->URL;

      //URL
      $game->URL = (string)$result->Items->Item->DetailPageURL;

        //comment
      if(($medialibrary_configuration['merge_description']['use'])){
        if (checkAccess_ML( $medialibrary_configuration['merge_description']['registrationlevel'],'RECURSE',  
                     userGID_ML($my->id), $acl)) {
                $game->comment = $game->comment . "<br /><p></p> ";
        } else $game->comment = "";
      } else $game->comment = "";        
      if( array_key_exists('EditorialReviews', $result->Items->Item ) && array_key_exists('EditorialReview',  
                     $result->Items->Item->EditorialReviews ) ) {
        foreach($result->Items->Item->EditorialReviews->EditorialReview as $item){
            $game->comment .= "<strong>".$item->Source ."</strong><br />";
            $game->comment .= $item->Content."<br />";
        }
      }

        //ReleaseDate
      $game->release_date = (string)$result->Items->Item->ItemAttributes->ReleaseDate;
    
        //studio
      $game->studio = (string)$result->Items->Item->ItemAttributes->Studio;
      
        //binding
      $game->binding = (string)$result->Items->Item->ItemAttributes->Binding;
    
          //Platform
      $i = 0;  
      $game->platform = "";
      foreach($result->Items->Item->ItemAttributes->Platform as $item){
          if ($i > 0) $game->platform.=', ';
          $game->platform .= $item ;
          $i++;
      }


    return $game;
  }




  static function fetchAmazonInfosBookPaapi5($media,$book) {
        global $medialibrary_configuration, $my, $acl;
        //******************************   Added by OrdaSoft   **********************************
        $param_ws = mosMedialibraryWS::getWsParamById($media->informationFrom);
        if ($param_ws == "COM"){
            $host = "webservices.amazon.com";
        } 
        else if ($param_ws == "UK") $host = "webservices.amazon.co.uk";
        else if ($param_ws == "CA") $host = "webservices.amazon.ca";
        else if ($param_ws == "DE") $host = "webservices.amazon.de";
        else if ($param_ws == "JP") $host = "webservices.amazon.co.jp";
        else if ($param_ws == "FR") $host = "webservices.amazon.fr";
        else if ($param_ws == "ES") $host = "webservices.amazon.es";
        else if ($param_ws == "IT") $host = "webservices.amazon.it";
        else if ($param_ws == "CN") $host = "webservices.amazon.com";
        else if ($param_ws == "IN") $host = "webservices.amazon.in";
        else if ($param_ws == "BR") $host = "webservices.amazon.com.br";
        else if ($param_ws == "US") $host = "webservices.amazon.com";



        $searchItemRequest = new SearchItemsRequest ();
        $searchItemRequest->PartnerType = "Associates";
        // Put your Partner tag (Store/Tracking id) in place of Partner tag
        $searchItemRequest->PartnerTag = $medialibrary_configuration['ws']['amazon']['tag'] ;
        $searchItemRequest->Keywords = $book->isbn;
        $searchItemRequest->SearchIndex = "All";
        $searchItemRequest->Resources = ["Images.Primary.Medium","ItemInfo.Title","Offers.Listings.Price","ItemInfo.ExternalIds","ItemInfo.ByLineInfo","ItemInfo.Classifications","ItemInfo.ContentInfo","ItemInfo.ContentRating","ItemInfo.Features","ItemInfo.ManufactureInfo","ItemInfo.ProductInfo","ItemInfo.TechnicalInfo","ItemInfo.TradeInInfo"];


//         $getItemsRequest = new GetItemsRequest ();
//         $getItemsRequest->PartnerType = "Associates";
//         // Put your Partner tag (Store/Tracking id) in place of Partner tag
//         $getItemsRequest->PartnerTag = $medialibrary_configuration['ws']['amazon']['tag'] ;
// //        $getItemsRequest->ItemIdType = $book->isbn; B0199980K4
//         $getItemsRequest->ItemIds =  ["B0199980K4"];
//         $getItemsRequest->ItemIdType = "ASIN";
//         $getItemsRequest->Resources = ["Images.Primary.Small","ItemInfo.Title","Offers.Listings.Price"];

        $path = "/paapi5/searchitems";
        //$path = "/paapi5/getitems";
        $payload = json_encode ($searchItemRequest);
//        $payload = json_encode ($getItemsRequest);
        //Put your Access Key in place of <ACCESS_KEY> and Secret Key in place of <SECRET_KEY> in double quotes
        $awsv4 = new AwsV4 ($medialibrary_configuration['ws']['amazon']['devtag'], $medialibrary_configuration['ws']['amazon']['secret_key']);

        $awsv4->setRegionName("us-east-1");
        $awsv4->setServiceName("ProductAdvertisingAPI");
        $awsv4->setPath ($path);
        $awsv4->setPayload ($payload);
        $awsv4->setRequestMethod ("POST");
        $awsv4->addHeader ('content-encoding', 'amz-1.0');
        $awsv4->addHeader ('content-type', 'application/json; charset=utf-8');
        $awsv4->addHeader ('host', $host);
        $awsv4->addHeader ('x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.SearchItems');
//        $awsv4->addHeader ('x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems');
        $headers = $awsv4->getHeaders ();
        $headerString = "";
        foreach ( $headers as $key => $value ) {
            $headerString .= $key . ': ' . $value . "\r\n";
        }
        $params = array (
                'http' => array (
                    'header' => $headerString,
                    'method' => 'POST',
                    'content' => $payload
                )
            );


        $stream = stream_context_create ( $params );

        $fp = fopen ( 'https://'.$host.$path, 'rb', false, $stream );
        // echo ":11111111111111111:";
        // print_r($host.$path) ;
        // echo ":11111111111111111:";
        // print_r( $stream ) ;
        // exit ;

        if (! $fp) {
            echo "<script> alert('Sorry, Amazon fetch info, Exception Occured '); window.history.go(-1);
                  </script>\n";
            exit;
        }
        $response = @stream_get_contents ( $fp );
        if ($response === false) {
            echo "<script> alert('Sorry, Amazon fetch info, Exception Occured '); window.history.go(-1);
                  </script>\n";
            exit;
        }
        //echo $response;


        $result = json_decode($response);

        foreach ($result->SearchResult->Items as $value) {
            if($value->ItemInfo->ExternalIds->ISBNs->DisplayValues[0] == $book->isbn ){
                 // echo "11111111111111111:";
                 // print_r($value); exit ;

                //ProductName
                $book->title = $value->ItemInfo->Title->DisplayValue;
                //ImageUrlMedium
                $book->imageURL = $value->Images->Primary->Medium->URL;
                //URL
                $book->URL = $value->DetailPageURL;
                //Number Of Pages
                $book->numberOfPages = $value->ItemInfo->ContentInfo->PagesCount->DisplayValue;
                //Manufacturer
                $book->manufacturer = $value->ItemInfo->ByLineInfo->Manufacturer->DisplayValue;
   
                $i = 0;
                $book->authors = "";
                foreach($value->ItemInfo->ByLineInfo->Contributors as $item) {
                    if($item->Role != "Author")  continue ;
                    if ($i > 0) $book->authors.= ', ';
                    $book->authors.= str_replace(",", " ", $item->Name); ;
                    $i++;
                }


                $book->release_date = substr($value->ItemInfo->ContentInfo->PublicationDate->DisplayValue,0,10);

                $book->edition = $value->ItemInfo->ContentInfo->Edition->DisplayValue;

                //Price no partner
                if (array_key_exists('Listings', $value->Offers) && 
                        array_key_exists('Amount', $value->Offers->Listings[0]->Price)) {
                    $book->price = 
                        substr_replace( $value->Offers->Listings[0]->Price->Amount, '.', -3, 1);
                    $book->priceunit = $value->Offers->Listings[0]->Price->Currency;
                    $mas = $book->price;
                    //$mas = ereg_replace("\xC2\xA3", "GBP ", $mas);  //for funt
                    //$mas = ereg_replace("\xEF\xBF\xA5", "JPY", $mas);  //for ena
                    $book->price = $mas;
                } else {
                    $book->price = "Does not exist anymore!";
                }


           }
        }


        return $book;
    }

                 
 static function fetchAmazonInfosVideoPaapi5($media,$video ) {
     
    global $medialibrary_configuration,$my,$acl ;
  
    $param_ws=mosMedialibraryWS::getWsParamById($media->informationFrom);

    $param_ws = mosMedialibraryWS::getWsParamById($media->informationFrom);
    if ($param_ws == "COM"){
        $host = "webservices.amazon.com";
    } 
    else if ($param_ws == "UK") $host = "webservices.amazon.co.uk";
    else if ($param_ws == "CA") $host = "webservices.amazon.ca";
    else if ($param_ws == "DE") $host = "webservices.amazon.de";
    else if ($param_ws == "JP") $host = "webservices.amazon.co.jp";
    else if ($param_ws == "FR") $host = "webservices.amazon.fr";
    else if ($param_ws == "ES") $host = "webservices.amazon.es";
    else if ($param_ws == "IT") $host = "webservices.amazon.it";
    else if ($param_ws == "CN") $host = "webservices.amazon.com";
    else if ($param_ws == "IN") $host = "webservices.amazon.in";
    else if ($param_ws == "BR") $host = "webservices.amazon.com.br";
    else if ($param_ws == "US") $host = "webservices.amazon.com";



        // $searchItemRequest = new SearchItemsRequest ();
        // $searchItemRequest->PartnerType = "Associates";
        // // Put your Partner tag (Store/Tracking id) in place of Partner tag
        // $searchItemRequest->PartnerTag = $medialibrary_configuration['ws']['amazon']['tag'] ;
        // $searchItemRequest->Keywords = $video->asin;
        // $searchItemRequest->SearchIndex = "All";
        // $searchItemRequest->Resources = ["Images.Primary.Medium","ItemInfo.Title","Offers.Listings.Price","ItemInfo.ExternalIds","ItemInfo.ByLineInfo","ItemInfo.Classifications","ItemInfo.ContentInfo","ItemInfo.ContentRating","ItemInfo.Features","ItemInfo.ManufactureInfo","ItemInfo.ProductInfo","ItemInfo.TechnicalInfo","ItemInfo.TradeInInfo"];


         $getItemsRequest = new GetItemsRequest ();
         $getItemsRequest->PartnerType = "Associates";
         // Put your Partner tag (Store/Tracking id) in place of Partner tag
         $getItemsRequest->PartnerTag = $medialibrary_configuration['ws']['amazon']['tag'] ;
         $getItemsRequest->ItemIds =  [$video->asin];
         $getItemsRequest->ItemIdType = "ASIN";
         $getItemsRequest->Resources = ["Images.Primary.Medium","ItemInfo.Title","Offers.Listings.Price","ItemInfo.ExternalIds","ItemInfo.ByLineInfo","ItemInfo.Classifications","ItemInfo.ContentInfo","ItemInfo.ContentRating","ItemInfo.Features","ItemInfo.ManufactureInfo","ItemInfo.ProductInfo","ItemInfo.TechnicalInfo","ItemInfo.TradeInInfo"];

//        $path = "/paapi5/searchitems";
        $path = "/paapi5/getitems";
//        $payload = json_encode ($searchItemRequest);
        $payload = json_encode ($getItemsRequest);
        //Put your Access Key in place of <ACCESS_KEY> and Secret Key in place of <SECRET_KEY> in double quotes
        $awsv4 = new AwsV4 ($medialibrary_configuration['ws']['amazon']['devtag'], $medialibrary_configuration['ws']['amazon']['secret_key']);

        $awsv4->setRegionName("us-east-1");
        $awsv4->setServiceName("ProductAdvertisingAPI");
        $awsv4->setPath ($path);
        $awsv4->setPayload ($payload);
        $awsv4->setRequestMethod ("POST");
        $awsv4->addHeader ('content-encoding', 'amz-1.0');
        $awsv4->addHeader ('content-type', 'application/json; charset=utf-8');
        $awsv4->addHeader ('host', $host);
//        $awsv4->addHeader ('x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.SearchItems');
        $awsv4->addHeader ('x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems');
        $headers = $awsv4->getHeaders ();
        $headerString = "";
        foreach ( $headers as $key => $value ) {
            $headerString .= $key . ': ' . $value . "\r\n";
        }
        $params = array (
                'http' => array (
                    'header' => $headerString,
                    'method' => 'POST',
                    'content' => $payload
                )
            );


        $stream = stream_context_create ( $params );

        $fp = fopen ( 'https://'.$host.$path, 'rb', false, $stream );
         // echo ":11111111111111111:";
         // print_r($host.$path) ;
         // echo ":11111111111111111:";
         // print_r( $stream ) ;
         // exit ;

        if (! $fp) {
            echo "<script> alert('Sorry, Amazon fetch info, Exception Occured '); window.history.go(-1);
                  </script>\n";
            exit;
        }
        $response = @stream_get_contents ( $fp );
        if ($response === false) {
            echo "<script> alert('Sorry, Amazon fetch info, Exception Occured '); window.history.go(-1);
                  </script>\n";
            exit;
        }
        //echo $response;


        $result = json_decode($response);

           // echo ":11111111111111111:";
           // print_r( $result) ;
           //  echo ":11111111111111111:";
           // print_r( $video) ;
          // exit ;

        foreach ($result->ItemsResult->Items as $value) {
            if($value->ASIN == $video->asin ){
                 // echo "11111111111111111:";
                 // print_r($value); exit ;

                //ProductName
                $video->title = $value->ItemInfo->Title->DisplayValue;
                //ImageUrlMedium
                $video->imageURL = $value->Images->Primary->Medium->URL;
                //URL
                $video->URL = $value->DetailPageURL;
   
                $i = 0;
                $video->actors = "";
                foreach($value->ItemInfo->ByLineInfo->Contributors as $item) {
                    if($item->Role != "Actor")  continue ;
                    if ($i > 0) $video->actors.= ', ';
                    $video->actors.= str_replace(",", " ", $item->Name); ;
                    $i++;
                }

                $i = 0;
                $video->producers = "";
                foreach($value->ItemInfo->ByLineInfo->Contributors as $item) {
                    if($item->Role != "Producer")  continue ;
                    if ($i > 0) $video->producers.= ', ';
                    $video->producers.= str_replace(",", " ", $item->Name); ;
                    $i++;
                }

                $i = 0;
                $video->directors = "";
                foreach($value->ItemInfo->ByLineInfo->Contributors as $item) {
                    if($item->Role != "Director")  continue ;
                    if ($i > 0) $video->directors.= ', ';
                    $video->directors.= str_replace(",", " ", $item->Name); ;
                    $i++;
                }




                $video->release_date = substr($value->ItemInfo->ProductInfo->ReleaseDate->DisplayValue,0,10);

                //Price no partner
                if (array_key_exists('Listings', $value->Offers) && 
                        array_key_exists('Amount', $value->Offers->Listings[0]->Price)) {
                    $video->price = 
                        substr_replace( $value->Offers->Listings[0]->Price->Amount, '.', -3, 1);
                    $video->priceunit = $value->Offers->Listings[0]->Price->Currency;
                    $mas = $video->price;
                    //$mas = ereg_replace("\xC2\xA3", "GBP ", $mas);  //for funt
                    //$mas = ereg_replace("\xEF\xBF\xA5", "JPY", $mas);  //for ena
                    $video->price = $mas;
                } else {
                    $video->price = "Does not exist anymore!";
                }


           }
        }

           // echo ":222222222:";
           // print_r( $result) ;
           //  echo ":22222222222222:";
           // print_r( $video) ;
           // exit ;

    return $video;
  }    

static function fetchAmazonInfosMusicPaapi5($media,$music) {

     
    global $medialibrary_configuration,$my,$acl ;
  
    $param_ws=mosMedialibraryWS::getWsParamById($media->informationFrom);

    $param_ws = mosMedialibraryWS::getWsParamById($media->informationFrom);
    if ($param_ws == "COM"){
        $host = "webservices.amazon.com";
    } 
    else if ($param_ws == "UK") $host = "webservices.amazon.co.uk";
    else if ($param_ws == "CA") $host = "webservices.amazon.ca";
    else if ($param_ws == "DE") $host = "webservices.amazon.de";
    else if ($param_ws == "JP") $host = "webservices.amazon.co.jp";
    else if ($param_ws == "FR") $host = "webservices.amazon.fr";
    else if ($param_ws == "ES") $host = "webservices.amazon.es";
    else if ($param_ws == "IT") $host = "webservices.amazon.it";
    else if ($param_ws == "CN") $host = "webservices.amazon.com";
    else if ($param_ws == "IN") $host = "webservices.amazon.in";
    else if ($param_ws == "BR") $host = "webservices.amazon.com.br";
    else if ($param_ws == "US") $host = "webservices.amazon.com";



        // $searchItemRequest = new SearchItemsRequest ();
        // $searchItemRequest->PartnerType = "Associates";
        // // Put your Partner tag (Store/Tracking id) in place of Partner tag
        // $searchItemRequest->PartnerTag = $medialibrary_configuration['ws']['amazon']['tag'] ;
        // $searchItemRequest->Keywords = $media->asin;
        // $searchItemRequest->SearchIndex = "All";
        // $searchItemRequest->Resources = ["Images.Primary.Medium","ItemInfo.Title","Offers.Listings.Price","ItemInfo.ExternalIds","ItemInfo.ByLineInfo","ItemInfo.Classifications","ItemInfo.ContentInfo","ItemInfo.ContentRating","ItemInfo.Features","ItemInfo.ManufactureInfo","ItemInfo.ProductInfo","ItemInfo.TechnicalInfo","ItemInfo.TradeInInfo"];


         $getItemsRequest = new GetItemsRequest ();
         $getItemsRequest->PartnerType = "Associates";
         // Put your Partner tag (Store/Tracking id) in place of Partner tag
         $getItemsRequest->PartnerTag = $medialibrary_configuration['ws']['amazon']['tag'] ;
         $getItemsRequest->ItemIds =  [$music->asin];
         $getItemsRequest->ItemIdType = "ASIN";
         $getItemsRequest->Resources = ["Images.Primary.Medium","ItemInfo.Title","Offers.Listings.Price","ItemInfo.ExternalIds","ItemInfo.ByLineInfo","ItemInfo.Classifications","ItemInfo.ContentInfo","ItemInfo.ContentRating","ItemInfo.Features","ItemInfo.ManufactureInfo","ItemInfo.ProductInfo","ItemInfo.TechnicalInfo","ItemInfo.TradeInInfo"];

//        $path = "/paapi5/searchitems";
        $path = "/paapi5/getitems";
//        $payload = json_encode ($searchItemRequest);
        $payload = json_encode ($getItemsRequest);
        //Put your Access Key in place of <ACCESS_KEY> and Secret Key in place of <SECRET_KEY> in double quotes
        $awsv4 = new AwsV4 ($medialibrary_configuration['ws']['amazon']['devtag'], $medialibrary_configuration['ws']['amazon']['secret_key']);

        $awsv4->setRegionName("us-east-1");
        $awsv4->setServiceName("ProductAdvertisingAPI");
        $awsv4->setPath ($path);
        $awsv4->setPayload ($payload);
        $awsv4->setRequestMethod ("POST");
        $awsv4->addHeader ('content-encoding', 'amz-1.0');
        $awsv4->addHeader ('content-type', 'application/json; charset=utf-8');
        $awsv4->addHeader ('host', $host);
//        $awsv4->addHeader ('x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.SearchItems');
        $awsv4->addHeader ('x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems');
        $headers = $awsv4->getHeaders ();
        $headerString = "";
        foreach ( $headers as $key => $value ) {
            $headerString .= $key . ': ' . $value . "\r\n";
        }
        $params = array (
                'http' => array (
                    'header' => $headerString,
                    'method' => 'POST',
                    'content' => $payload
                )
            );


        $stream = stream_context_create ( $params );

        $fp = fopen ( 'https://'.$host.$path, 'rb', false, $stream );
         // echo ":11111111111111111:";
         // print_r($host.$path) ;
         // echo ":11111111111111111:";
         // print_r( $stream ) ;
         // exit ;

        if (! $fp) {
            echo "<script> alert('Sorry, Amazon fetch info, Exception Occured '); window.history.go(-1);
                  </script>\n";
            exit;
        }
        $response = @stream_get_contents ( $fp );
        if ($response === false) {
            echo "<script> alert('Sorry, Amazon fetch info, Exception Occured '); window.history.go(-1);
                  </script>\n";
            exit;
        }
        //echo $response;


        $result = json_decode($response);

          //  echo ":11111111111111111:";
          //  print_r( $result) ;
          //   echo ":11111111111111111:";
          //  print_r( $music) ;
          // exit ;

        foreach ($result->ItemsResult->Items as $value) {
            if($value->ASIN == $music->asin ){
                 // echo "11111111111111111:";
                 // print_r($value); exit ;

                //ProductName
                $music->title = $value->ItemInfo->Title->DisplayValue;
                //ImageUrlMedium
                $music->imageURL = $value->Images->Primary->Medium->URL;
                //URL
                $music->URL = $value->DetailPageURL;
   
                $i = 0;
                $music->artist = "";
                foreach($value->ItemInfo->ByLineInfo->Contributors as $item) {
                    if($item->Role != "Primary Contributor")  continue ;
                    if ($i > 0) $music->artist.= ', ';
                    $music->artist.= str_replace(",", " ", $item->Name); ;
                    $i++;
                }


                //binding
                $music->binding = $value->ItemInfo->Classifications->Binding->DisplayValue;
            
                //add label
                $music->label = $value->ItemInfo->ByLineInfo->Manufacturer->DisplayValue; 

                $music->release_date = substr($value->ItemInfo->ProductInfo->ReleaseDate->DisplayValue,0,10);

                //Price no partner
                if (array_key_exists('Listings', $value->Offers) && 
                        array_key_exists('Amount', $value->Offers->Listings[0]->Price)) {
                    $music->price = 
                        substr_replace( $value->Offers->Listings[0]->Price->Amount, '.', -3, 1);
                    $music->priceunit = $value->Offers->Listings[0]->Price->Currency;
                    $mas = $music->price;
                    //$mas = ereg_replace("\xC2\xA3", "GBP ", $mas);  //for funt
                    //$mas = ereg_replace("\xEF\xBF\xA5", "JPY", $mas);  //for ena
                    $music->price = $mas;
                } else {
                    $music->price = "Does not exist anymore!";
                }


           }
        }
           //  echo ":11111111111111111:";
           //  print_r( $result) ;
           //   echo ":11111111111111111:";
           //  print_r( $music) ;
           // exit ;


    return $music;
  }


 static function fetchAmazonInfosGamePaapi5($media,$game) {
     
    global $medialibrary_configuration,$my,$acl ;
  
    $param_ws=mosMedialibraryWS::getWsParamById($media->informationFrom);

    $param_ws = mosMedialibraryWS::getWsParamById($media->informationFrom);
    if ($param_ws == "COM"){
        $host = "webservices.amazon.com";
    } 
    else if ($param_ws == "UK") $host = "webservices.amazon.co.uk";
    else if ($param_ws == "CA") $host = "webservices.amazon.ca";
    else if ($param_ws == "DE") $host = "webservices.amazon.de";
    else if ($param_ws == "JP") $host = "webservices.amazon.co.jp";
    else if ($param_ws == "FR") $host = "webservices.amazon.fr";
    else if ($param_ws == "ES") $host = "webservices.amazon.es";
    else if ($param_ws == "IT") $host = "webservices.amazon.it";
    else if ($param_ws == "CN") $host = "webservices.amazon.com";
    else if ($param_ws == "IN") $host = "webservices.amazon.in";
    else if ($param_ws == "BR") $host = "webservices.amazon.com.br";
    else if ($param_ws == "US") $host = "webservices.amazon.com";



        // $searchItemRequest = new SearchItemsRequest ();
        // $searchItemRequest->PartnerType = "Associates";
        // // Put your Partner tag (Store/Tracking id) in place of Partner tag
        // $searchItemRequest->PartnerTag = $medialibrary_configuration['ws']['amazon']['tag'] ;
        // $searchItemRequest->Keywords = $media->asin;
        // $searchItemRequest->SearchIndex = "All";
        // $searchItemRequest->Resources = ["Images.Primary.Medium","ItemInfo.Title","Offers.Listings.Price","ItemInfo.ExternalIds","ItemInfo.ByLineInfo","ItemInfo.Classifications","ItemInfo.ContentInfo","ItemInfo.ContentRating","ItemInfo.Features","ItemInfo.ManufactureInfo","ItemInfo.ProductInfo","ItemInfo.TechnicalInfo","ItemInfo.TradeInInfo"];


         $getItemsRequest = new GetItemsRequest ();
         $getItemsRequest->PartnerType = "Associates";
         // Put your Partner tag (Store/Tracking id) in place of Partner tag
         $getItemsRequest->PartnerTag = $medialibrary_configuration['ws']['amazon']['tag'] ;
         $getItemsRequest->ItemIds =  [$game->asin];
         $getItemsRequest->ItemIdType = "ASIN";
         $getItemsRequest->Resources = ["Images.Primary.Medium","ItemInfo.Title","Offers.Listings.Price","ItemInfo.ExternalIds","ItemInfo.ByLineInfo","ItemInfo.Classifications","ItemInfo.ContentInfo","ItemInfo.ContentRating","ItemInfo.Features","ItemInfo.ManufactureInfo","ItemInfo.ProductInfo","ItemInfo.TechnicalInfo","ItemInfo.TradeInInfo"];

//        $path = "/paapi5/searchitems";
        $path = "/paapi5/getitems";
//        $payload = json_encode ($searchItemRequest);
        $payload = json_encode ($getItemsRequest);
        //Put your Access Key in place of <ACCESS_KEY> and Secret Key in place of <SECRET_KEY> in double quotes
        $awsv4 = new AwsV4 ($medialibrary_configuration['ws']['amazon']['devtag'], $medialibrary_configuration['ws']['amazon']['secret_key']);

        $awsv4->setRegionName("us-east-1");
        $awsv4->setServiceName("ProductAdvertisingAPI");
        $awsv4->setPath ($path);
        $awsv4->setPayload ($payload);
        $awsv4->setRequestMethod ("POST");
        $awsv4->addHeader ('content-encoding', 'amz-1.0');
        $awsv4->addHeader ('content-type', 'application/json; charset=utf-8');
        $awsv4->addHeader ('host', $host);
//        $awsv4->addHeader ('x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.SearchItems');
        $awsv4->addHeader ('x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems');
        $headers = $awsv4->getHeaders ();
        $headerString = "";
        foreach ( $headers as $key => $value ) {
            $headerString .= $key . ': ' . $value . "\r\n";
        }
        $params = array (
                'http' => array (
                    'header' => $headerString,
                    'method' => 'POST',
                    'content' => $payload
                )
            );


        $stream = stream_context_create ( $params );

        $fp = fopen ( 'https://'.$host.$path, 'rb', false, $stream );
         // echo ":11111111111111111:";
         // print_r($host.$path) ;
         // echo ":11111111111111111:";
         // print_r( $stream ) ;
         // exit ;

        if (! $fp) {
            echo "<script> alert('Sorry, Amazon fetch info, Exception Occured '); window.history.go(-1);
                  </script>\n";
            exit;
        }
        $response = @stream_get_contents ( $fp );
        if ($response === false) {
            echo "<script> alert('Sorry, Amazon fetch info, Exception Occured '); window.history.go(-1);
                  </script>\n";
            exit;
        }
        //echo $response;


        $result = json_decode($response);

          //  echo ":11111111111111111:";
          //  print_r( $result) ;
          //   echo ":11111111111111111:";
          //  print_r( $game) ;
          // exit ;

        foreach ($result->ItemsResult->Items as $value) {
            if($value->ASIN == $game->asin ){
                 // echo "11111111111111111:";
                 // print_r($value); exit ;

                //ProductName
                $game->title = $value->ItemInfo->Title->DisplayValue;
                //ImageUrlMedium
                $game->imageURL = $value->Images->Primary->Medium->URL;
                //URL
                $game->URL = $value->DetailPageURL;
   
                $i = 0;
                $game->artist = "";
                foreach($value->ItemInfo->ByLineInfo->Contributors as $item) {
                    if($item->Role != "Primary Contributor")  continue ;
                    if ($i > 0) $game->artist.= ', ';
                    $game->artist.= str_replace(",", " ", $item->Name); ;
                    $i++;
                }


                //binding
                $game->binding = $value->ItemInfo->Classifications->Binding->DisplayValue;

                //add platform
                $game->platform = $value->ItemInfo->ByLineInfo->Brand->DisplayValue; 
          
                //studio
                $game->studio = $value->ItemInfo->ByLineInfo->Manufacturer->DisplayValue; 

                $game->release_date = substr($value->ItemInfo->ProductInfo->ReleaseDate->DisplayValue,0,10);

                //Price no partner
                if (array_key_exists('Listings', $value->Offers) && 
                        array_key_exists('Amount', $value->Offers->Listings[0]->Price)) {
                    $game->price = 
                        substr_replace( $value->Offers->Listings[0]->Price->Amount, '.', -3, 1);
                    $game->priceunit = $value->Offers->Listings[0]->Price->Currency;
                    $mas = $game->price;
                    //$mas = ereg_replace("\xC2\xA3", "GBP ", $mas);  //for funt
                    //$mas = ereg_replace("\xEF\xBF\xA5", "JPY", $mas);  //for ena
                    $game->price = $mas;
                } else {
                    $game->price = "Does not exist anymore!";
                }


           }
        }
           //  echo ":11111111111111111:";
           //  print_r( $result) ;
           //   echo ":11111111111111111:";
           //  print_r( $music) ;
           // exit ;


    return $game;
  }

}

