]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/HTTP/Request.php
Merge branch '0.7.x' into 0.8.x
[quix0rs-gnu-social.git] / extlib / HTTP / Request.php
1 <?php\r
2 /**\r
3  * Class for performing HTTP requests\r
4  *\r
5  * PHP versions 4 and 5\r
6  *\r
7  * LICENSE:\r
8  *\r
9  * Copyright (c) 2002-2007, Richard Heyes\r
10  * All rights reserved.\r
11  *\r
12  * Redistribution and use in source and binary forms, with or without\r
13  * modification, are permitted provided that the following conditions\r
14  * are met:\r
15  *\r
16  * o Redistributions of source code must retain the above copyright\r
17  *   notice, this list of conditions and the following disclaimer.\r
18  * o Redistributions in binary form must reproduce the above copyright\r
19  *   notice, this list of conditions and the following disclaimer in the\r
20  *   documentation and/or other materials provided with the distribution.\r
21  * o The names of the authors may not be used to endorse or promote\r
22  *   products derived from this software without specific prior written\r
23  *   permission.\r
24  *\r
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
26  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
27  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
28  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
29  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
30  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
31  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
35  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
36  *\r
37  * @category    HTTP\r
38  * @package     HTTP_Request\r
39  * @author      Richard Heyes <richard@phpguru.org>\r
40  * @author      Alexey Borzov <avb@php.net>\r
41  * @copyright   2002-2007 Richard Heyes\r
42  * @license     http://opensource.org/licenses/bsd-license.php New BSD License\r
43  * @version     CVS: $Id: Request.php,v 1.63 2008/10/11 11:07:10 avb Exp $\r
44  * @link        http://pear.php.net/package/HTTP_Request/\r
45  */\r
46 \r
47 /**\r
48  * PEAR and PEAR_Error classes (for error handling)\r
49  */\r
50 require_once 'PEAR.php';\r
51 /**\r
52  * Socket class\r
53  */\r
54 require_once 'Net/Socket.php';\r
55 /**\r
56  * URL handling class\r
57  */\r
58 require_once 'Net/URL.php';\r
59 \r
60 /**#@+\r
61  * Constants for HTTP request methods\r
62  */\r
63 define('HTTP_REQUEST_METHOD_GET',     'GET',     true);\r
64 define('HTTP_REQUEST_METHOD_HEAD',    'HEAD',    true);\r
65 define('HTTP_REQUEST_METHOD_POST',    'POST',    true);\r
66 define('HTTP_REQUEST_METHOD_PUT',     'PUT',     true);\r
67 define('HTTP_REQUEST_METHOD_DELETE',  'DELETE',  true);\r
68 define('HTTP_REQUEST_METHOD_OPTIONS', 'OPTIONS', true);\r
69 define('HTTP_REQUEST_METHOD_TRACE',   'TRACE',   true);\r
70 /**#@-*/\r
71 \r
72 /**#@+\r
73  * Constants for HTTP request error codes\r
74  */\r
75 define('HTTP_REQUEST_ERROR_FILE',             1);\r
76 define('HTTP_REQUEST_ERROR_URL',              2);\r
77 define('HTTP_REQUEST_ERROR_PROXY',            4);\r
78 define('HTTP_REQUEST_ERROR_REDIRECTS',        8);\r
79 define('HTTP_REQUEST_ERROR_RESPONSE',        16);\r
80 define('HTTP_REQUEST_ERROR_GZIP_METHOD',     32);\r
81 define('HTTP_REQUEST_ERROR_GZIP_READ',       64);\r
82 define('HTTP_REQUEST_ERROR_GZIP_DATA',      128);\r
83 define('HTTP_REQUEST_ERROR_GZIP_CRC',       256);\r
84 /**#@-*/\r
85 \r
86 /**#@+\r
87  * Constants for HTTP protocol versions\r
88  */\r
89 define('HTTP_REQUEST_HTTP_VER_1_0', '1.0', true);\r
90 define('HTTP_REQUEST_HTTP_VER_1_1', '1.1', true);\r
91 /**#@-*/\r
92 \r
93 if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {\r
94    /**\r
95     * Whether string functions are overloaded by their mbstring equivalents\r
96     */\r
97     define('HTTP_REQUEST_MBSTRING', true);\r
98 } else {\r
99    /**\r
100     * @ignore\r
101     */\r
102     define('HTTP_REQUEST_MBSTRING', false);\r
103 }\r
104 \r
105 /**\r
106  * Class for performing HTTP requests\r
107  *\r
108  * Simple example (fetches yahoo.com and displays it):\r
109  * <code>\r
110  * $a = &new HTTP_Request('http://www.yahoo.com/');\r
111  * $a->sendRequest();\r
112  * echo $a->getResponseBody();\r
113  * </code>\r
114  *\r
115  * @category    HTTP\r
116  * @package     HTTP_Request\r
117  * @author      Richard Heyes <richard@phpguru.org>\r
118  * @author      Alexey Borzov <avb@php.net>\r
119  * @version     Release: 1.4.4\r
120  */\r
121 class HTTP_Request\r
122 {\r
123    /**#@+\r
124     * @access private\r
125     */\r
126     /**\r
127     * Instance of Net_URL\r
128     * @var Net_URL\r
129     */\r
130     var $_url;\r
131 \r
132     /**\r
133     * Type of request\r
134     * @var string\r
135     */\r
136     var $_method;\r
137 \r
138     /**\r
139     * HTTP Version\r
140     * @var string\r
141     */\r
142     var $_http;\r
143 \r
144     /**\r
145     * Request headers\r
146     * @var array\r
147     */\r
148     var $_requestHeaders;\r
149 \r
150     /**\r
151     * Basic Auth Username\r
152     * @var string\r
153     */\r
154     var $_user;\r
155 \r
156     /**\r
157     * Basic Auth Password\r
158     * @var string\r
159     */\r
160     var $_pass;\r
161 \r
162     /**\r
163     * Socket object\r
164     * @var Net_Socket\r
165     */\r
166     var $_sock;\r
167 \r
168     /**\r
169     * Proxy server\r
170     * @var string\r
171     */\r
172     var $_proxy_host;\r
173 \r
174     /**\r
175     * Proxy port\r
176     * @var integer\r
177     */\r
178     var $_proxy_port;\r
179 \r
180     /**\r
181     * Proxy username\r
182     * @var string\r
183     */\r
184     var $_proxy_user;\r
185 \r
186     /**\r
187     * Proxy password\r
188     * @var string\r
189     */\r
190     var $_proxy_pass;\r
191 \r
192     /**\r
193     * Post data\r
194     * @var array\r
195     */\r
196     var $_postData;\r
197 \r
198    /**\r
199     * Request body\r
200     * @var string\r
201     */\r
202     var $_body;\r
203 \r
204    /**\r
205     * A list of methods that MUST NOT have a request body, per RFC 2616\r
206     * @var array\r
207     */\r
208     var $_bodyDisallowed = array('TRACE');\r
209 \r
210    /**\r
211     * Methods having defined semantics for request body\r
212     *\r
213     * Content-Length header (indicating that the body follows, section 4.3 of\r
214     * RFC 2616) will be sent for these methods even if no body was added\r
215     *\r
216     * @var array\r
217     */\r
218     var $_bodyRequired = array('POST', 'PUT');\r
219 \r
220    /**\r
221     * Files to post\r
222     * @var array\r
223     */\r
224     var $_postFiles = array();\r
225 \r
226     /**\r
227     * Connection timeout.\r
228     * @var float\r
229     */\r
230     var $_timeout;\r
231 \r
232     /**\r
233     * HTTP_Response object\r
234     * @var HTTP_Response\r
235     */\r
236     var $_response;\r
237 \r
238     /**\r
239     * Whether to allow redirects\r
240     * @var boolean\r
241     */\r
242     var $_allowRedirects;\r
243 \r
244     /**\r
245     * Maximum redirects allowed\r
246     * @var integer\r
247     */\r
248     var $_maxRedirects;\r
249 \r
250     /**\r
251     * Current number of redirects\r
252     * @var integer\r
253     */\r
254     var $_redirects;\r
255 \r
256    /**\r
257     * Whether to append brackets [] to array variables\r
258     * @var bool\r
259     */\r
260     var $_useBrackets = true;\r
261 \r
262    /**\r
263     * Attached listeners\r
264     * @var array\r
265     */\r
266     var $_listeners = array();\r
267 \r
268    /**\r
269     * Whether to save response body in response object property\r
270     * @var bool\r
271     */\r
272     var $_saveBody = true;\r
273 \r
274    /**\r
275     * Timeout for reading from socket (array(seconds, microseconds))\r
276     * @var array\r
277     */\r
278     var $_readTimeout = null;\r
279 \r
280    /**\r
281     * Options to pass to Net_Socket::connect. See stream_context_create\r
282     * @var array\r
283     */\r
284     var $_socketOptions = null;\r
285    /**#@-*/\r
286 \r
287     /**\r
288     * Constructor\r
289     *\r
290     * Sets up the object\r
291     * @param    string  The url to fetch/access\r
292     * @param    array   Associative array of parameters which can have the following keys:\r
293     * <ul>\r
294     *   <li>method         - Method to use, GET, POST etc (string)</li>\r
295     *   <li>http           - HTTP Version to use, 1.0 or 1.1 (string)</li>\r
296     *   <li>user           - Basic Auth username (string)</li>\r
297     *   <li>pass           - Basic Auth password (string)</li>\r
298     *   <li>proxy_host     - Proxy server host (string)</li>\r
299     *   <li>proxy_port     - Proxy server port (integer)</li>\r
300     *   <li>proxy_user     - Proxy auth username (string)</li>\r
301     *   <li>proxy_pass     - Proxy auth password (string)</li>\r
302     *   <li>timeout        - Connection timeout in seconds (float)</li>\r
303     *   <li>allowRedirects - Whether to follow redirects or not (bool)</li>\r
304     *   <li>maxRedirects   - Max number of redirects to follow (integer)</li>\r
305     *   <li>useBrackets    - Whether to append [] to array variable names (bool)</li>\r
306     *   <li>saveBody       - Whether to save response body in response object property (bool)</li>\r
307     *   <li>readTimeout    - Timeout for reading / writing data over the socket (array (seconds, microseconds))</li>\r
308     *   <li>socketOptions  - Options to pass to Net_Socket object (array)</li>\r
309     * </ul>\r
310     * @access public\r
311     */\r
312     function HTTP_Request($url = '', $params = array())\r
313     {\r
314         $this->_method         =  HTTP_REQUEST_METHOD_GET;\r
315         $this->_http           =  HTTP_REQUEST_HTTP_VER_1_1;\r
316         $this->_requestHeaders = array();\r
317         $this->_postData       = array();\r
318         $this->_body           = null;\r
319 \r
320         $this->_user = null;\r
321         $this->_pass = null;\r
322 \r
323         $this->_proxy_host = null;\r
324         $this->_proxy_port = null;\r
325         $this->_proxy_user = null;\r
326         $this->_proxy_pass = null;\r
327 \r
328         $this->_allowRedirects = false;\r
329         $this->_maxRedirects   = 3;\r
330         $this->_redirects      = 0;\r
331 \r
332         $this->_timeout  = null;\r
333         $this->_response = null;\r
334 \r
335         foreach ($params as $key => $value) {\r
336             $this->{'_' . $key} = $value;\r
337         }\r
338 \r
339         if (!empty($url)) {\r
340             $this->setURL($url);\r
341         }\r
342 \r
343         // Default useragent\r
344         $this->addHeader('User-Agent', 'PEAR HTTP_Request class ( http://pear.php.net/ )');\r
345 \r
346         // We don't do keep-alives by default\r
347         $this->addHeader('Connection', 'close');\r
348 \r
349         // Basic authentication\r
350         if (!empty($this->_user)) {\r
351             $this->addHeader('Authorization', 'Basic ' . base64_encode($this->_user . ':' . $this->_pass));\r
352         }\r
353 \r
354         // Proxy authentication (see bug #5913)\r
355         if (!empty($this->_proxy_user)) {\r
356             $this->addHeader('Proxy-Authorization', 'Basic ' . base64_encode($this->_proxy_user . ':' . $this->_proxy_pass));\r
357         }\r
358 \r
359         // Use gzip encoding if possible\r
360         if (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http && extension_loaded('zlib')) {\r
361             $this->addHeader('Accept-Encoding', 'gzip');\r
362         }\r
363     }\r
364 \r
365     /**\r
366     * Generates a Host header for HTTP/1.1 requests\r
367     *\r
368     * @access private\r
369     * @return string\r
370     */\r
371     function _generateHostHeader()\r
372     {\r
373         if ($this->_url->port != 80 AND strcasecmp($this->_url->protocol, 'http') == 0) {\r
374             $host = $this->_url->host . ':' . $this->_url->port;\r
375 \r
376         } elseif ($this->_url->port != 443 AND strcasecmp($this->_url->protocol, 'https') == 0) {\r
377             $host = $this->_url->host . ':' . $this->_url->port;\r
378 \r
379         } elseif ($this->_url->port == 443 AND strcasecmp($this->_url->protocol, 'https') == 0 AND strpos($this->_url->url, ':443') !== false) {\r
380             $host = $this->_url->host . ':' . $this->_url->port;\r
381 \r
382         } else {\r
383             $host = $this->_url->host;\r
384         }\r
385 \r
386         return $host;\r
387     }\r
388 \r
389     /**\r
390     * Resets the object to its initial state (DEPRECATED).\r
391     * Takes the same parameters as the constructor.\r
392     *\r
393     * @param  string $url    The url to be requested\r
394     * @param  array  $params Associative array of parameters\r
395     *                        (see constructor for details)\r
396     * @access public\r
397     * @deprecated deprecated since 1.2, call the constructor if this is necessary\r
398     */\r
399     function reset($url, $params = array())\r
400     {\r
401         $this->HTTP_Request($url, $params);\r
402     }\r
403 \r
404     /**\r
405     * Sets the URL to be requested\r
406     *\r
407     * @param  string The url to be requested\r
408     * @access public\r
409     */\r
410     function setURL($url)\r
411     {\r
412         $this->_url = &new Net_URL($url, $this->_useBrackets);\r
413 \r
414         if (!empty($this->_url->user) || !empty($this->_url->pass)) {\r
415             $this->setBasicAuth($this->_url->user, $this->_url->pass);\r
416         }\r
417 \r
418         if (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http) {\r
419             $this->addHeader('Host', $this->_generateHostHeader());\r
420         }\r
421 \r
422         // set '/' instead of empty path rather than check later (see bug #8662)\r
423         if (empty($this->_url->path)) {\r
424             $this->_url->path = '/';\r
425         }\r
426     }\r
427 \r
428    /**\r
429     * Returns the current request URL\r
430     *\r
431     * @return   string  Current request URL\r
432     * @access   public\r
433     */\r
434     function getUrl()\r
435     {\r
436         return empty($this->_url)? '': $this->_url->getUrl();\r
437     }\r
438 \r
439     /**\r
440     * Sets a proxy to be used\r
441     *\r
442     * @param string     Proxy host\r
443     * @param int        Proxy port\r
444     * @param string     Proxy username\r
445     * @param string     Proxy password\r
446     * @access public\r
447     */\r
448     function setProxy($host, $port = 8080, $user = null, $pass = null)\r
449     {\r
450         $this->_proxy_host = $host;\r
451         $this->_proxy_port = $port;\r
452         $this->_proxy_user = $user;\r
453         $this->_proxy_pass = $pass;\r
454 \r
455         if (!empty($user)) {\r
456             $this->addHeader('Proxy-Authorization', 'Basic ' . base64_encode($user . ':' . $pass));\r
457         }\r
458     }\r
459 \r
460     /**\r
461     * Sets basic authentication parameters\r
462     *\r
463     * @param string     Username\r
464     * @param string     Password\r
465     */\r
466     function setBasicAuth($user, $pass)\r
467     {\r
468         $this->_user = $user;\r
469         $this->_pass = $pass;\r
470 \r
471         $this->addHeader('Authorization', 'Basic ' . base64_encode($user . ':' . $pass));\r
472     }\r
473 \r
474     /**\r
475     * Sets the method to be used, GET, POST etc.\r
476     *\r
477     * @param string     Method to use. Use the defined constants for this\r
478     * @access public\r
479     */\r
480     function setMethod($method)\r
481     {\r
482         $this->_method = $method;\r
483     }\r
484 \r
485     /**\r
486     * Sets the HTTP version to use, 1.0 or 1.1\r
487     *\r
488     * @param string     Version to use. Use the defined constants for this\r
489     * @access public\r
490     */\r
491     function setHttpVer($http)\r
492     {\r
493         $this->_http = $http;\r
494     }\r
495 \r
496     /**\r
497     * Adds a request header\r
498     *\r
499     * @param string     Header name\r
500     * @param string     Header value\r
501     * @access public\r
502     */\r
503     function addHeader($name, $value)\r
504     {\r
505         $this->_requestHeaders[strtolower($name)] = $value;\r
506     }\r
507 \r
508     /**\r
509     * Removes a request header\r
510     *\r
511     * @param string     Header name to remove\r
512     * @access public\r
513     */\r
514     function removeHeader($name)\r
515     {\r
516         if (isset($this->_requestHeaders[strtolower($name)])) {\r
517             unset($this->_requestHeaders[strtolower($name)]);\r
518         }\r
519     }\r
520 \r
521     /**\r
522     * Adds a querystring parameter\r
523     *\r
524     * @param string     Querystring parameter name\r
525     * @param string     Querystring parameter value\r
526     * @param bool       Whether the value is already urlencoded or not, default = not\r
527     * @access public\r
528     */\r
529     function addQueryString($name, $value, $preencoded = false)\r
530     {\r
531         $this->_url->addQueryString($name, $value, $preencoded);\r
532     }\r
533 \r
534     /**\r
535     * Sets the querystring to literally what you supply\r
536     *\r
537     * @param string     The querystring data. Should be of the format foo=bar&x=y etc\r
538     * @param bool       Whether data is already urlencoded or not, default = already encoded\r
539     * @access public\r
540     */\r
541     function addRawQueryString($querystring, $preencoded = true)\r
542     {\r
543         $this->_url->addRawQueryString($querystring, $preencoded);\r
544     }\r
545 \r
546     /**\r
547     * Adds postdata items\r
548     *\r
549     * @param string     Post data name\r
550     * @param string     Post data value\r
551     * @param bool       Whether data is already urlencoded or not, default = not\r
552     * @access public\r
553     */\r
554     function addPostData($name, $value, $preencoded = false)\r
555     {\r
556         if ($preencoded) {\r
557             $this->_postData[$name] = $value;\r
558         } else {\r
559             $this->_postData[$name] = $this->_arrayMapRecursive('urlencode', $value);\r
560         }\r
561     }\r
562 \r
563    /**\r
564     * Recursively applies the callback function to the value\r
565     *\r
566     * @param    mixed   Callback function\r
567     * @param    mixed   Value to process\r
568     * @access   private\r
569     * @return   mixed   Processed value\r
570     */\r
571     function _arrayMapRecursive($callback, $value)\r
572     {\r
573         if (!is_array($value)) {\r
574             return call_user_func($callback, $value);\r
575         } else {\r
576             $map = array();\r
577             foreach ($value as $k => $v) {\r
578                 $map[$k] = $this->_arrayMapRecursive($callback, $v);\r
579             }\r
580             return $map;\r
581         }\r
582     }\r
583 \r
584    /**\r
585     * Adds a file to form-based file upload\r
586     *\r
587     * Used to emulate file upload via a HTML form. The method also sets\r
588     * Content-Type of HTTP request to 'multipart/form-data'.\r
589     *\r
590     * If you just want to send the contents of a file as the body of HTTP\r
591     * request you should use setBody() method.\r
592     *\r
593     * @access public\r
594     * @param  string    name of file-upload field\r
595     * @param  mixed     file name(s)\r
596     * @param  mixed     content-type(s) of file(s) being uploaded\r
597     * @return bool      true on success\r
598     * @throws PEAR_Error\r
599     */\r
600     function addFile($inputName, $fileName, $contentType = 'application/octet-stream')\r
601     {\r
602         if (!is_array($fileName) && !is_readable($fileName)) {\r
603             return PEAR::raiseError("File '{$fileName}' is not readable", HTTP_REQUEST_ERROR_FILE);\r
604         } elseif (is_array($fileName)) {\r
605             foreach ($fileName as $name) {\r
606                 if (!is_readable($name)) {\r
607                     return PEAR::raiseError("File '{$name}' is not readable", HTTP_REQUEST_ERROR_FILE);\r
608                 }\r
609             }\r
610         }\r
611         $this->addHeader('Content-Type', 'multipart/form-data');\r
612         $this->_postFiles[$inputName] = array(\r
613             'name' => $fileName,\r
614             'type' => $contentType\r
615         );\r
616         return true;\r
617     }\r
618 \r
619     /**\r
620     * Adds raw postdata (DEPRECATED)\r
621     *\r
622     * @param string     The data\r
623     * @param bool       Whether data is preencoded or not, default = already encoded\r
624     * @access public\r
625     * @deprecated       deprecated since 1.3.0, method setBody() should be used instead\r
626     */\r
627     function addRawPostData($postdata, $preencoded = true)\r
628     {\r
629         $this->_body = $preencoded ? $postdata : urlencode($postdata);\r
630     }\r
631 \r
632    /**\r
633     * Sets the request body (for POST, PUT and similar requests)\r
634     *\r
635     * @param    string  Request body\r
636     * @access   public\r
637     */\r
638     function setBody($body)\r
639     {\r
640         $this->_body = $body;\r
641     }\r
642 \r
643     /**\r
644     * Clears any postdata that has been added (DEPRECATED).\r
645     *\r
646     * Useful for multiple request scenarios.\r
647     *\r
648     * @access public\r
649     * @deprecated deprecated since 1.2\r
650     */\r
651     function clearPostData()\r
652     {\r
653         $this->_postData = null;\r
654     }\r
655 \r
656     /**\r
657     * Appends a cookie to "Cookie:" header\r
658     *\r
659     * @param string $name cookie name\r
660     * @param string $value cookie value\r
661     * @access public\r
662     */\r
663     function addCookie($name, $value)\r
664     {\r
665         $cookies = isset($this->_requestHeaders['cookie']) ? $this->_requestHeaders['cookie']. '; ' : '';\r
666         $this->addHeader('Cookie', $cookies . $name . '=' . $value);\r
667     }\r
668 \r
669     /**\r
670     * Clears any cookies that have been added (DEPRECATED).\r
671     *\r
672     * Useful for multiple request scenarios\r
673     *\r
674     * @access public\r
675     * @deprecated deprecated since 1.2\r
676     */\r
677     function clearCookies()\r
678     {\r
679         $this->removeHeader('Cookie');\r
680     }\r
681 \r
682     /**\r
683     * Sends the request\r
684     *\r
685     * @access public\r
686     * @param  bool   Whether to store response body in Response object property,\r
687     *                set this to false if downloading a LARGE file and using a Listener\r
688     * @return mixed  PEAR error on error, true otherwise\r
689     */\r
690     function sendRequest($saveBody = true)\r
691     {\r
692         if (!is_a($this->_url, 'Net_URL')) {\r
693             return PEAR::raiseError('No URL given', HTTP_REQUEST_ERROR_URL);\r
694         }\r
695 \r
696         $host = isset($this->_proxy_host) ? $this->_proxy_host : $this->_url->host;\r
697         $port = isset($this->_proxy_port) ? $this->_proxy_port : $this->_url->port;\r
698 \r
699         if (strcasecmp($this->_url->protocol, 'https') == 0) {\r
700             // Bug #14127, don't try connecting to HTTPS sites without OpenSSL\r
701             if (version_compare(PHP_VERSION, '4.3.0', '<') || !extension_loaded('openssl')) {\r
702                 return PEAR::raiseError('Need PHP 4.3.0 or later with OpenSSL support for https:// requests',\r
703                                         HTTP_REQUEST_ERROR_URL);\r
704             } elseif (isset($this->_proxy_host)) {\r
705                 return PEAR::raiseError('HTTPS proxies are not supported', HTTP_REQUEST_ERROR_PROXY);\r
706             }\r
707             $host = 'ssl://' . $host;\r
708         }\r
709 \r
710         // magic quotes may fuck up file uploads and chunked response processing\r
711         $magicQuotes = ini_get('magic_quotes_runtime');\r
712         ini_set('magic_quotes_runtime', false);\r
713 \r
714         // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive\r
715         // connection token to a proxy server...\r
716         if (isset($this->_proxy_host) && !empty($this->_requestHeaders['connection']) &&\r
717             'Keep-Alive' == $this->_requestHeaders['connection'])\r
718         {\r
719             $this->removeHeader('connection');\r
720         }\r
721 \r
722         $keepAlive = (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http && empty($this->_requestHeaders['connection'])) ||\r
723                      (!empty($this->_requestHeaders['connection']) && 'Keep-Alive' == $this->_requestHeaders['connection']);\r
724         $sockets   = &PEAR::getStaticProperty('HTTP_Request', 'sockets');\r
725         $sockKey   = $host . ':' . $port;\r
726         unset($this->_sock);\r
727 \r
728         // There is a connected socket in the "static" property?\r
729         if ($keepAlive && !empty($sockets[$sockKey]) &&\r
730             !empty($sockets[$sockKey]->fp))\r
731         {\r
732             $this->_sock =& $sockets[$sockKey];\r
733             $err = null;\r
734         } else {\r
735             $this->_notify('connect');\r
736             $this->_sock =& new Net_Socket();\r
737             $err = $this->_sock->connect($host, $port, null, $this->_timeout, $this->_socketOptions);\r
738         }\r
739         PEAR::isError($err) or $err = $this->_sock->write($this->_buildRequest());\r
740 \r
741         if (!PEAR::isError($err)) {\r
742             if (!empty($this->_readTimeout)) {\r
743                 $this->_sock->setTimeout($this->_readTimeout[0], $this->_readTimeout[1]);\r
744             }\r
745 \r
746             $this->_notify('sentRequest');\r
747 \r
748             // Read the response\r
749             $this->_response = &new HTTP_Response($this->_sock, $this->_listeners);\r
750             $err = $this->_response->process(\r
751                 $this->_saveBody && $saveBody,\r
752                 HTTP_REQUEST_METHOD_HEAD != $this->_method\r
753             );\r
754 \r
755             if ($keepAlive) {\r
756                 $keepAlive = (isset($this->_response->_headers['content-length'])\r
757                               || (isset($this->_response->_headers['transfer-encoding'])\r
758                                   && strtolower($this->_response->_headers['transfer-encoding']) == 'chunked'));\r
759                 if ($keepAlive) {\r
760                     if (isset($this->_response->_headers['connection'])) {\r
761                         $keepAlive = strtolower($this->_response->_headers['connection']) == 'keep-alive';\r
762                     } else {\r
763                         $keepAlive = 'HTTP/'.HTTP_REQUEST_HTTP_VER_1_1 == $this->_response->_protocol;\r
764                     }\r
765                 }\r
766             }\r
767         }\r
768 \r
769         ini_set('magic_quotes_runtime', $magicQuotes);\r
770 \r
771         if (PEAR::isError($err)) {\r
772             return $err;\r
773         }\r
774 \r
775         if (!$keepAlive) {\r
776             $this->disconnect();\r
777         // Store the connected socket in "static" property\r
778         } elseif (empty($sockets[$sockKey]) || empty($sockets[$sockKey]->fp)) {\r
779             $sockets[$sockKey] =& $this->_sock;\r
780         }\r
781 \r
782         // Check for redirection\r
783         if (    $this->_allowRedirects\r
784             AND $this->_redirects <= $this->_maxRedirects\r
785             AND $this->getResponseCode() > 300\r
786             AND $this->getResponseCode() < 399\r
787             AND !empty($this->_response->_headers['location'])) {\r
788 \r
789 \r
790             $redirect = $this->_response->_headers['location'];\r
791 \r
792             // Absolute URL\r
793             if (preg_match('/^https?:\/\//i', $redirect)) {\r
794                 $this->_url = &new Net_URL($redirect);\r
795                 $this->addHeader('Host', $this->_generateHostHeader());\r
796             // Absolute path\r
797             } elseif ($redirect{0} == '/') {\r
798                 $this->_url->path = $redirect;\r
799 \r
800             // Relative path\r
801             } elseif (substr($redirect, 0, 3) == '../' OR substr($redirect, 0, 2) == './') {\r
802                 if (substr($this->_url->path, -1) == '/') {\r
803                     $redirect = $this->_url->path . $redirect;\r
804                 } else {\r
805                     $redirect = dirname($this->_url->path) . '/' . $redirect;\r
806                 }\r
807                 $redirect = Net_URL::resolvePath($redirect);\r
808                 $this->_url->path = $redirect;\r
809 \r
810             // Filename, no path\r
811             } else {\r
812                 if (substr($this->_url->path, -1) == '/') {\r
813                     $redirect = $this->_url->path . $redirect;\r
814                 } else {\r
815                     $redirect = dirname($this->_url->path) . '/' . $redirect;\r
816                 }\r
817                 $this->_url->path = $redirect;\r
818             }\r
819 \r
820             $this->_redirects++;\r
821             return $this->sendRequest($saveBody);\r
822 \r
823         // Too many redirects\r
824         } elseif ($this->_allowRedirects AND $this->_redirects > $this->_maxRedirects) {\r
825             return PEAR::raiseError('Too many redirects', HTTP_REQUEST_ERROR_REDIRECTS);\r
826         }\r
827 \r
828         return true;\r
829     }\r
830 \r
831     /**\r
832      * Disconnect the socket, if connected. Only useful if using Keep-Alive.\r
833      *\r
834      * @access public\r
835      */\r
836     function disconnect()\r
837     {\r
838         if (!empty($this->_sock) && !empty($this->_sock->fp)) {\r
839             $this->_notify('disconnect');\r
840             $this->_sock->disconnect();\r
841         }\r
842     }\r
843 \r
844     /**\r
845     * Returns the response code\r
846     *\r
847     * @access public\r
848     * @return mixed     Response code, false if not set\r
849     */\r
850     function getResponseCode()\r
851     {\r
852         return isset($this->_response->_code) ? $this->_response->_code : false;\r
853     }\r
854 \r
855     /**\r
856     * Returns the response reason phrase\r
857     *\r
858     * @access public\r
859     * @return mixed     Response reason phrase, false if not set\r
860     */\r
861     function getResponseReason()\r
862     {\r
863         return isset($this->_response->_reason) ? $this->_response->_reason : false;\r
864     }\r
865 \r
866     /**\r
867     * Returns either the named header or all if no name given\r
868     *\r
869     * @access public\r
870     * @param string     The header name to return, do not set to get all headers\r
871     * @return mixed     either the value of $headername (false if header is not present)\r
872     *                   or an array of all headers\r
873     */\r
874     function getResponseHeader($headername = null)\r
875     {\r
876         if (!isset($headername)) {\r
877             return isset($this->_response->_headers)? $this->_response->_headers: array();\r
878         } else {\r
879             $headername = strtolower($headername);\r
880             return isset($this->_response->_headers[$headername]) ? $this->_response->_headers[$headername] : false;\r
881         }\r
882     }\r
883 \r
884     /**\r
885     * Returns the body of the response\r
886     *\r
887     * @access public\r
888     * @return mixed     response body, false if not set\r
889     */\r
890     function getResponseBody()\r
891     {\r
892         return isset($this->_response->_body) ? $this->_response->_body : false;\r
893     }\r
894 \r
895     /**\r
896     * Returns cookies set in response\r
897     *\r
898     * @access public\r
899     * @return mixed     array of response cookies, false if none are present\r
900     */\r
901     function getResponseCookies()\r
902     {\r
903         return isset($this->_response->_cookies) ? $this->_response->_cookies : false;\r
904     }\r
905 \r
906     /**\r
907     * Builds the request string\r
908     *\r
909     * @access private\r
910     * @return string The request string\r
911     */\r
912     function _buildRequest()\r
913     {\r
914         $separator = ini_get('arg_separator.output');\r
915         ini_set('arg_separator.output', '&');\r
916         $querystring = ($querystring = $this->_url->getQueryString()) ? '?' . $querystring : '';\r
917         ini_set('arg_separator.output', $separator);\r
918 \r
919         $host = isset($this->_proxy_host) ? $this->_url->protocol . '://' . $this->_url->host : '';\r
920         $port = (isset($this->_proxy_host) AND $this->_url->port != 80) ? ':' . $this->_url->port : '';\r
921         $path = $this->_url->path . $querystring;\r
922         $url  = $host . $port . $path;\r
923 \r
924         if (!strlen($url)) {\r
925             $url = '/';\r
926         }\r
927 \r
928         $request = $this->_method . ' ' . $url . ' HTTP/' . $this->_http . "\r\n";\r
929 \r
930         if (in_array($this->_method, $this->_bodyDisallowed) ||\r
931             (0 == strlen($this->_body) && (HTTP_REQUEST_METHOD_POST != $this->_method ||\r
932              (empty($this->_postData) && empty($this->_postFiles)))))\r
933         {\r
934             $this->removeHeader('Content-Type');\r
935         } else {\r
936             if (empty($this->_requestHeaders['content-type'])) {\r
937                 // Add default content-type\r
938                 $this->addHeader('Content-Type', 'application/x-www-form-urlencoded');\r
939             } elseif ('multipart/form-data' == $this->_requestHeaders['content-type']) {\r
940                 $boundary = 'HTTP_Request_' . md5(uniqid('request') . microtime());\r
941                 $this->addHeader('Content-Type', 'multipart/form-data; boundary=' . $boundary);\r
942             }\r
943         }\r
944 \r
945         // Request Headers\r
946         if (!empty($this->_requestHeaders)) {\r
947             foreach ($this->_requestHeaders as $name => $value) {\r
948                 $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));\r
949                 $request      .= $canonicalName . ': ' . $value . "\r\n";\r
950             }\r
951         }\r
952 \r
953         // Method does not allow a body, simply add a final CRLF\r
954         if (in_array($this->_method, $this->_bodyDisallowed)) {\r
955 \r
956             $request .= "\r\n";\r
957 \r
958         // Post data if it's an array\r
959         } elseif (HTTP_REQUEST_METHOD_POST == $this->_method &&\r
960                   (!empty($this->_postData) || !empty($this->_postFiles))) {\r
961 \r
962             // "normal" POST request\r
963             if (!isset($boundary)) {\r
964                 $postdata = implode('&', array_map(\r
965                     create_function('$a', 'return $a[0] . \'=\' . $a[1];'),\r
966                     $this->_flattenArray('', $this->_postData)\r
967                 ));\r
968 \r
969             // multipart request, probably with file uploads\r
970             } else {\r
971                 $postdata = '';\r
972                 if (!empty($this->_postData)) {\r
973                     $flatData = $this->_flattenArray('', $this->_postData);\r
974                     foreach ($flatData as $item) {\r
975                         $postdata .= '--' . $boundary . "\r\n";\r
976                         $postdata .= 'Content-Disposition: form-data; name="' . $item[0] . '"';\r
977                         $postdata .= "\r\n\r\n" . urldecode($item[1]) . "\r\n";\r
978                     }\r
979                 }\r
980                 foreach ($this->_postFiles as $name => $value) {\r
981                     if (is_array($value['name'])) {\r
982                         $varname       = $name . ($this->_useBrackets? '[]': '');\r
983                     } else {\r
984                         $varname       = $name;\r
985                         $value['name'] = array($value['name']);\r
986                     }\r
987                     foreach ($value['name'] as $key => $filename) {\r
988                         $fp       = fopen($filename, 'r');\r
989                         $basename = basename($filename);\r
990                         $type     = is_array($value['type'])? @$value['type'][$key]: $value['type'];\r
991 \r
992                         $postdata .= '--' . $boundary . "\r\n";\r
993                         $postdata .= 'Content-Disposition: form-data; name="' . $varname . '"; filename="' . $basename . '"';\r
994                         $postdata .= "\r\nContent-Type: " . $type;\r
995                         $postdata .= "\r\n\r\n" . fread($fp, filesize($filename)) . "\r\n";\r
996                         fclose($fp);\r
997                     }\r
998                 }\r
999                 $postdata .= '--' . $boundary . "--\r\n";\r
1000             }\r
1001             $request .= 'Content-Length: ' .\r
1002                         (HTTP_REQUEST_MBSTRING? mb_strlen($postdata, 'iso-8859-1'): strlen($postdata)) .\r
1003                         "\r\n\r\n";\r
1004             $request .= $postdata;\r
1005 \r
1006         // Explicitly set request body\r
1007         } elseif (0 < strlen($this->_body)) {\r
1008 \r
1009             $request .= 'Content-Length: ' .\r
1010                         (HTTP_REQUEST_MBSTRING? mb_strlen($this->_body, 'iso-8859-1'): strlen($this->_body)) .\r
1011                         "\r\n\r\n";\r
1012             $request .= $this->_body;\r
1013 \r
1014         // No body: send a Content-Length header nonetheless (request #12900),\r
1015         // but do that only for methods that require a body (bug #14740)\r
1016         } else {\r
1017 \r
1018             if (in_array($this->_method, $this->_bodyRequired)) {\r
1019                 $request .= "Content-Length: 0\r\n";\r
1020             }\r
1021             $request .= "\r\n";\r
1022         }\r
1023 \r
1024         return $request;\r
1025     }\r
1026 \r
1027    /**\r
1028     * Helper function to change the (probably multidimensional) associative array\r
1029     * into the simple one.\r
1030     *\r
1031     * @param    string  name for item\r
1032     * @param    mixed   item's values\r
1033     * @return   array   array with the following items: array('item name', 'item value');\r
1034     * @access   private\r
1035     */\r
1036     function _flattenArray($name, $values)\r
1037     {\r
1038         if (!is_array($values)) {\r
1039             return array(array($name, $values));\r
1040         } else {\r
1041             $ret = array();\r
1042             foreach ($values as $k => $v) {\r
1043                 if (empty($name)) {\r
1044                     $newName = $k;\r
1045                 } elseif ($this->_useBrackets) {\r
1046                     $newName = $name . '[' . $k . ']';\r
1047                 } else {\r
1048                     $newName = $name;\r
1049                 }\r
1050                 $ret = array_merge($ret, $this->_flattenArray($newName, $v));\r
1051             }\r
1052             return $ret;\r
1053         }\r
1054     }\r
1055 \r
1056 \r
1057    /**\r
1058     * Adds a Listener to the list of listeners that are notified of\r
1059     * the object's events\r
1060     *\r
1061     * Events sent by HTTP_Request object\r
1062     * - 'connect': on connection to server\r
1063     * - 'sentRequest': after the request was sent\r
1064     * - 'disconnect': on disconnection from server\r
1065     *\r
1066     * Events sent by HTTP_Response object\r
1067     * - 'gotHeaders': after receiving response headers (headers are passed in $data)\r
1068     * - 'tick': on receiving a part of response body (the part is passed in $data)\r
1069     * - 'gzTick': on receiving a gzip-encoded part of response body (ditto)\r
1070     * - 'gotBody': after receiving the response body (passes the decoded body in $data if it was gzipped)\r
1071     *\r
1072     * @param    HTTP_Request_Listener   listener to attach\r
1073     * @return   boolean                 whether the listener was successfully attached\r
1074     * @access   public\r
1075     */\r
1076     function attach(&$listener)\r
1077     {\r
1078         if (!is_a($listener, 'HTTP_Request_Listener')) {\r
1079             return false;\r
1080         }\r
1081         $this->_listeners[$listener->getId()] =& $listener;\r
1082         return true;\r
1083     }\r
1084 \r
1085 \r
1086    /**\r
1087     * Removes a Listener from the list of listeners\r
1088     *\r
1089     * @param    HTTP_Request_Listener   listener to detach\r
1090     * @return   boolean                 whether the listener was successfully detached\r
1091     * @access   public\r
1092     */\r
1093     function detach(&$listener)\r
1094     {\r
1095         if (!is_a($listener, 'HTTP_Request_Listener') ||\r
1096             !isset($this->_listeners[$listener->getId()])) {\r
1097             return false;\r
1098         }\r
1099         unset($this->_listeners[$listener->getId()]);\r
1100         return true;\r
1101     }\r
1102 \r
1103 \r
1104    /**\r
1105     * Notifies all registered listeners of an event.\r
1106     *\r
1107     * @param    string  Event name\r
1108     * @param    mixed   Additional data\r
1109     * @access   private\r
1110     * @see      HTTP_Request::attach()\r
1111     */\r
1112     function _notify($event, $data = null)\r
1113     {\r
1114         foreach (array_keys($this->_listeners) as $id) {\r
1115             $this->_listeners[$id]->update($this, $event, $data);\r
1116         }\r
1117     }\r
1118 }\r
1119 \r
1120 \r
1121 /**\r
1122  * Response class to complement the Request class\r
1123  *\r
1124  * @category    HTTP\r
1125  * @package     HTTP_Request\r
1126  * @author      Richard Heyes <richard@phpguru.org>\r
1127  * @author      Alexey Borzov <avb@php.net>\r
1128  * @version     Release: 1.4.4\r
1129  */\r
1130 class HTTP_Response\r
1131 {\r
1132     /**\r
1133     * Socket object\r
1134     * @var Net_Socket\r
1135     */\r
1136     var $_sock;\r
1137 \r
1138     /**\r
1139     * Protocol\r
1140     * @var string\r
1141     */\r
1142     var $_protocol;\r
1143 \r
1144     /**\r
1145     * Return code\r
1146     * @var string\r
1147     */\r
1148     var $_code;\r
1149 \r
1150     /**\r
1151     * Response reason phrase\r
1152     * @var string\r
1153     */\r
1154     var $_reason;\r
1155 \r
1156     /**\r
1157     * Response headers\r
1158     * @var array\r
1159     */\r
1160     var $_headers;\r
1161 \r
1162     /**\r
1163     * Cookies set in response\r
1164     * @var array\r
1165     */\r
1166     var $_cookies;\r
1167 \r
1168     /**\r
1169     * Response body\r
1170     * @var string\r
1171     */\r
1172     var $_body = '';\r
1173 \r
1174    /**\r
1175     * Used by _readChunked(): remaining length of the current chunk\r
1176     * @var string\r
1177     */\r
1178     var $_chunkLength = 0;\r
1179 \r
1180    /**\r
1181     * Attached listeners\r
1182     * @var array\r
1183     */\r
1184     var $_listeners = array();\r
1185 \r
1186    /**\r
1187     * Bytes left to read from message-body\r
1188     * @var null|int\r
1189     */\r
1190     var $_toRead;\r
1191 \r
1192     /**\r
1193     * Constructor\r
1194     *\r
1195     * @param  Net_Socket    socket to read the response from\r
1196     * @param  array         listeners attached to request\r
1197     */\r
1198     function HTTP_Response(&$sock, &$listeners)\r
1199     {\r
1200         $this->_sock      =& $sock;\r
1201         $this->_listeners =& $listeners;\r
1202     }\r
1203 \r
1204 \r
1205    /**\r
1206     * Processes a HTTP response\r
1207     *\r
1208     * This extracts response code, headers, cookies and decodes body if it\r
1209     * was encoded in some way\r
1210     *\r
1211     * @access public\r
1212     * @param  bool      Whether to store response body in object property, set\r
1213     *                   this to false if downloading a LARGE file and using a Listener.\r
1214     *                   This is assumed to be true if body is gzip-encoded.\r
1215     * @param  bool      Whether the response can actually have a message-body.\r
1216     *                   Will be set to false for HEAD requests.\r
1217     * @throws PEAR_Error\r
1218     * @return mixed     true on success, PEAR_Error in case of malformed response\r
1219     */\r
1220     function process($saveBody = true, $canHaveBody = true)\r
1221     {\r
1222         do {\r
1223             $line = $this->_sock->readLine();\r
1224             if (!preg_match('!^(HTTP/\d\.\d) (\d{3})(?: (.+))?!', $line, $s)) {\r
1225                 return PEAR::raiseError('Malformed response', HTTP_REQUEST_ERROR_RESPONSE);\r
1226             } else {\r
1227                 $this->_protocol = $s[1];\r
1228                 $this->_code     = intval($s[2]);\r
1229                 $this->_reason   = empty($s[3])? null: $s[3];\r
1230             }\r
1231             while ('' !== ($header = $this->_sock->readLine())) {\r
1232                 $this->_processHeader($header);\r
1233             }\r
1234         } while (100 == $this->_code);\r
1235 \r
1236         $this->_notify('gotHeaders', $this->_headers);\r
1237 \r
1238         // RFC 2616, section 4.4:\r
1239         // 1. Any response message which "MUST NOT" include a message-body ...\r
1240         // is always terminated by the first empty line after the header fields\r
1241         // 3. ... If a message is received with both a\r
1242         // Transfer-Encoding header field and a Content-Length header field,\r
1243         // the latter MUST be ignored.\r
1244         $canHaveBody = $canHaveBody && $this->_code >= 200 &&\r
1245                        $this->_code != 204 && $this->_code != 304;\r
1246 \r
1247         // If response body is present, read it and decode\r
1248         $chunked = isset($this->_headers['transfer-encoding']) && ('chunked' == $this->_headers['transfer-encoding']);\r
1249         $gzipped = isset($this->_headers['content-encoding']) && ('gzip' == $this->_headers['content-encoding']);\r
1250         $hasBody = false;\r
1251         if ($canHaveBody && ($chunked || !isset($this->_headers['content-length']) ||\r
1252                 0 != $this->_headers['content-length']))\r
1253         {\r
1254             if ($chunked || !isset($this->_headers['content-length'])) {\r
1255                 $this->_toRead = null;\r
1256             } else {\r
1257                 $this->_toRead = $this->_headers['content-length'];\r
1258             }\r
1259             while (!$this->_sock->eof() && (is_null($this->_toRead) || 0 < $this->_toRead)) {\r
1260                 if ($chunked) {\r
1261                     $data = $this->_readChunked();\r
1262                 } elseif (is_null($this->_toRead)) {\r
1263                     $data = $this->_sock->read(4096);\r
1264                 } else {\r
1265                     $data = $this->_sock->read(min(4096, $this->_toRead));\r
1266                     $this->_toRead -= HTTP_REQUEST_MBSTRING? mb_strlen($data, 'iso-8859-1'): strlen($data);\r
1267                 }\r
1268                 if ('' == $data && (!$this->_chunkLength || $this->_sock->eof())) {\r
1269                     break;\r
1270                 } else {\r
1271                     $hasBody = true;\r
1272                     if ($saveBody || $gzipped) {\r
1273                         $this->_body .= $data;\r
1274                     }\r
1275                     $this->_notify($gzipped? 'gzTick': 'tick', $data);\r
1276                 }\r
1277             }\r
1278         }\r
1279 \r
1280         if ($hasBody) {\r
1281             // Uncompress the body if needed\r
1282             if ($gzipped) {\r
1283                 $body = $this->_decodeGzip($this->_body);\r
1284                 if (PEAR::isError($body)) {\r
1285                     return $body;\r
1286                 }\r
1287                 $this->_body = $body;\r
1288                 $this->_notify('gotBody', $this->_body);\r
1289             } else {\r
1290                 $this->_notify('gotBody');\r
1291             }\r
1292         }\r
1293         return true;\r
1294     }\r
1295 \r
1296 \r
1297    /**\r
1298     * Processes the response header\r
1299     *\r
1300     * @access private\r
1301     * @param  string    HTTP header\r
1302     */\r
1303     function _processHeader($header)\r
1304     {\r
1305         if (false === strpos($header, ':')) {\r
1306             return;\r
1307         }\r
1308         list($headername, $headervalue) = explode(':', $header, 2);\r
1309         $headername  = strtolower($headername);\r
1310         $headervalue = ltrim($headervalue);\r
1311 \r
1312         if ('set-cookie' != $headername) {\r
1313             if (isset($this->_headers[$headername])) {\r
1314                 $this->_headers[$headername] .= ',' . $headervalue;\r
1315             } else {\r
1316                 $this->_headers[$headername]  = $headervalue;\r
1317             }\r
1318         } else {\r
1319             $this->_parseCookie($headervalue);\r
1320         }\r
1321     }\r
1322 \r
1323 \r
1324    /**\r
1325     * Parse a Set-Cookie header to fill $_cookies array\r
1326     *\r
1327     * @access private\r
1328     * @param  string    value of Set-Cookie header\r
1329     */\r
1330     function _parseCookie($headervalue)\r
1331     {\r
1332         $cookie = array(\r
1333             'expires' => null,\r
1334             'domain'  => null,\r
1335             'path'    => null,\r
1336             'secure'  => false\r
1337         );\r
1338 \r
1339         // Only a name=value pair\r
1340         if (!strpos($headervalue, ';')) {\r
1341             $pos = strpos($headervalue, '=');\r
1342             $cookie['name']  = trim(substr($headervalue, 0, $pos));\r
1343             $cookie['value'] = trim(substr($headervalue, $pos + 1));\r
1344 \r
1345         // Some optional parameters are supplied\r
1346         } else {\r
1347             $elements = explode(';', $headervalue);\r
1348             $pos = strpos($elements[0], '=');\r
1349             $cookie['name']  = trim(substr($elements[0], 0, $pos));\r
1350             $cookie['value'] = trim(substr($elements[0], $pos + 1));\r
1351 \r
1352             for ($i = 1; $i < count($elements); $i++) {\r
1353                 if (false === strpos($elements[$i], '=')) {\r
1354                     $elName  = trim($elements[$i]);\r
1355                     $elValue = null;\r
1356                 } else {\r
1357                     list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));\r
1358                 }\r
1359                 $elName = strtolower($elName);\r
1360                 if ('secure' == $elName) {\r
1361                     $cookie['secure'] = true;\r
1362                 } elseif ('expires' == $elName) {\r
1363                     $cookie['expires'] = str_replace('"', '', $elValue);\r
1364                 } elseif ('path' == $elName || 'domain' == $elName) {\r
1365                     $cookie[$elName] = urldecode($elValue);\r
1366                 } else {\r
1367                     $cookie[$elName] = $elValue;\r
1368                 }\r
1369             }\r
1370         }\r
1371         $this->_cookies[] = $cookie;\r
1372     }\r
1373 \r
1374 \r
1375    /**\r
1376     * Read a part of response body encoded with chunked Transfer-Encoding\r
1377     *\r
1378     * @access private\r
1379     * @return string\r
1380     */\r
1381     function _readChunked()\r
1382     {\r
1383         // at start of the next chunk?\r
1384         if (0 == $this->_chunkLength) {\r
1385             $line = $this->_sock->readLine();\r
1386             if (preg_match('/^([0-9a-f]+)/i', $line, $matches)) {\r
1387                 $this->_chunkLength = hexdec($matches[1]);\r
1388                 // Chunk with zero length indicates the end\r
1389                 if (0 == $this->_chunkLength) {\r
1390                     $this->_sock->readLine(); // make this an eof()\r
1391                     return '';\r
1392                 }\r
1393             } else {\r
1394                 return '';\r
1395             }\r
1396         }\r
1397         $data = $this->_sock->read($this->_chunkLength);\r
1398         $this->_chunkLength -= HTTP_REQUEST_MBSTRING? mb_strlen($data, 'iso-8859-1'): strlen($data);\r
1399         if (0 == $this->_chunkLength) {\r
1400             $this->_sock->readLine(); // Trailing CRLF\r
1401         }\r
1402         return $data;\r
1403     }\r
1404 \r
1405 \r
1406    /**\r
1407     * Notifies all registered listeners of an event.\r
1408     *\r
1409     * @param    string  Event name\r
1410     * @param    mixed   Additional data\r
1411     * @access   private\r
1412     * @see HTTP_Request::_notify()\r
1413     */\r
1414     function _notify($event, $data = null)\r
1415     {\r
1416         foreach (array_keys($this->_listeners) as $id) {\r
1417             $this->_listeners[$id]->update($this, $event, $data);\r
1418         }\r
1419     }\r
1420 \r
1421 \r
1422    /**\r
1423     * Decodes the message-body encoded by gzip\r
1424     *\r
1425     * The real decoding work is done by gzinflate() built-in function, this\r
1426     * method only parses the header and checks data for compliance with\r
1427     * RFC 1952\r
1428     *\r
1429     * @access   private\r
1430     * @param    string  gzip-encoded data\r
1431     * @return   string  decoded data\r
1432     */\r
1433     function _decodeGzip($data)\r
1434     {\r
1435         if (HTTP_REQUEST_MBSTRING) {\r
1436             $oldEncoding = mb_internal_encoding();\r
1437             mb_internal_encoding('iso-8859-1');\r
1438         }\r
1439         $length = strlen($data);\r
1440         // If it doesn't look like gzip-encoded data, don't bother\r
1441         if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) {\r
1442             return $data;\r
1443         }\r
1444         $method = ord(substr($data, 2, 1));\r
1445         if (8 != $method) {\r
1446             return PEAR::raiseError('_decodeGzip(): unknown compression method', HTTP_REQUEST_ERROR_GZIP_METHOD);\r
1447         }\r
1448         $flags = ord(substr($data, 3, 1));\r
1449         if ($flags & 224) {\r
1450             return PEAR::raiseError('_decodeGzip(): reserved bits are set', HTTP_REQUEST_ERROR_GZIP_DATA);\r
1451         }\r
1452 \r
1453         // header is 10 bytes minimum. may be longer, though.\r
1454         $headerLength = 10;\r
1455         // extra fields, need to skip 'em\r
1456         if ($flags & 4) {\r
1457             if ($length - $headerLength - 2 < 8) {\r
1458                 return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);\r
1459             }\r
1460             $extraLength = unpack('v', substr($data, 10, 2));\r
1461             if ($length - $headerLength - 2 - $extraLength[1] < 8) {\r
1462                 return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);\r
1463             }\r
1464             $headerLength += $extraLength[1] + 2;\r
1465         }\r
1466         // file name, need to skip that\r
1467         if ($flags & 8) {\r
1468             if ($length - $headerLength - 1 < 8) {\r
1469                 return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);\r
1470             }\r
1471             $filenameLength = strpos(substr($data, $headerLength), chr(0));\r
1472             if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) {\r
1473                 return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);\r
1474             }\r
1475             $headerLength += $filenameLength + 1;\r
1476         }\r
1477         // comment, need to skip that also\r
1478         if ($flags & 16) {\r
1479             if ($length - $headerLength - 1 < 8) {\r
1480                 return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);\r
1481             }\r
1482             $commentLength = strpos(substr($data, $headerLength), chr(0));\r
1483             if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) {\r
1484                 return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);\r
1485             }\r
1486             $headerLength += $commentLength + 1;\r
1487         }\r
1488         // have a CRC for header. let's check\r
1489         if ($flags & 1) {\r
1490             if ($length - $headerLength - 2 < 8) {\r
1491                 return PEAR::raiseError('_decodeGzip(): data too short', HTTP_REQUEST_ERROR_GZIP_DATA);\r
1492             }\r
1493             $crcReal   = 0xffff & crc32(substr($data, 0, $headerLength));\r
1494             $crcStored = unpack('v', substr($data, $headerLength, 2));\r
1495             if ($crcReal != $crcStored[1]) {\r
1496                 return PEAR::raiseError('_decodeGzip(): header CRC check failed', HTTP_REQUEST_ERROR_GZIP_CRC);\r
1497             }\r
1498             $headerLength += 2;\r
1499         }\r
1500         // unpacked data CRC and size at the end of encoded data\r
1501         $tmp = unpack('V2', substr($data, -8));\r
1502         $dataCrc  = $tmp[1];\r
1503         $dataSize = $tmp[2];\r
1504 \r
1505         // finally, call the gzinflate() function\r
1506         // don't pass $dataSize to gzinflate, see bugs #13135, #14370\r
1507         $unpacked = gzinflate(substr($data, $headerLength, -8));\r
1508         if (false === $unpacked) {\r
1509             return PEAR::raiseError('_decodeGzip(): gzinflate() call failed', HTTP_REQUEST_ERROR_GZIP_READ);\r
1510         } elseif ($dataSize != strlen($unpacked)) {\r
1511             return PEAR::raiseError('_decodeGzip(): data size check failed', HTTP_REQUEST_ERROR_GZIP_READ);\r
1512         } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {\r
1513             return PEAR::raiseError('_decodeGzip(): data CRC check failed', HTTP_REQUEST_ERROR_GZIP_CRC);\r
1514         }\r
1515         if (HTTP_REQUEST_MBSTRING) {\r
1516             mb_internal_encoding($oldEncoding);\r
1517         }\r
1518         return $unpacked;\r
1519     }\r
1520 } // End class HTTP_Response\r
1521 ?>\r