<?php

/**
 * @author Ronny Bansemer
 * @version 2.00
 *
 */
class DatenlinkConnector
{
   protected
   $debug = false,
   $settings =
      array(
         'lang' => 'DEU',
         'format' => 'json',
         'version' => '2.0',
         'use_compression' => true,
         'use_ssl' => true),
   $softwareName,
   $authenticationData;

   function __construct($application_token, $softwareName, $company_token = null)
   {
      $this->softwareName = $softwareName;
      $this->authenticationData =
         array(
            'application_token' => $application_token,
            'company_token' => $company_token);
   }

   public function setDebug()
   {
      $this->debug = true;
   }

   public function setVersion($version)
   {
      if(in_array($version, array('2.0'), true))
      {
         $this->settings['version'] = $version;
      }
      else
      {
         // your errorhandling
      }
   }

   public function setFormat($format)
   {
      if(in_array($format, array('xml', 'json'), true))
      {
         $this->settings['format'] = $format;
      }
      else
      {
         // your errorhandling
      }
   }

   public function setLanguage($lang)
   {
      if(in_array($lang, array('DEU'), true))
      {
         $this->settings['lang'] = $format;
      }
      else
      {
         // your errorhandling
      }
   }

   public function disableCompression()
   {
      $this->settings['use_compression'] = false;
   }

   public function disableSSL()
   {
      $this->settings['use_ssl'] = false;
   }

   public function validateCompanyToken($token)
   {
      return $this->sendRequest('validateCompanyToken', array('token' => $token));
   }

   public function getComponentLists()
   {
      return $this->sendRequest('getComponentLists');
   }

   public function getComponentListEntries($component_list, $key = false, $multirequest = false)
   {
      $param =
         array(
            'component_list' => $component_list);

      if($key !== false)
      {
         $param['key'] = $key;

         if($multirequest !== false)
         {
            $param['multirequest'] = $multirequest;
         }
      }

      return $this->sendRequest('getComponentListEntries', $param);
   }

   public function getDistributorList()
   {
      return $this->sendRequest('getDistributorList');
   }

   public function getDistributorData($id)
   {
      return $this->sendRequest('getDistributorData', array('id' => $id));
   }

   public function getSubscribedProductVersions()
   {
      return $this->sendRequest('getSubscribedProductVersions');
   }

   public function getProductVersions($datenlink_id)
   {
      return $this->sendRequest('getProductVersions', array('datenlink_id' => $datenlink_id));
   }

   public function getProductVersionData($datenlink_id, $version = false, $response_type = false, $resolve_values = false)
   {
      $param =
         array(
            'datenlink_id' => $datenlink_id);

      if($version !== false)
      {
         $param['version'] = $version;
      }

      if($response_type !== false)
      {
         $param['response_type'] = $response_type;
      }

      if($resolve_values !== false)
      {
         $param['resolve_values'] = $resolve_values;
      }

      return $this->sendRequest('getProductVersionData', $param);
   }

   public function subscribeProductVersion($datenlink_id, $force_override = 'NO')
   {
      return $this->sendRequest('subscribeProductVersion',
         array(
            'datenlink_id' => $datenlink_id,
            'force_override' => $force_override));
   }

   public function unsubscribeProductVersion($datenlink_id)
   {
      return $this->sendRequest('unsubscribeProductVersion',
         array(
            'datenlink_id' => $datenlink_id));
   }

   public function lookupProduct($identifier = false, $value = false, $filter_id = false, $current_page = false, $results_per_page = false)
   {
      $param = array();

      if($identifier !== false)
      {
         $param['identifier'] = $identifier;
         $param['value'] = $value;
      }

      if($filter_id !== false)
      {
         $param['filter_id'] = $filter_id;
      }

      if($current_page !== false)
      {
         $param['current_page'] = $current_page;
      }

      if($results_per_page !== false)
      {
         $param['results_per_page'] = $results_per_page;
      }

      return $this->sendRequest('lookupProduct', $param);
   }

   public function sendRequest($service, $param = null)
   {
      $content = null;

      $curl = curl_init('http'.($this->settings['use_ssl'] === true ? 's' : '').'://api.datenlink.info/basic/'.$this->settings['version'].'/'.$service.'.'.$this->settings['format'].'?lang='.$this->settings['lang']);

      // disable on using safe_mode or open_basedir!
      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($curl, CURLOPT_MAXREDIRS, 2);

      curl_setopt($curl, CURLOPT_USERAGENT, $this->softwareName);
      curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
      curl_setopt($curl, CURLOPT_HEADER, true);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLINFO_HEADER_OUT, true);
      curl_setopt($curl, CURLOPT_VERBOSE, true);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

      $optHeader = array('X-DL-TOKEN-APPLICATION: '.$this->authenticationData['application_token']);

      if($this->authenticationData['company_token'] !== null)
      {
         $optHeader[] = 'X-DL-TOKEN-COMPANY: '.$this->authenticationData['company_token'];
      }

      curl_setopt($curl, CURLOPT_HTTPHEADER, $optHeader);

      if($this->settings['use_compression'] === true)
      {
         curl_setopt($curl, CURLOPT_ENCODING, 'DEFLATE');
      }

      if($param !== null && ($paramCount = count($param)) > 0)
      {
         $paramString = http_build_query($param);

         curl_setopt($curl, CURLOPT_POST, $paramCount);
         curl_setopt($curl, CURLOPT_POSTFIELDS, $paramString);
      }

      $response = curl_exec($curl);
      $error = curl_error($curl);
      $http_status = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);
      $content = mb_substr($response, curl_getinfo($curl, CURLINFO_HEADER_SIZE));

      if($this->debug === true)
      {
         if($this->settings['use_compression'] === true)
         {
            echo '<strong>Komressionsrate:</strong> ',(round(curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD) / strlen($content), 2) * 100),'%';
         }

         echo '<h2>-- Request --</h2>',
         nl2br(curl_getinfo($curl, CURLINFO_HEADER_OUT)),
         $paramString;

         echo '<h2>-- Response --</h2>',
         nl2br(htmlspecialchars($response, ENT_NOQUOTES));
      }

      if($error == '')
      {
         if($this->settings['format'] === 'json')
         {
            $content = json_decode($content, true);
         }

         if($this->debug === true)
         {
            echo '<h2>-- Formatiertes Ergebnis --</h1><pre>';

            if($this->settings['format'] === 'json')
            {
               print_r($content);
            }
            else
            {
               $doc = new DomDocument('1.0', 'UTF-8');
               $doc->loadXML($content);
               $doc->preserveWhiteSpace = false;
               $doc->formatOutput = true;

               echo htmlspecialchars($doc->saveXML(), ENT_NOQUOTES);
            }

            echo '</pre>';
         }
      }
      else
      {
         if($this->debug === true)
         {
            echo 'HTTP-Statuscode: '.$http_status;
            print_r($error);
         }
         else
         {
            // your errorhandling
         }
      }

      curl_close($curl);

      return $content;
   }
}

?>
