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