PageRenderTime 726ms CodeModel.GetById 71ms app.highlight 407ms RepoModel.GetById 132ms app.codeStats 2ms

/library/Zend/Http/Client.php

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