home *** CD-ROM | disk | FTP | other *** search
/ Cricao de Sites - 650 Layouts Prontos / WebMasters.iso / Servidores / xampp-win32-1.6.7-installer.exe / php / PEAR / Services / Ebay / Session.php < prev   
Encoding:
PHP Script  |  2008-07-02  |  17.0 KB  |  535 lines

  1. <?PHP
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4                                                        |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2002 The PHP Group                                |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.0 of the PHP license,       |
  9. // | that is bundled with this package in the file LICENSE, and is        |
  10. // | available at through the world-wide-web at                           |
  11. // | http://www.php.net/license/2_02.txt.                                 |
  12. // | If you did not receive a copy of the PHP license and are unable to   |
  13. // | obtain it through the world-wide-web, please send a note to          |
  14. // | license@php.net so we can mail you a copy immediately.               |
  15. // +----------------------------------------------------------------------+
  16. // | Authors: Stephan Schmidt <schst@php.net>                             |
  17. // +----------------------------------------------------------------------+
  18. //
  19. // $Id: Session.php,v 1.17 2005/06/05 13:28:39 schst Exp $
  20.  
  21. /**
  22.  * Services/Ebay/Session.php
  23.  *
  24.  * manages IDs, authentication, serialization, etc.
  25.  *
  26.  * @package  Services_Ebay
  27.  * @author   Stephan Schmidt <schst@php.net>
  28.  */
  29. class Services_Ebay_Session
  30. {
  31.    /**
  32.     * Debugging disabled
  33.     */
  34.     const DEBUG_NONE = 0;
  35.  
  36.    /**
  37.     * Store debug data, so it can be displayed using getWire()
  38.     */
  39.     const DEBUG_STORE = 1;
  40.  
  41.    /**
  42.     * Display debug data
  43.     */
  44.     const DEBUG_PRINT = 2;
  45.  
  46.    /**
  47.     * Sandbox gateway URL
  48.     */
  49.     const URL_SANDBOX = 'https://api.sandbox.ebay.com/ws/api.dll';
  50.  
  51.    /**
  52.     * Production gateway URL
  53.     */
  54.     const URL_PRODUCTION = 'https://api.ebay.com/ws/api.dll';
  55.  
  56.    /**o
  57.     * developer ID
  58.     *
  59.     * If you do not already have one, please
  60.     * apply for a developer ID at http://developer.ebay.com
  61.     *
  62.     * @var string
  63.     */
  64.     private $devId;
  65.     
  66.    /**
  67.     * application id
  68.     *
  69.     * @var string
  70.     */
  71.     private $appId;
  72.  
  73.    /**
  74.     * application id
  75.     *
  76.     * @var certificate ID
  77.     */
  78.     private $certId;
  79.     
  80.    /**
  81.     * Auth & Auth token
  82.     *
  83.     * @var string
  84.     */
  85.     private $token;
  86.  
  87.    /**
  88.     * auth username
  89.     *
  90.     * @var string
  91.     */
  92.     private $requestUserId;
  93.  
  94.    /**
  95.     * auth password
  96.     *
  97.     * @var string
  98.     */
  99.     private $requestPassword;
  100.  
  101.     /**
  102.     * name of the transport driver to use
  103.     *
  104.     * @var string
  105.     */
  106.     private $transportDriver = 'Curl';
  107.  
  108.    /**
  109.     * transport driver
  110.     *
  111.     * @var  object Services_Ebay_Transport
  112.     */
  113.     private $transport;
  114.     
  115.    /**
  116.     * URL to use
  117.     *
  118.     * By default, the sandbox URL is used.
  119.     *
  120.     * @var  string
  121.     */
  122.     private $url;
  123.  
  124.    /**
  125.     * site id
  126.     *
  127.     * @var  integer
  128.     */
  129.     private $siteId = 0;
  130.  
  131.    /**
  132.     * XML_Serializer object
  133.     *
  134.     * @var object XML_Serializer
  135.     */
  136.     private $ser;
  137.  
  138.    /**
  139.     * XML_Unserializer object
  140.     *
  141.     * @var object XML_Unserializer
  142.     */
  143.     private $us;
  144.     
  145.    /**
  146.     * debug flag
  147.     *
  148.     * @var boolean
  149.     */
  150.     public $debug = 0;
  151.     
  152.    /**
  153.     * XML wire
  154.     *
  155.     * @var string
  156.     */
  157.     public $wire = null;
  158.     
  159.    /**
  160.     * compatibility level
  161.     *
  162.     * @var       integer
  163.     */
  164.     public $compatLevel = 379;
  165.  
  166.    /**
  167.     * general detail Level
  168.     *
  169.     * @var  int
  170.     */
  171.     private $detailLevel = 0;
  172.  
  173.    /**
  174.     * error language
  175.     *
  176.     * @var  int
  177.     */
  178.     private $errorLanguage = null;
  179.  
  180.    /**
  181.     * additional options for the serializer
  182.     *
  183.     * These options will be set by the call objects
  184.     *
  185.     * @var  array
  186.     */
  187.     private $serializerOptions = array();
  188.  
  189.    /**
  190.     * additional options for the unserializer
  191.     *
  192.     * These options will be set by the call objects
  193.     *
  194.     * @var  array
  195.     */
  196.     private $unserializerOptions = array();
  197.  
  198.    /**
  199.     * errors returned by the webservice
  200.     *
  201.     * @var array
  202.     */
  203.     private $errors = array();
  204.     
  205.    /**
  206.     * create the session object
  207.     *
  208.     * @param    string  developer id
  209.     * @param    string  application id
  210.     * @param    string  certificate id
  211.     * @param    string  external encoding, as eBay uses UTF-8, the session will encode and decode to
  212.     *                   the specified encoding. Possible values are ISO-8859-1 and UTF-8
  213.     */
  214.     public function __construct($devId, $appId, $certId, $encoding = 'ISO-8859-1')
  215.     {
  216.         $this->devId = $devId;
  217.         $this->appId = $appId;
  218.         $this->certId = $certId;
  219.         $this->url = self::URL_SANDBOX;
  220.         
  221.         $opts = array(
  222.                          'indent'             => '  ',
  223.                          'linebreak'          => "\n",
  224.                          'typeHints'          => false,
  225.                          'addDecl'            => true,
  226.                          'encoding'           => 'UTF-8',
  227.                          'scalarAsAttributes' => false,
  228.                          'rootName'           => 'request',
  229.                          'rootAttributes'     => array( 'xmlns' => 'urn:eBayAPIschema' ),
  230.                     );
  231.         // UTF-8 encode the document, if the user does not already
  232.         // use UTF-8 encoding
  233.         if ($encoding !== 'UTF-8') {
  234.             $opts['encodeFunction'] = 'utf8_encode';
  235.         }
  236.  
  237.         $this->ser = new XML_Serializer($opts);
  238.  
  239.         $opts = array(
  240.                     'forceEnum'      => array('Error'),
  241.                     'encoding'       => 'UTF-8',
  242.                     'targetEncoding' => $encoding,
  243.                     );
  244.         $this->us  = new XML_Unserializer($opts);
  245.     }
  246.  
  247.    /**
  248.     * set the debug mode
  249.     *
  250.     * Possible values are:
  251.     * - Services_Ebay_Session::DEBUG_NONE
  252.     * - Services_Ebay_Session::DEBUG_STORE
  253.     * - Services_Ebay_Session::DEBUG_PRINT
  254.     *
  255.     * @param    integer
  256.     * @see      getWire()
  257.     */
  258.     public function setDebug($debug)
  259.     {
  260.         $this->debug = $debug;
  261.     }
  262.  
  263.    /**
  264.     * get the XML code that was sent accross the network
  265.     *
  266.     * To use this, debug mode must be set to DEBUG_STORE or DEBUG_PRINT
  267.     *
  268.     * @return   string      xml wire
  269.     */
  270.     public function getWire()
  271.     {
  272.         return $this->wire;
  273.     }
  274.  
  275.    /**
  276.     * set the authentication token
  277.     *
  278.     * @param    string
  279.     */
  280.     public function setToken($token)
  281.     {
  282.         $this->token = $token;
  283.     }
  284.  
  285.    /**
  286.     * set the authentication username and password
  287.     *
  288.     * @param    string
  289.     */
  290.     public function setAuthenticationData($username, $password = null)
  291.     {
  292.         $this->requestUserId   = $username;
  293.         $this->requestPassword = $password;
  294.     }
  295.  
  296.    /**
  297.     * set the API URL
  298.     *
  299.     * @param    string
  300.     *
  301.     * Possible values are:
  302.     * - Services_Ebay_Session::URL_SANDBOX
  303.     * - Services_Ebay_Session::URL_PRODUCTION
  304.     * - Other URLs as applicable
  305.     *
  306.     */
  307.     public function setUrl($url)
  308.     {
  309.        $this->url = $url;
  310.     }
  311.  
  312.    /**
  313.     * set the site id
  314.     *
  315.     * @param    integer
  316.     */
  317.     public function setSiteId($siteId)
  318.     {
  319.        $this->siteId = $siteId;
  320.     }
  321.  
  322.    /**
  323.     * set the detail level
  324.     *
  325.     * @param    integer
  326.     */
  327.     public function setDetailLevel($level)
  328.     {
  329.         $this->detailLevel = $level;
  330.     }
  331.     
  332.    /**
  333.     * set the error language
  334.     *
  335.     * @param    string
  336.     */
  337.     public function setErrorLanguage($language)
  338.     {
  339.        $this->errorLanguage = $language;
  340.     }
  341.  
  342.    /**
  343.     * build XML code for a request
  344.     *
  345.     * @access   private
  346.     * @param    string      verb of the request
  347.     * @param    array|null  parameters of the request
  348.     * @return   string      XML request
  349.     */
  350.     public function buildRequestBody( $verb, $params = array(), $authType = Services_Ebay::AUTH_TYPE_TOKEN )
  351.     {
  352.         $request = array(
  353.                             'DetailLevel'     => $this->detailLevel,
  354.                             'ErrorLevel'      => 1,
  355.                             'SiteId'          => $this->siteId,
  356.                             'Verb'            => $verb
  357.                         );
  358.         switch ($authType) {
  359.             case Services_Ebay::AUTH_TYPE_TOKEN:
  360.                 if (empty($this->token)) {
  361.                     throw new Services_Ebay_Auth_Exception('No authentication token set.');
  362.                 }
  363.                 $request['RequestToken'] = $this->token;
  364.                 break;
  365.             case Services_Ebay::AUTH_TYPE_USER:
  366.                 if (empty($this->requestUserId) || empty($this->requestPassword)) {
  367.                     throw new Services_Ebay_Auth_Exception('No authentication data (username and password) set.');
  368.                 }
  369.                 $request['RequestUserId']   = $this->requestUserId;
  370.                 $request['RequestPassword'] = $this->requestPassword;
  371.                 break;
  372.             case Services_Ebay::AUTH_TYPE_NONE:
  373.                 if (empty($this->requestUserId)) {
  374.                     throw new Services_Ebay_Auth_Exception('No username has been set.');
  375.                 }
  376.                 $request['RequestUserId']   = $this->requestUserId;
  377.                 break;
  378.         }
  379.  
  380.         $request = array_merge($request, $params);
  381.  
  382.         $this->ser->serialize($request, $this->serializerOptions);
  383.         
  384.         return $this->ser->getSerializedData();
  385.     }
  386.  
  387.    /**
  388.     * send a request
  389.     *
  390.     * This method is used by the API methods. You
  391.     * may call it directly to access any eBay function that
  392.     * is not yet implemented.
  393.     *
  394.     * @access   public
  395.     * @param    string      function to call
  396.     * @param    array       associative array containing all parameters for the function call
  397.     * @param    integer     authentication type
  398.     * @param    boolean     flag to indicate, whether XML should be parsed or returned raw
  399.     * @return   array       response
  400.     * @todo     add real error handling
  401.     */
  402.     public function sendRequest( $verb, $params = array(), $authType = Services_Ebay::AUTH_TYPE_TOKEN, $parseResult = true )
  403.     {
  404.         $this->wire = '';
  405.  
  406.         if (!isset($params['ErrorLanguage']) && !is_null($this->errorLanguage)) {
  407.             $params['ErrorLanguage'] = $this->errorLanguage;
  408.         }
  409.  
  410.         $body    = $this->buildRequestBody($verb, $params, $authType);
  411.  
  412.         if (!isset($params['DetailLevel'])) {
  413.             $params['DetailLevel'] = $this->detailLevel;
  414.         }
  415.         
  416.         $headers = array(
  417.                             'X-EBAY-API-SESSION-CERTIFICATE' => sprintf( '%s;%s;%s', $this->devId, $this->appId, $this->certId ),      // Required. Used to authenticate the function call. Use this format, where DevId is the same as the value of the X-EBAY-API-DEV-NAME header, AppId is the same as the value of the X-EBAY-API-APP-NAME header, and CertId  is the same as the value of the X-EBAY-API-CERT-NAME header: DevId;AppId;CertId
  418.                             'X-EBAY-API-COMPATIBILITY-LEVEL' => $this->compatLevel,                                                 // Required. Regulates versioning of the XML interface for the API.
  419.                             'X-EBAY-API-DEV-NAME'            => $this->devId,                                                       // Required. Developer ID, as registered with the Developer's Program. This value should match the first value (DevId) in the X-EBAY-API-SESSION-CERTIFICATE header. Used to authenticate the function call.
  420.                             'X-EBAY-API-APP-NAME'            => $this->appId,                                                       // Required. Application ID, as registered with the Developer's Program. This value should match the second value (AppId) in the X-EBAY-API-SESSION-CERTIFICATE header. Used to authenticate the function call.
  421.                             'X-EBAY-API-CERT-NAME'           => $this->certId,                                                      // Required. Certificate ID, as registered with the Developer's Program. This value should match the third value (CertId) in the X-EBAY-API-SESSION-CERTIFICATE header. Used to authenticate the function call.
  422.                             'X-EBAY-API-CALL-NAME'           => $verb,                                                              // Required. Name of the function being called, for example: 'GetItem' (without the quotation marks). This must match the information passed in the Verb input argument for each function.
  423.                             'X-EBAY-API-SITEID'              => $this->siteId,                                                      // Required. eBay site an item is listed on or that a user is registered on, depending on the purpose of the function call. This must match the information passed in the SiteId input argument for all functions.
  424.                             'X-EBAY-API-DETAIL-LEVEL'        => $params['DetailLevel'],                                             // Required. Controls amount or level of data returned by the function call. May be zero if the function does not support varying detail levels. This must match the information passed in the DetailLevel input argument for each function.
  425.                             'Content-Type'                   => 'text/xml',                                                         // Required. Specifies the kind of data being transmitted. The value must be 'text/xml'. Sending any other value (e.g., 'application/x-www-form-urlencoded') may cause the call to fail.
  426.                             'Content-Length'                 => strlen( $body )                                                     // Recommended. Specifies the size of the data (i.e., the length of the XML string) you are sending. This is used by eBay to determine how much data to read from the stream.
  427.                         );
  428.  
  429.         $file  = SERVICES_EBAY_BASEDIR.'/Ebay/Transport/'.$this->transportDriver.'.php';
  430.         $class = 'Services_Ebay_Transport_'.$this->transportDriver;
  431.  
  432.         @include_once $file;
  433.         if (!class_exists($class)) {
  434.             throw new Services_Ebay_Transport_Exception('Could not load selected transport driver.');            
  435.         }
  436.         $tp = new $class();
  437.         
  438.         if ($this->debug > 0) {
  439.             $this->wire .= "Sending request:\n";
  440.             $this->wire .= $body."\n\n";
  441.         }
  442.  
  443.         $response = $tp->sendRequest($this->url, $body, $headers);
  444.  
  445.         if (PEAR::isError($response)) {
  446.             return $response;
  447.         }
  448.         
  449.         if ($this->debug > 0) {
  450.             $this->wire .= "Received response:\n";
  451.             $this->wire .= $response."\n\n";
  452.         }
  453.  
  454.         if ($this->debug > 1) {
  455.             echo $this->wire . "\n";
  456.         }
  457.         
  458.         if ($parseResult === false) {
  459.             return $response;
  460.         }
  461.  
  462.         $this->us->unserialize( $response, false, $this->unserializerOptions );
  463.         $result = $this->us->getUnserializedData();
  464.  
  465.         $errors = array();
  466.         
  467.         if (isset($result['Errors'])) {
  468.             if (isset($result['Errors']['Error'])) {
  469.                 foreach ($result['Errors']['Error'] as $error) {
  470.                     $tmp = new Services_Ebay_Error($error);
  471.                     // last errors
  472.                     array_push($errors, $tmp);
  473.                     
  474.                     // all errors
  475.                     array_push($this->errors, $tmp);
  476.                 }
  477.  
  478.                 // check for serious errors
  479.                 $message = '';
  480.                 $severe  = array();
  481.                 foreach ($errors as $error) {
  482.                     if ($error->getSeverityCode() == 2) {
  483.                         continue;
  484.                     }
  485.                     $message .= $error->getLongMessage();
  486.                     $message .= "\n";
  487.                     array_push($severe, $error);
  488.                 }
  489.                 if (!empty($severe)) {
  490.                     throw new Services_Ebay_API_Exception($message, $severe);
  491.                 }
  492.             } else {
  493.                 throw new Services_Ebay_API_Exception('Unknown error occured.');
  494.             }
  495.         }
  496.         return $result;
  497.     }
  498.  
  499.    /**
  500.     * get the errors and warnings that happened during the
  501.     * last API calls
  502.     *
  503.     * @param  boolean   whether to clear the internal error list
  504.     * @return array
  505.     */
  506.     public function getErrors($clear = true)
  507.     {
  508.         $errors = $this->errors;
  509.         if ($clear === true) {
  510.             $this->errors = array();
  511.         }
  512.         return $errors;
  513.     }
  514.     
  515.    /**
  516.     * set additional options for the serializer
  517.     *
  518.     * @param    array
  519.     */
  520.     public function setSerializerOptions($opts = array())
  521.     {
  522.         $this->serializerOptions = $opts;
  523.     }
  524.  
  525.    /**
  526.     * set additional options for the unserializer
  527.     *
  528.     * @param    array
  529.     */
  530.     public function setUnserializerOptions($opts = array())
  531.     {
  532.         $this->unserializerOptions = $opts;
  533.     }
  534. }
  535. ?>