source: temp/trunk/data/module/Request.php @ 6901

Revision 6901, 44.8 KB checked in by kakinaka, 20 years ago (diff)

* empty log message *

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