PageRenderTime 869ms CodeModel.GetById 156ms app.highlight 572ms RepoModel.GetById 91ms app.codeStats 1ms

/library/Zend/Http/Client.php

https://bitbucket.org/baruffaldi/cms-php-bfcms
PHP | 1186 lines | 529 code | 161 blank | 496 comment | 134 complexity | 29db64d10d0164b162951b0dbcd5fb31 MD5 | raw file
   1<?php
   2
   3/**
   4 * Zend Framework
   5 *
   6 * LICENSE
   7 *
   8 * This source file is subject to the new BSD license that is bundled
   9 * with this package in the file LICENSE.txt.
  10 * It is also available through the world-wide-web at this URL:
  11 * http://framework.zend.com/license/new-bsd
  12 * If you did not receive a copy of the license and are unable to
  13 * obtain it through the world-wide-web, please send an email
  14 * to license@zend.com so we can send you a copy immediately.
  15 *
  16 * @category   Zend
  17 * @package    Zend_Http
  18 * @subpackage Client
  19 * @version    $Id: Client.php 9906 2008-07-02 21:20:10Z shahar $
  20 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  21 * @license    http://framework.zend.com/license/new-bsd     New BSD License
  22 */
  23
  24/**
  25 * @see Zend_Loader
  26 */
  27require_once 'Zend/Loader.php';
  28
  29
  30/**
  31 * @see Zend_Uri
  32 */
  33require_once 'Zend/Uri.php';
  34
  35
  36/**
  37 * @see Zend_Http_Client_Adapter_Interface
  38 */
  39require_once 'Zend/Http/Client/Adapter/Interface.php';
  40
  41
  42/**
  43 * @see Zend_Http_Response
  44 */
  45require_once 'Zend/Http/Response.php';
  46
  47/**
  48 * Zend_Http_Client is an implemetation of an HTTP client in PHP. The client
  49 * supports basic features like sending different HTTP requests and handling
  50 * redirections, as well as more advanced features like proxy settings, HTTP
  51 * authentication and cookie persistance (using a Zend_Http_CookieJar object)
  52 *
  53 * @todo Implement proxy settings
  54 * @category   Zend
  55 * @package    Zend_Http
  56 * @subpackage Client
  57 * @throws     Zend_Http_Client_Exception
  58 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  59 * @license    http://framework.zend.com/license/new-bsd     New BSD License
  60 */
  61class Zend_Http_Client
  62{
  63    /**
  64     * HTTP request methods
  65     */
  66    const GET     = 'GET';
  67    const POST    = 'POST';
  68    const PUT     = 'PUT';
  69    const HEAD    = 'HEAD';
  70    const DELETE  = 'DELETE';
  71    const TRACE   = 'TRACE';
  72    const OPTIONS = 'OPTIONS';
  73    const CONNECT = 'CONNECT';
  74
  75    /**
  76     * Supported HTTP Authentication methods
  77     */
  78    const AUTH_BASIC = 'basic';
  79    //const AUTH_DIGEST = 'digest'; <-- not implemented yet
  80
  81    /**
  82     * HTTP protocol versions
  83     */
  84    const HTTP_1 = '1.1';
  85    const HTTP_0 = '1.0';
  86
  87    /**
  88     * POST data encoding methods
  89     */
  90    const ENC_URLENCODED = 'application/x-www-form-urlencoded';
  91    const ENC_FORMDATA   = 'multipart/form-data';
  92
  93    /**
  94     * Configuration array, set using the constructor or using ::setConfig()
  95     *
  96     * @var array
  97     */
  98    protected $config = array(
  99        'maxredirects'    => 5,
 100        'strictredirects' => false,
 101        'useragent'       => 'Zend_Http_Client',
 102        'timeout'         => 10,
 103        'adapter'         => 'Zend_Http_Client_Adapter_Socket',
 104        'httpversion'     => self::HTTP_1,
 105        'keepalive'       => false,
 106        'storeresponse'   => true,
 107        'strict'          => true
 108    );
 109
 110    /**
 111     * The adapter used to preform the actual connection to the server
 112     *
 113     * @var Zend_Http_Client_Adapter_Interface
 114     */
 115    protected $adapter = null;
 116
 117    /**
 118     * Request URI
 119     *
 120     * @var Zend_Uri_Http
 121     */
 122    protected $uri;
 123
 124    /**
 125     * Associative array of request headers
 126     *
 127     * @var array
 128     */
 129    protected $headers = array();
 130
 131    /**
 132     * HTTP request method
 133     *
 134     * @var string
 135     */
 136    protected $method = self::GET;
 137
 138    /**
 139     * Associative array of GET parameters
 140     *
 141     * @var array
 142     */
 143    protected $paramsGet = array();
 144
 145    /**
 146     * Assiciative array of POST parameters
 147     *
 148     * @var array
 149     */
 150    protected $paramsPost = array();
 151
 152    /**
 153     * Request body content type (for POST requests)
 154     *
 155     * @var string
 156     */
 157    protected $enctype = null;
 158
 159    /**
 160     * The raw post data to send. Could be set by setRawData($data, $enctype).
 161     *
 162     * @var string
 163     */
 164    protected $raw_post_data = null;
 165
 166    /**
 167     * HTTP Authentication settings
 168     *
 169     * Expected to be an associative array with this structure:
 170     * $this->auth = array('user' => 'username', 'password' => 'password', 'type' => 'basic')
 171     * Where 'type' should be one of the supported authentication types (see the AUTH_*
 172     * constants), for example 'basic' or 'digest'.
 173     *
 174     * If null, no authentication will be used.
 175     *
 176     * @var array|null
 177     */
 178    protected $auth;
 179
 180    /**
 181     * File upload arrays (used in POST requests)
 182     *
 183     * An associative array, where each element is of the format:
 184     *   'name' => array('filename.txt', 'text/plain', 'This is the actual file contents')
 185     *
 186     * @var array
 187     */
 188    protected $files = array();
 189
 190    /**
 191     * The client's cookie jar
 192     *
 193     * @var Zend_Http_CookieJar
 194     */
 195    protected $cookiejar = null;
 196
 197    /**
 198     * The last HTTP request sent by the client, as string
 199     *
 200     * @var string
 201     */
 202    protected $last_request = null;
 203
 204    /**
 205     * The last HTTP response received by the client
 206     *
 207     * @var Zend_Http_Response
 208     */
 209    protected $last_response = null;
 210
 211    /**
 212     * Redirection counter
 213     *
 214     * @var int
 215     */
 216    protected $redirectCounter = 0;
 217
 218    /**
 219     * Fileinfo magic database resource
 220     * 
 221     * This varaiable is populated the first time _detectFileMimeType is called
 222     * and is then reused on every call to this method
 223     *
 224     * @var resource
 225     */
 226    static protected $_fileInfoDb = null;
 227    
 228    /**
 229     * Contructor method. Will create a new HTTP client. Accepts the target
 230     * URL and optionally configuration array.
 231     *
 232     * @param Zend_Uri_Http|string $uri
 233     * @param array $config Configuration key-value pairs.
 234     */
 235    public function __construct($uri = null, $config = null)
 236    {
 237        if ($uri !== null) $this->setUri($uri);
 238        if ($config !== null) $this->setConfig($config);
 239    }
 240
 241    /**
 242     * Set the URI for the next request
 243     *
 244     * @param  Zend_Uri_Http|string $uri
 245     * @return Zend_Http_Client
 246     * @throws Zend_Http_Client_Exception
 247     */
 248    public function setUri($uri)
 249    {
 250        if (is_string($uri)) {
 251            $uri = Zend_Uri::factory($uri);
 252        }
 253
 254        if (!$uri instanceof Zend_Uri_Http) {
 255            /** @see Zend_Http_Client_Exception */
 256            require_once 'Zend/Http/Client/Exception.php';
 257            throw new Zend_Http_Client_Exception('Passed parameter is not a valid HTTP URI.');
 258        }
 259
 260        // We have no ports, set the defaults
 261        if (! $uri->getPort()) {
 262            $uri->setPort(($uri->getScheme() == 'https' ? 443 : 80));
 263        }
 264
 265        $this->uri = $uri;
 266
 267        return $this;
 268    }
 269
 270    /**
 271     * Get the URI for the next request
 272     *
 273     * @param boolean $as_string If true, will return the URI as a string
 274     * @return Zend_Uri_Http|string
 275     */
 276    public function getUri($as_string = false)
 277    {
 278        if ($as_string && $this->uri instanceof Zend_Uri_Http) {
 279            return $this->uri->__toString();
 280        } else {
 281            return $this->uri;
 282        }
 283    }
 284
 285    /**
 286     * Set configuration parameters for this HTTP client
 287     *
 288     * @param array $config
 289     * @return Zend_Http_Client
 290     * @throws Zend_Http_Client_Exception
 291     */
 292    public function setConfig($config = array())
 293    {
 294        if (! is_array($config)) {
 295            /** @see Zend_Http_Client_Exception */
 296            require_once 'Zend/Http/Client/Exception.php';
 297            throw new Zend_Http_Client_Exception('Expected array parameter, given ' . gettype($config));
 298        }
 299
 300        foreach ($config as $k => $v)
 301            $this->config[strtolower($k)] = $v;
 302
 303        return $this;
 304    }
 305
 306    /**
 307     * Set the next request's method
 308     *
 309     * Validated the passed method and sets it. If we have files set for
 310     * POST requests, and the new method is not POST, the files are silently
 311     * dropped.
 312     *
 313     * @param string $method
 314     * @return Zend_Http_Client
 315     * @throws Zend_Http_Client_Exception
 316     */
 317    public function setMethod($method = self::GET)
 318    {
 319        $regex = '/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/';
 320        if (! preg_match($regex, $method)) {
 321            /** @see Zend_Http_Client_Exception */
 322            require_once 'Zend/Http/Client/Exception.php';
 323            throw new Zend_Http_Client_Exception("'{$method}' is not a valid HTTP request method.");
 324        }
 325
 326        if ($method == self::POST && $this->enctype === null)
 327            $this->setEncType(self::ENC_URLENCODED);
 328
 329        $this->method = $method;
 330
 331        return $this;
 332    }
 333
 334    /**
 335     * Set one or more request headers
 336     *
 337     * This function can be used in several ways to set the client's request
 338     * headers:
 339     * 1. By providing two parameters: $name as the header to set (eg. 'Host')
 340     *    and $value as it's value (eg. 'www.example.com').
 341     * 2. By providing a single header string as the only parameter
 342     *    eg. 'Host: www.example.com'
 343     * 3. By providing an array of headers as the first parameter
 344     *    eg. array('host' => 'www.example.com', 'x-foo: bar'). In This case
 345     *    the function will call itself recursively for each array item.
 346     *
 347     * @param string|array $name Header name, full header string ('Header: value')
 348     *     or an array of headers
 349     * @param mixed $value Header value or null
 350     * @return Zend_Http_Client
 351     * @throws Zend_Http_Client_Exception
 352     */
 353    public function setHeaders($name, $value = null)
 354    {
 355        // If we got an array, go recusive!
 356        if (is_array($name)) {
 357            foreach ($name as $k => $v) {
 358                if (is_string($k)) {
 359                    $this->setHeaders($k, $v);
 360                } else {
 361                    $this->setHeaders($v, null);
 362                }
 363            }
 364        } else {
 365            // Check if $name needs to be split
 366            if ($value === null && (strpos($name, ':') > 0))
 367                list($name, $value) = explode(':', $name, 2);
 368
 369            // Make sure the name is valid if we are in strict mode
 370            if ($this->config['strict'] && (! preg_match('/^[a-zA-Z0-9-]+$/', $name))) {
 371                /** @see Zend_Http_Client_Exception */
 372                require_once 'Zend/Http/Client/Exception.php';
 373                throw new Zend_Http_Client_Exception("{$name} is not a valid HTTP header name");
 374            }
 375            
 376            $normalized_name = strtolower($name);
 377
 378            // If $value is null or false, unset the header
 379            if ($value === null || $value === false) {
 380                unset($this->headers[$normalized_name]);
 381
 382            // Else, set the header
 383            } else {
 384                // Header names are storred lowercase internally.
 385                if (is_string($value)) $value = trim($value);
 386                $this->headers[$normalized_name] = array($name, $value);
 387            }
 388        }
 389
 390        return $this;
 391    }
 392
 393    /**
 394     * Get the value of a specific header
 395     *
 396     * Note that if the header has more than one value, an array
 397     * will be returned.
 398     *
 399     * @param string $key
 400     * @return string|array|null The header value or null if it is not set
 401     */
 402    public function getHeader($key)
 403    {
 404        $key = strtolower($key);
 405        if (isset($this->headers[$key])) {
 406            return $this->headers[$key][1];
 407        } else {
 408            return null;
 409        }
 410    }
 411
 412    /**
 413     * Set a GET parameter for the request. Wrapper around _setParameter
 414     *
 415     * @param string|array $name
 416     * @param string $value
 417     * @return Zend_Http_Client
 418     */
 419    public function setParameterGet($name, $value = null)
 420    {
 421        if (is_array($name)) {
 422            foreach ($name as $k => $v)
 423                $this->_setParameter('GET', $k, $v);
 424        } else {
 425            $this->_setParameter('GET', $name, $value);
 426        }
 427
 428        return $this;
 429    }
 430
 431    /**
 432     * Set a POST parameter for the request. Wrapper around _setParameter
 433     *
 434     * @param string|array $name
 435     * @param string $value
 436     * @return Zend_Http_Client
 437     */
 438    public function setParameterPost($name, $value = null)
 439    {
 440        if (is_array($name)) {
 441            foreach ($name as $k => $v)
 442                $this->_setParameter('POST', $k, $v);
 443        } else {
 444            $this->_setParameter('POST', $name, $value);
 445        }
 446
 447        return $this;
 448    }
 449
 450    /**
 451     * Set a GET or POST parameter - used by SetParameterGet and SetParameterPost
 452     *
 453     * @param string $type GET or POST
 454     * @param string $name
 455     * @param string $value
 456     * @return null
 457     */
 458    protected function _setParameter($type, $name, $value)
 459    {
 460        $parray = array();
 461        $type = strtolower($type);
 462        switch ($type) {
 463            case 'get':
 464                $parray = &$this->paramsGet;
 465                break;
 466            case 'post':
 467                $parray = &$this->paramsPost;
 468                break;
 469        }
 470
 471        if ($value === null) {
 472            if (isset($parray[$name])) unset($parray[$name]);
 473        } else {
 474            $parray[$name] = $value;
 475        }
 476    }
 477
 478    /**
 479     * Get the number of redirections done on the last request
 480     *
 481     * @return int
 482     */
 483    public function getRedirectionsCount()
 484    {
 485        return $this->redirectCounter;
 486    }
 487
 488    /**
 489     * Set HTTP authentication parameters
 490     *
 491     * $type should be one of the supported types - see the self::AUTH_*
 492     * constants.
 493     *
 494     * To enable authentication:
 495     * <code>
 496     * $this->setAuth('shahar', 'secret', Zend_Http_Client::AUTH_BASIC);
 497     * </code>
 498     *
 499     * To disable authentication:
 500     * <code>
 501     * $this->setAuth(false);
 502     * </code>
 503     *
 504     * @see http://www.faqs.org/rfcs/rfc2617.html
 505     * @param string|false $user User name or false disable authentication
 506     * @param string $password Password
 507     * @param string $type Authentication type
 508     * @return Zend_Http_Client
 509     * @throws Zend_Http_Client_Exception
 510     */
 511    public function setAuth($user, $password = '', $type = self::AUTH_BASIC)
 512    {
 513        // If we got false or null, disable authentication
 514        if ($user === false || $user === null) {
 515            $this->auth = null;
 516
 517        // Else, set up authentication
 518        } else {
 519            // Check we got a proper authentication type
 520            if (! defined('self::AUTH_' . strtoupper($type))) {
 521                /** @see Zend_Http_Client_Exception */
 522                require_once 'Zend/Http/Client/Exception.php';
 523                throw new Zend_Http_Client_Exception("Invalid or not supported authentication type: '$type'");
 524            }
 525
 526            $this->auth = array(
 527                'user' => (string) $user,
 528                'password' => (string) $password,
 529                'type' => $type
 530            );
 531        }
 532
 533        return $this;
 534    }
 535
 536    /**
 537     * Set the HTTP client's cookie jar.
 538     *
 539     * A cookie jar is an object that holds and maintains cookies across HTTP requests
 540     * and responses.
 541     *
 542     * @param Zend_Http_CookieJar|boolean $cookiejar Existing cookiejar object, true to create a new one, false to disable
 543     * @return Zend_Http_Client
 544     * @throws Zend_Http_Client_Exception
 545     */
 546    public function setCookieJar($cookiejar = true)
 547    {
 548        if (! class_exists('Zend_Http_CookieJar'))
 549            require_once 'Zend/Http/CookieJar.php';
 550
 551        if ($cookiejar instanceof Zend_Http_CookieJar) {
 552            $this->cookiejar = $cookiejar;
 553        } elseif ($cookiejar === true) {
 554            $this->cookiejar = new Zend_Http_CookieJar();
 555        } elseif (! $cookiejar) {
 556            $this->cookiejar = null;
 557        } else {
 558            /** @see Zend_Http_Client_Exception */
 559            require_once 'Zend/Http/Client/Exception.php';
 560            throw new Zend_Http_Client_Exception('Invalid parameter type passed as CookieJar');
 561        }
 562
 563        return $this;
 564    }
 565
 566    /**
 567     * Return the current cookie jar or null if none.
 568     *
 569     * @return Zend_Http_CookieJar|null
 570     */
 571    public function getCookieJar()
 572    {
 573        return $this->cookiejar;
 574    }
 575
 576    /**
 577     * Add a cookie to the request. If the client has no Cookie Jar, the cookies
 578     * will be added directly to the headers array as "Cookie" headers.
 579     *
 580     * @param Zend_Http_Cookie|string $cookie
 581     * @param string|null $value If "cookie" is a string, this is the cookie value.
 582     * @return Zend_Http_Client
 583     * @throws Zend_Http_Client_Exception
 584     */
 585    public function setCookie($cookie, $value = null)
 586    {
 587        if (! class_exists('Zend_Http_Cookie'))
 588            require_once 'Zend/Http/Cookie.php';
 589
 590        if (is_array($cookie)) {
 591            foreach ($cookie as $c => $v) {
 592                if (is_string($c)) {
 593                    $this->setCookie($c, $v);
 594                } else {
 595                    $this->setCookie($v);
 596                }
 597            }
 598
 599            return $this;
 600        }
 601
 602        if ($value !== null) $value = urlencode($value);
 603
 604        if (isset($this->cookiejar)) {
 605            if ($cookie instanceof Zend_Http_Cookie) {
 606                $this->cookiejar->addCookie($cookie);
 607            } elseif (is_string($cookie) && $value !== null) {
 608                $cookie = Zend_Http_Cookie::fromString("{$cookie}={$value}", $this->uri);
 609                $this->cookiejar->addCookie($cookie);
 610            }
 611        } else {
 612            if ($cookie instanceof Zend_Http_Cookie) {
 613                $name = $cookie->getName();
 614                $value = $cookie->getValue();
 615                $cookie = $name;
 616            }
 617
 618            if (preg_match("/[=,; \t\r\n\013\014]/", $cookie)) {
 619                /** @see Zend_Http_Client_Exception */
 620                require_once 'Zend/Http/Client/Exception.php';
 621                throw new Zend_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\013\014 ({$cookie})");
 622            }
 623
 624            $value = addslashes($value);
 625
 626            if (! isset($this->headers['cookie'])) $this->headers['cookie'] = array('Cookie', '');
 627            $this->headers['cookie'][1] .= $cookie . '=' . $value . '; ';
 628        }
 629
 630        return $this;
 631    }
 632
 633    /**
 634     * Set a file to upload (using a POST request)
 635     *
 636     * Can be used in two ways:
 637     *
 638     * 1. $data is null (default): $filename is treated as the name if a local file which
 639     *    will be read and sent. Will try to guess the content type using mime_content_type().
 640     * 2. $data is set - $filename is sent as the file name, but $data is sent as the file
 641     *    contents and no file is read from the file system. In this case, you need to
 642     *    manually set the content-type ($ctype) or it will default to
 643     *    application/octet-stream.
 644     *
 645     * @param string $filename Name of file to upload, or name to save as
 646     * @param string $formname Name of form element to send as
 647     * @param string $data Data to send (if null, $filename is read and sent)
 648     * @param string $ctype Content type to use (if $data is set and $ctype is
 649     *     null, will be application/octet-stream)
 650     * @return Zend_Http_Client
 651     * @throws Zend_Http_Client_Exception
 652     */
 653    public function setFileUpload($filename, $formname, $data = null, $ctype = null)
 654    {
 655        if ($data === null) {
 656            if (($data = @file_get_contents($filename)) === false) {
 657                /** @see Zend_Http_Client_Exception */
 658                require_once 'Zend/Http/Client/Exception.php';
 659                throw new Zend_Http_Client_Exception("Unable to read file '{$filename}' for upload");
 660            }
 661
 662            if (! $ctype) $ctype = $this->_detectFileMimeType($filename);
 663        }
 664
 665        // Force enctype to multipart/form-data
 666        $this->setEncType(self::ENC_FORMDATA);
 667
 668        $this->files[$formname] = array(basename($filename), $ctype, $data);
 669
 670        return $this;
 671    }
 672
 673    /**
 674     * Set the encoding type for POST data
 675     *
 676     * @param string $enctype
 677     * @return Zend_Http_Client
 678     */
 679    public function setEncType($enctype = self::ENC_URLENCODED)
 680    {
 681        $this->enctype = $enctype;
 682
 683        return $this;
 684    }
 685
 686    /**
 687     * Set the raw (already encoded) POST data.
 688     *
 689     * This function is here for two reasons:
 690     * 1. For advanced user who would like to set their own data, already encoded
 691     * 2. For backwards compatibilty: If someone uses the old post($data) method.
 692     *    this method will be used to set the encoded data.
 693     *
 694     * @param string $data
 695     * @param string $enctype
 696     * @return Zend_Http_Client
 697     */
 698    public function setRawData($data, $enctype = null)
 699    {
 700        $this->raw_post_data = $data;
 701        $this->setEncType($enctype);
 702
 703        return $this;
 704    }
 705
 706    /**
 707     * Clear all GET and POST parameters
 708     *
 709     * Should be used to reset the request parameters if the client is
 710     * used for several concurrent requests.
 711     *
 712     * @return Zend_Http_Client
 713     */
 714    public function resetParameters()
 715    {
 716        // Reset parameter data
 717        $this->paramsGet     = array();
 718        $this->paramsPost    = array();
 719        $this->files         = array();
 720        $this->raw_post_data = null;
 721
 722        // Clear outdated headers
 723        if (isset($this->headers['content-type'])) unset($this->headers['content-type']);
 724        if (isset($this->headers['content-length'])) unset($this->headers['content-length']);
 725
 726        return $this;
 727    }
 728
 729    /**
 730     * Get the last HTTP request as string
 731     *
 732     * @return string
 733     */
 734    public function getLastRequest()
 735    {
 736        return $this->last_request;
 737    }
 738
 739    /**
 740     * Get the last HTTP response received by this client
 741     *
 742     * If $config['storeresponse'] is set to false, or no response was
 743     * stored yet, will return null
 744     *
 745     * @return Zend_Http_Response or null if none
 746     */
 747    public function getLastResponse()
 748    {
 749        return $this->last_response;
 750    }
 751
 752    /**
 753     * Load the connection adapter
 754     *
 755     * While this method is not called more than one for a client, it is
 756     * seperated from ->request() to preserve logic and readability
 757     *
 758     * @param Zend_Http_Client_Adapter_Interface|string $adapter
 759     * @return null
 760     * @throws Zend_Http_Client_Exception
 761     */
 762    public function setAdapter($adapter)
 763    {
 764        if (is_string($adapter)) {
 765            try {
 766                Zend_Loader::loadClass($adapter);
 767            } catch (Zend_Exception $e) {
 768                /** @see Zend_Http_Client_Exception */
 769                require_once 'Zend/Http/Client/Exception.php';
 770                throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}");
 771            }
 772
 773            $adapter = new $adapter;
 774        }
 775
 776        if (! $adapter instanceof Zend_Http_Client_Adapter_Interface) {
 777            /** @see Zend_Http_Client_Exception */
 778            require_once 'Zend/Http/Client/Exception.php';
 779            throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
 780        }
 781
 782        $this->adapter = $adapter;
 783        $config = $this->config;
 784        unset($config['adapter']);
 785        $this->adapter->setConfig($config);
 786    }
 787
 788    /**
 789     * Send the HTTP request and return an HTTP response object
 790     *
 791     * @param string $method
 792     * @return Zend_Http_Response
 793     * @throws Zend_Http_Client_Exception
 794     */
 795    public function request($method = null)
 796    {
 797        if (! $this->uri instanceof Zend_Uri_Http) {
 798            /** @see Zend_Http_Client_Exception */
 799            require_once 'Zend/Http/Client/Exception.php';
 800            throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
 801        }
 802
 803        if ($method) $this->setMethod($method);
 804        $this->redirectCounter = 0;
 805        $response = null;
 806
 807        // Make sure the adapter is loaded
 808        if ($this->adapter == null) $this->setAdapter($this->config['adapter']);
 809
 810        // Send the first request. If redirected, continue.
 811        do {
 812            // Clone the URI and add the additional GET parameters to it
 813            $uri = clone $this->uri;
 814            if (! empty($this->paramsGet)) {
 815                $query = $uri->getQuery();
 816                   if (! empty($query)) $query .= '&';
 817                $query .= http_build_query($this->paramsGet, null, '&');
 818
 819                $uri->setQuery($query);
 820            }
 821
 822            $body = $this->_prepareBody();
 823            $headers = $this->_prepareHeaders();
 824
 825            // Open the connection, send the request and read the response
 826            $this->adapter->connect($uri->getHost(), $uri->getPort(),
 827                ($uri->getScheme() == 'https' ? true : false));
 828
 829            $this->last_request = $this->adapter->write($this->method,
 830                $uri, $this->config['httpversion'], $headers, $body);
 831
 832            $response = $this->adapter->read();
 833            if (! $response) {
 834                /** @see Zend_Http_Client_Exception */
 835                require_once 'Zend/Http/Client/Exception.php';
 836                throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
 837            }
 838
 839            $response = Zend_Http_Response::fromString($response);
 840            if ($this->config['storeresponse']) $this->last_response = $response;
 841
 842            // Load cookies into cookie jar
 843            if (isset($this->cookiejar)) $this->cookiejar->addCookiesFromResponse($response, $uri);
 844
 845            // If we got redirected, look for the Location header
 846            if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
 847
 848                // Check whether we send the exact same request again, or drop the parameters
 849                // and send a GET request
 850                if ($response->getStatus() == 303 ||
 851                   ((! $this->config['strictredirects']) && ($response->getStatus() == 302 ||
 852                       $response->getStatus() == 301))) {
 853
 854                    $this->resetParameters();
 855                    $this->setMethod(self::GET);
 856                }
 857
 858                // If we got a well formed absolute URI
 859                if (Zend_Uri_Http::check($location)) {
 860                    $this->setHeaders('host', null);
 861                    $this->setUri($location);
 862
 863                } else {
 864
 865                    // Split into path and query and set the query
 866                    if (strpos($location, '?') !== false) {
 867                        list($location, $query) = explode('?', $location, 2);
 868                    } else {
 869                        $query = '';
 870                    }
 871                    $this->uri->setQuery($query);
 872
 873                    // Else, if we got just an absolute path, set it
 874                    if(strpos($location, '/') === 0) {
 875                        $this->uri->setPath($location);
 876
 877                        // Else, assume we have a relative path
 878                    } else {
 879                        // Get the current path directory, removing any trailing slashes
 880                        $path = $this->uri->getPath();
 881                        $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
 882                        $this->uri->setPath($path . '/' . $location);
 883                    }
 884                }
 885                ++$this->redirectCounter;
 886
 887            } else {
 888                // If we didn't get any location, stop redirecting
 889                break;
 890            }
 891
 892        } while ($this->redirectCounter < $this->config['maxredirects']);
 893
 894        return $response;
 895    }
 896
 897    /**
 898     * Prepare the request headers
 899     *
 900     * @return array
 901     */
 902    protected function _prepareHeaders()
 903    {
 904        $headers = array();
 905
 906        // Set the host header
 907        if (! isset($this->headers['host'])) {
 908            $host = $this->uri->getHost();
 909
 910            // If the port is not default, add it
 911            if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) ||
 912                  ($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) {
 913                $host .= ':' . $this->uri->getPort();
 914            }
 915
 916            $headers[] = "Host: {$host}";
 917        }
 918
 919        // Set the connection header
 920        if (! isset($this->headers['connection'])) {
 921            if (! $this->config['keepalive']) $headers[] = "Connection: close";
 922        }
 923
 924        // Set the Accept-encoding header if not set - depending on whether
 925        // zlib is available or not.
 926        if (! isset($this->headers['accept-encoding'])) {
 927        	if (function_exists('gzinflate')) {
 928        		$headers[] = 'Accept-encoding: gzip, deflate';
 929        	} else {
 930        		$headers[] = 'Accept-encoding: identity';
 931        	}
 932        }
 933        
 934        // Set the content-type header
 935        if ($this->method == self::POST &&
 936           (! isset($this->headers['content-type']) && isset($this->enctype))) {
 937
 938            $headers[] = "Content-type: {$this->enctype}";
 939        }
 940        
 941        // Set the user agent header
 942        if (! isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
 943            $headers[] = "User-agent: {$this->config['useragent']}";
 944        }
 945
 946        // Set HTTP authentication if needed
 947        if (is_array($this->auth)) {
 948            $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
 949            $headers[] = "Authorization: {$auth}";
 950        }
 951
 952        // Load cookies from cookie jar
 953        if (isset($this->cookiejar)) {
 954            $cookstr = $this->cookiejar->getMatchingCookies($this->uri,
 955                true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
 956
 957            if ($cookstr) $headers[] = "Cookie: {$cookstr}";
 958        }
 959
 960        // Add all other user defined headers
 961        foreach ($this->headers as $header) {
 962        	list($name, $value) = $header;
 963            if (is_array($value))
 964                $value = implode(', ', $value);
 965
 966            $headers[] = "$name: $value";
 967        }
 968
 969        return $headers;
 970    }
 971
 972    /**
 973     * Prepare the request body (for POST and PUT requests)
 974     *
 975     * @return string
 976     * @throws Zend_Http_Client_Exception
 977     */
 978    protected function _prepareBody()
 979    {
 980        // According to RFC2616, a TRACE request should not have a body.
 981        if ($this->method == self::TRACE) {
 982            return '';
 983        }
 984
 985        // If we have raw_post_data set, just use it as the body.
 986        if (isset($this->raw_post_data)) {
 987            $this->setHeaders('Content-length', strlen($this->raw_post_data));
 988            return $this->raw_post_data;
 989        }
 990
 991        $body = '';
 992
 993        // If we have files to upload, force enctype to multipart/form-data
 994        if (count ($this->files) > 0) $this->setEncType(self::ENC_FORMDATA);
 995
 996        // If we have POST parameters or files, encode and add them to the body
 997        if (count($this->paramsPost) > 0 || count($this->files) > 0) {
 998            switch($this->enctype) {
 999                case self::ENC_FORMDATA:
1000                    // Encode body as multipart/form-data
1001                    $boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
1002                    $this->setHeaders('Content-type', self::ENC_FORMDATA . "; boundary={$boundary}");
1003
1004                    // Get POST parameters and encode them
1005                    $params = $this->_getParametersRecursive($this->paramsPost);
1006                    foreach ($params as $pp) {
1007                        $body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
1008                    }
1009
1010                    // Encode files
1011                    foreach ($this->files as $name => $file) {
1012                        $fhead = array('Content-type' => $file[1]);
1013                        $body .= self::encodeFormData($boundary, $name, $file[2], $file[0], $fhead);
1014                    }
1015
1016                    $body .= "--{$boundary}--\r\n";
1017                    break;
1018
1019                case self::ENC_URLENCODED:
1020                    // Encode body as application/x-www-form-urlencoded
1021                    $this->setHeaders('Content-type', self::ENC_URLENCODED);
1022                    $body = http_build_query($this->paramsPost, '', '&');
1023                    break;
1024
1025                default:
1026                    /** @see Zend_Http_Client_Exception */
1027                    require_once 'Zend/Http/Client/Exception.php';
1028                    throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." .
1029                        " Please use Zend_Http_Client::setRawData to send this kind of content.");
1030                    break;
1031            }
1032        }
1033        
1034        // Set the content-length if we have a body or if request is POST/PUT
1035        if ($body || $this->method == self::POST || $this->method == self::PUT) {
1036            $this->setHeaders('Content-length', strlen($body));
1037        }
1038
1039        return $body;
1040    }
1041
1042    /**
1043     * Helper method that gets a possibly multi-level parameters array (get or
1044     * post) and flattens it.
1045     *
1046     * The method returns an array of (key, value) pairs (because keys are not
1047     * necessarily unique. If one of the parameters in as array, it will also
1048     * add a [] suffix to the key.
1049     *
1050     * @param array $parray The parameters array
1051     * @param bool $urlencode Whether to urlencode the name and value
1052     * @return array
1053     */
1054    protected function _getParametersRecursive($parray, $urlencode = false)
1055    {
1056        if (! is_array($parray)) return $parray;
1057        $parameters = array();
1058
1059        foreach ($parray as $name => $value) {
1060            if ($urlencode) $name = urlencode($name);
1061
1062            // If $value is an array, iterate over it
1063            if (is_array($value)) {
1064                $name .= ($urlencode ? '%5B%5D' : '[]');
1065                foreach ($value as $subval) {
1066                    if ($urlencode) $subval = urlencode($subval);
1067                    $parameters[] = array($name, $subval);
1068                }
1069            } else {
1070                if ($urlencode) $value = urlencode($value);
1071                $parameters[] = array($name, $value);
1072            }
1073        }
1074
1075        return $parameters;
1076    }
1077    
1078    /**
1079     * Attempt to detect the MIME type of a file using available extensions
1080     * 
1081     * This method will try to detect the MIME type of a file. If the fileinfo
1082     * extension is available, it will be used. If not, the mime_magic 
1083     * extension which is deprected but is still available in many PHP setups
1084     * will be tried. 
1085     * 
1086     * If neither extension is available, the default application/octet-stream
1087     * MIME type will be returned
1088     *
1089     * @param  string $file File path
1090     * @return string       MIME type
1091     */
1092    protected function _detectFileMimeType($file)
1093    {
1094        $type = null;
1095        
1096        // First try with fileinfo functions
1097        if (function_exists('finfo_open')) {
1098            if (self::$_fileInfoDb === null) {
1099                self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
1100            }
1101            
1102            if (self::$_fileInfoDb) { 
1103                $type = finfo_file(self::$_fileInfoDb, $file);
1104            }
1105            
1106        } elseif (function_exists('mime_content_type')) {
1107            $type = mime_content_type($file);
1108        }
1109        
1110        // Fallback to the default application/octet-stream
1111        if (! $type) {
1112            $type = 'application/octet-stream';
1113        }
1114        
1115        return $type;
1116    }
1117
1118    /**
1119     * Encode data to a multipart/form-data part suitable for a POST request.
1120     *
1121     * @param string $boundary
1122     * @param string $name
1123     * @param mixed $value
1124     * @param string $filename
1125     * @param array $headers Associative array of optional headers @example ("Content-transfer-encoding" => "binary")
1126     * @return string
1127     */
1128    public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
1129        $ret = "--{$boundary}\r\n" .
1130            'Content-disposition: form-data; name="' . $name .'"';
1131
1132        if ($filename) $ret .= '; filename="' . $filename . '"';
1133        $ret .= "\r\n";
1134
1135        foreach ($headers as $hname => $hvalue) {
1136            $ret .= "{$hname}: {$hvalue}\r\n";
1137        }
1138        $ret .= "\r\n";
1139
1140        $ret .= "{$value}\r\n";
1141
1142        return $ret;
1143    }
1144
1145    /**
1146     * Create a HTTP authentication "Authorization:" header according to the
1147     * specified user, password and authentication method.
1148     *
1149     * @see http://www.faqs.org/rfcs/rfc2617.html
1150     * @param string $user
1151     * @param string $password
1152     * @param string $type
1153     * @return string
1154     * @throws Zend_Http_Client_Exception
1155     */
1156    public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
1157    {
1158        $authHeader = null;
1159
1160        switch ($type) {
1161            case self::AUTH_BASIC:
1162                // In basic authentication, the user name cannot contain ":"
1163                if (strpos($user, ':') !== false) {
1164                    /** @see Zend_Http_Client_Exception */
1165                    require_once 'Zend/Http/Client/Exception.php';
1166                    throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
1167                }
1168
1169                $authHeader = 'Basic ' . base64_encode($user . ':' . $password);
1170                break;
1171
1172            //case self::AUTH_DIGEST:
1173                /**
1174                 * @todo Implement digest authentication
1175                 */
1176            //    break;
1177
1178            default:
1179                /** @see Zend_Http_Client_Exception */
1180                require_once 'Zend/Http/Client/Exception.php';
1181                throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");
1182        }
1183
1184        return $authHeader;
1185    }
1186}