]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/HTTP/Request2.php
Use intval on ini_get or we use a string for timeout
[quix0rs-gnu-social.git] / extlib / HTTP / Request2.php
1 <?php\r
2 /**\r
3  * Class representing a HTTP request message\r
4  *\r
5  * PHP version 5\r
6  *\r
7  * LICENSE\r
8  *\r
9  * This source file is subject to BSD 3-Clause License that is bundled\r
10  * with this package in the file LICENSE and available at the URL\r
11  * https://raw.github.com/pear/HTTP_Request2/trunk/docs/LICENSE\r
12  *\r
13  * @category  HTTP\r
14  * @package   HTTP_Request2\r
15  * @author    Alexey Borzov <avb@php.net>\r
16  * @copyright 2008-2016 Alexey Borzov <avb@php.net>\r
17  * @license   http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License\r
18  * @link      http://pear.php.net/package/HTTP_Request2\r
19  */\r
20 \r
21 /**\r
22  * A class representing an URL as per RFC 3986.\r
23  */\r
24 if (!class_exists('Net_URL2', true)) {\r
25     require_once 'Net/URL2.php';\r
26 }\r
27 \r
28 /**\r
29  * Exception class for HTTP_Request2 package\r
30  */\r
31 require_once 'HTTP/Request2/Exception.php';\r
32 \r
33 /**\r
34  * Class representing a HTTP request message\r
35  *\r
36  * @category HTTP\r
37  * @package  HTTP_Request2\r
38  * @author   Alexey Borzov <avb@php.net>\r
39  * @license  http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License\r
40  * @version  Release: 2.3.0\r
41  * @link     http://pear.php.net/package/HTTP_Request2\r
42  * @link     http://tools.ietf.org/html/rfc2616#section-5\r
43  */\r
44 class HTTP_Request2 implements SplSubject\r
45 {\r
46     /**#@+\r
47      * Constants for HTTP request methods\r
48      *\r
49      * @link http://tools.ietf.org/html/rfc2616#section-5.1.1\r
50      */\r
51     const METHOD_OPTIONS = 'OPTIONS';\r
52     const METHOD_GET     = 'GET';\r
53     const METHOD_HEAD    = 'HEAD';\r
54     const METHOD_POST    = 'POST';\r
55     const METHOD_PUT     = 'PUT';\r
56     const METHOD_DELETE  = 'DELETE';\r
57     const METHOD_TRACE   = 'TRACE';\r
58     const METHOD_CONNECT = 'CONNECT';\r
59     /**#@-*/\r
60 \r
61     /**#@+\r
62      * Constants for HTTP authentication schemes\r
63      *\r
64      * @link http://tools.ietf.org/html/rfc2617\r
65      */\r
66     const AUTH_BASIC  = 'basic';\r
67     const AUTH_DIGEST = 'digest';\r
68     /**#@-*/\r
69 \r
70     /**\r
71      * Regular expression used to check for invalid symbols in RFC 2616 tokens\r
72      * @link http://pear.php.net/bugs/bug.php?id=15630\r
73      */\r
74     const REGEXP_INVALID_TOKEN = '![\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]!';\r
75 \r
76     /**\r
77      * Regular expression used to check for invalid symbols in cookie strings\r
78      * @link http://pear.php.net/bugs/bug.php?id=15630\r
79      * @link http://web.archive.org/web/20080331104521/http://cgi.netscape.com/newsref/std/cookie_spec.html\r
80      */\r
81     const REGEXP_INVALID_COOKIE = '/[\s,;]/';\r
82 \r
83     /**\r
84      * Fileinfo magic database resource\r
85      * @var  resource\r
86      * @see  detectMimeType()\r
87      */\r
88     private static $_fileinfoDb;\r
89 \r
90     /**\r
91      * Observers attached to the request (instances of SplObserver)\r
92      * @var  array\r
93      */\r
94     protected $observers = array();\r
95 \r
96     /**\r
97      * Request URL\r
98      * @var  Net_URL2\r
99      */\r
100     protected $url;\r
101 \r
102     /**\r
103      * Request method\r
104      * @var  string\r
105      */\r
106     protected $method = self::METHOD_GET;\r
107 \r
108     /**\r
109      * Authentication data\r
110      * @var  array\r
111      * @see  getAuth()\r
112      */\r
113     protected $auth;\r
114 \r
115     /**\r
116      * Request headers\r
117      * @var  array\r
118      */\r
119     protected $headers = array();\r
120 \r
121     /**\r
122      * Configuration parameters\r
123      * @var  array\r
124      * @see  setConfig()\r
125      */\r
126     protected $config = array(\r
127         'adapter'           => 'HTTP_Request2_Adapter_Socket',\r
128         'connect_timeout'   => 10,\r
129         'timeout'           => 0,\r
130         'use_brackets'      => true,\r
131         'protocol_version'  => '1.1',\r
132         'buffer_size'       => 16384,\r
133         'store_body'        => true,\r
134         'local_ip'          => null,\r
135 \r
136         'proxy_host'        => '',\r
137         'proxy_port'        => '',\r
138         'proxy_user'        => '',\r
139         'proxy_password'    => '',\r
140         'proxy_auth_scheme' => self::AUTH_BASIC,\r
141         'proxy_type'        => 'http',\r
142 \r
143         'ssl_verify_peer'   => true,\r
144         'ssl_verify_host'   => true,\r
145         'ssl_cafile'        => null,\r
146         'ssl_capath'        => null,\r
147         'ssl_local_cert'    => null,\r
148         'ssl_passphrase'    => null,\r
149 \r
150         'digest_compat_ie'  => false,\r
151 \r
152         'follow_redirects'  => false,\r
153         'max_redirects'     => 5,\r
154         'strict_redirects'  => false\r
155     );\r
156 \r
157     /**\r
158      * Last event in request / response handling, intended for observers\r
159      * @var  array\r
160      * @see  getLastEvent()\r
161      */\r
162     protected $lastEvent = array(\r
163         'name' => 'start',\r
164         'data' => null\r
165     );\r
166 \r
167     /**\r
168      * Request body\r
169      * @var  string|resource\r
170      * @see  setBody()\r
171      */\r
172     protected $body = '';\r
173 \r
174     /**\r
175      * Array of POST parameters\r
176      * @var  array\r
177      */\r
178     protected $postParams = array();\r
179 \r
180     /**\r
181      * Array of file uploads (for multipart/form-data POST requests)\r
182      * @var  array\r
183      */\r
184     protected $uploads = array();\r
185 \r
186     /**\r
187      * Adapter used to perform actual HTTP request\r
188      * @var  HTTP_Request2_Adapter\r
189      */\r
190     protected $adapter;\r
191 \r
192     /**\r
193      * Cookie jar to persist cookies between requests\r
194      * @var HTTP_Request2_CookieJar\r
195      */\r
196     protected $cookieJar = null;\r
197 \r
198     /**\r
199      * Constructor. Can set request URL, method and configuration array.\r
200      *\r
201      * Also sets a default value for User-Agent header.\r
202      *\r
203      * @param string|Net_Url2 $url    Request URL\r
204      * @param string          $method Request method\r
205      * @param array           $config Configuration for this Request instance\r
206      */\r
207     public function __construct(\r
208         $url = null, $method = self::METHOD_GET, array $config = array()\r
209     ) {\r
210         $this->setConfig($config);\r
211         if (!empty($url)) {\r
212             $this->setUrl($url);\r
213         }\r
214         if (!empty($method)) {\r
215             $this->setMethod($method);\r
216         }\r
217         $this->setHeader(\r
218             'user-agent', 'HTTP_Request2/2.3.0 ' .\r
219             '(http://pear.php.net/package/http_request2) PHP/' . phpversion()\r
220         );\r
221     }\r
222 \r
223     /**\r
224      * Sets the URL for this request\r
225      *\r
226      * If the URL has userinfo part (username & password) these will be removed\r
227      * and converted to auth data. If the URL does not have a path component,\r
228      * that will be set to '/'.\r
229      *\r
230      * @param string|Net_URL2 $url Request URL\r
231      *\r
232      * @return   HTTP_Request2\r
233      * @throws   HTTP_Request2_LogicException\r
234      */\r
235     public function setUrl($url)\r
236     {\r
237         if (is_string($url)) {\r
238             $url = new Net_URL2(\r
239                 $url, array(Net_URL2::OPTION_USE_BRACKETS => $this->config['use_brackets'])\r
240             );\r
241         }\r
242         if (!$url instanceof Net_URL2) {\r
243             throw new HTTP_Request2_LogicException(\r
244                 'Parameter is not a valid HTTP URL',\r
245                 HTTP_Request2_Exception::INVALID_ARGUMENT\r
246             );\r
247         }\r
248         // URL contains username / password?\r
249         if ($url->getUserinfo()) {\r
250             $username = $url->getUser();\r
251             $password = $url->getPassword();\r
252             $this->setAuth(rawurldecode($username), $password? rawurldecode($password): '');\r
253             $url->setUserinfo('');\r
254         }\r
255         if ('' == $url->getPath()) {\r
256             $url->setPath('/');\r
257         }\r
258         $this->url = $url;\r
259 \r
260         return $this;\r
261     }\r
262 \r
263     /**\r
264      * Returns the request URL\r
265      *\r
266      * @return   Net_URL2\r
267      */\r
268     public function getUrl()\r
269     {\r
270         return $this->url;\r
271     }\r
272 \r
273     /**\r
274      * Sets the request method\r
275      *\r
276      * @param string $method one of the methods defined in RFC 2616\r
277      *\r
278      * @return   HTTP_Request2\r
279      * @throws   HTTP_Request2_LogicException if the method name is invalid\r
280      */\r
281     public function setMethod($method)\r
282     {\r
283         // Method name should be a token: http://tools.ietf.org/html/rfc2616#section-5.1.1\r
284         if (preg_match(self::REGEXP_INVALID_TOKEN, $method)) {\r
285             throw new HTTP_Request2_LogicException(\r
286                 "Invalid request method '{$method}'",\r
287                 HTTP_Request2_Exception::INVALID_ARGUMENT\r
288             );\r
289         }\r
290         $this->method = $method;\r
291 \r
292         return $this;\r
293     }\r
294 \r
295     /**\r
296      * Returns the request method\r
297      *\r
298      * @return   string\r
299      */\r
300     public function getMethod()\r
301     {\r
302         return $this->method;\r
303     }\r
304 \r
305     /**\r
306      * Sets the configuration parameter(s)\r
307      *\r
308      * The following parameters are available:\r
309      * <ul>\r
310      *   <li> 'adapter'           - adapter to use (string)</li>\r
311      *   <li> 'connect_timeout'   - Connection timeout in seconds (integer)</li>\r
312      *   <li> 'timeout'           - Total number of seconds a request can take.\r
313      *                              Use 0 for no limit, should be greater than\r
314      *                              'connect_timeout' if set (integer)</li>\r
315      *   <li> 'use_brackets'      - Whether to append [] to array variable names (bool)</li>\r
316      *   <li> 'protocol_version'  - HTTP Version to use, '1.0' or '1.1' (string)</li>\r
317      *   <li> 'buffer_size'       - Buffer size to use for reading and writing (int)</li>\r
318      *   <li> 'store_body'        - Whether to store response body in response object.\r
319      *                              Set to false if receiving a huge response and\r
320      *                              using an Observer to save it (boolean)</li>\r
321      *   <li> 'local_ip'          - Specifies the IP address that will be used for accessing\r
322      *                              the network (string)</li>\r
323      *   <li> 'proxy_type'        - Proxy type, 'http' or 'socks5' (string)</li>\r
324      *   <li> 'proxy_host'        - Proxy server host (string)</li>\r
325      *   <li> 'proxy_port'        - Proxy server port (integer)</li>\r
326      *   <li> 'proxy_user'        - Proxy auth username (string)</li>\r
327      *   <li> 'proxy_password'    - Proxy auth password (string)</li>\r
328      *   <li> 'proxy_auth_scheme' - Proxy auth scheme, one of HTTP_Request2::AUTH_* constants (string)</li>\r
329      *   <li> 'proxy'             - Shorthand for proxy_* parameters, proxy given as URL,\r
330      *                              e.g. 'socks5://localhost:1080/' (string)</li>\r
331      *   <li> 'ssl_verify_peer'   - Whether to verify peer's SSL certificate (bool)</li>\r
332      *   <li> 'ssl_verify_host'   - Whether to check that Common Name in SSL\r
333      *                              certificate matches host name (bool)</li>\r
334      *   <li> 'ssl_cafile'        - Cerificate Authority file to verify the peer\r
335      *                              with (use with 'ssl_verify_peer') (string)</li>\r
336      *   <li> 'ssl_capath'        - Directory holding multiple Certificate\r
337      *                              Authority files (string)</li>\r
338      *   <li> 'ssl_local_cert'    - Name of a file containing local cerificate (string)</li>\r
339      *   <li> 'ssl_passphrase'    - Passphrase with which local certificate\r
340      *                              was encoded (string)</li>\r
341      *   <li> 'digest_compat_ie'  - Whether to imitate behaviour of MSIE 5 and 6\r
342      *                              in using URL without query string in digest\r
343      *                              authentication (boolean)</li>\r
344      *   <li> 'follow_redirects'  - Whether to automatically follow HTTP Redirects (boolean)</li>\r
345      *   <li> 'max_redirects'     - Maximum number of redirects to follow (integer)</li>\r
346      *   <li> 'strict_redirects'  - Whether to keep request method on redirects via status 301 and\r
347      *                              302 (true, needed for compatibility with RFC 2616)\r
348      *                              or switch to GET (false, needed for compatibility with most\r
349      *                              browsers) (boolean)</li>\r
350      * </ul>\r
351      *\r
352      * @param string|array $nameOrConfig configuration parameter name or array\r
353      *                                   ('parameter name' => 'parameter value')\r
354      * @param mixed        $value        parameter value if $nameOrConfig is not an array\r
355      *\r
356      * @return   HTTP_Request2\r
357      * @throws   HTTP_Request2_LogicException If the parameter is unknown\r
358      */\r
359     public function setConfig($nameOrConfig, $value = null)\r
360     {\r
361         if (is_array($nameOrConfig)) {\r
362             foreach ($nameOrConfig as $name => $value) {\r
363                 $this->setConfig($name, $value);\r
364             }\r
365 \r
366         } elseif ('proxy' == $nameOrConfig) {\r
367             $url = new Net_URL2($value);\r
368             $this->setConfig(array(\r
369                 'proxy_type'     => $url->getScheme(),\r
370                 'proxy_host'     => $url->getHost(),\r
371                 'proxy_port'     => $url->getPort(),\r
372                 'proxy_user'     => rawurldecode($url->getUser()),\r
373                 'proxy_password' => rawurldecode($url->getPassword())\r
374             ));\r
375 \r
376         } else {\r
377             if (!array_key_exists($nameOrConfig, $this->config)) {\r
378                 throw new HTTP_Request2_LogicException(\r
379                     "Unknown configuration parameter '{$nameOrConfig}'",\r
380                     HTTP_Request2_Exception::INVALID_ARGUMENT\r
381                 );\r
382             }\r
383             $this->config[$nameOrConfig] = $value;\r
384         }\r
385 \r
386         return $this;\r
387     }\r
388 \r
389     /**\r
390      * Returns the value(s) of the configuration parameter(s)\r
391      *\r
392      * @param string $name parameter name\r
393      *\r
394      * @return   mixed   value of $name parameter, array of all configuration\r
395      *                   parameters if $name is not given\r
396      * @throws   HTTP_Request2_LogicException If the parameter is unknown\r
397      */\r
398     public function getConfig($name = null)\r
399     {\r
400         if (null === $name) {\r
401             return $this->config;\r
402         } elseif (!array_key_exists($name, $this->config)) {\r
403             throw new HTTP_Request2_LogicException(\r
404                 "Unknown configuration parameter '{$name}'",\r
405                 HTTP_Request2_Exception::INVALID_ARGUMENT\r
406             );\r
407         }\r
408         return $this->config[$name];\r
409     }\r
410 \r
411     /**\r
412      * Sets the autentification data\r
413      *\r
414      * @param string $user     user name\r
415      * @param string $password password\r
416      * @param string $scheme   authentication scheme\r
417      *\r
418      * @return   HTTP_Request2\r
419      */\r
420     public function setAuth($user, $password = '', $scheme = self::AUTH_BASIC)\r
421     {\r
422         if (empty($user)) {\r
423             $this->auth = null;\r
424         } else {\r
425             $this->auth = array(\r
426                 'user'     => (string)$user,\r
427                 'password' => (string)$password,\r
428                 'scheme'   => $scheme\r
429             );\r
430         }\r
431 \r
432         return $this;\r
433     }\r
434 \r
435     /**\r
436      * Returns the authentication data\r
437      *\r
438      * The array has the keys 'user', 'password' and 'scheme', where 'scheme'\r
439      * is one of the HTTP_Request2::AUTH_* constants.\r
440      *\r
441      * @return   array\r
442      */\r
443     public function getAuth()\r
444     {\r
445         return $this->auth;\r
446     }\r
447 \r
448     /**\r
449      * Sets request header(s)\r
450      *\r
451      * The first parameter may be either a full header string 'header: value' or\r
452      * header name. In the former case $value parameter is ignored, in the latter\r
453      * the header's value will either be set to $value or the header will be\r
454      * removed if $value is null. The first parameter can also be an array of\r
455      * headers, in that case method will be called recursively.\r
456      *\r
457      * Note that headers are treated case insensitively as per RFC 2616.\r
458      *\r
459      * <code>\r
460      * $req->setHeader('Foo: Bar'); // sets the value of 'Foo' header to 'Bar'\r
461      * $req->setHeader('FoO', 'Baz'); // sets the value of 'Foo' header to 'Baz'\r
462      * $req->setHeader(array('foo' => 'Quux')); // sets the value of 'Foo' header to 'Quux'\r
463      * $req->setHeader('FOO'); // removes 'Foo' header from request\r
464      * </code>\r
465      *\r
466      * @param string|array      $name    header name, header string ('Header: value')\r
467      *                                   or an array of headers\r
468      * @param string|array|null $value   header value if $name is not an array,\r
469      *                                   header will be removed if value is null\r
470      * @param bool              $replace whether to replace previous header with the\r
471      *                                   same name or append to its value\r
472      *\r
473      * @return   HTTP_Request2\r
474      * @throws   HTTP_Request2_LogicException\r
475      */\r
476     public function setHeader($name, $value = null, $replace = true)\r
477     {\r
478         if (is_array($name)) {\r
479             foreach ($name as $k => $v) {\r
480                 if (is_string($k)) {\r
481                     $this->setHeader($k, $v, $replace);\r
482                 } else {\r
483                     $this->setHeader($v, null, $replace);\r
484                 }\r
485             }\r
486         } else {\r
487             if (null === $value && strpos($name, ':')) {\r
488                 list($name, $value) = array_map('trim', explode(':', $name, 2));\r
489             }\r
490             // Header name should be a token: http://tools.ietf.org/html/rfc2616#section-4.2\r
491             if (preg_match(self::REGEXP_INVALID_TOKEN, $name)) {\r
492                 throw new HTTP_Request2_LogicException(\r
493                     "Invalid header name '{$name}'",\r
494                     HTTP_Request2_Exception::INVALID_ARGUMENT\r
495                 );\r
496             }\r
497             // Header names are case insensitive anyway\r
498             $name = strtolower($name);\r
499             if (null === $value) {\r
500                 unset($this->headers[$name]);\r
501 \r
502             } else {\r
503                 if (is_array($value)) {\r
504                     $value = implode(', ', array_map('trim', $value));\r
505                 } elseif (is_string($value)) {\r
506                     $value = trim($value);\r
507                 }\r
508                 if (!isset($this->headers[$name]) || $replace) {\r
509                     $this->headers[$name] = $value;\r
510                 } else {\r
511                     $this->headers[$name] .= ', ' . $value;\r
512                 }\r
513             }\r
514         }\r
515 \r
516         return $this;\r
517     }\r
518 \r
519     /**\r
520      * Returns the request headers\r
521      *\r
522      * The array is of the form ('header name' => 'header value'), header names\r
523      * are lowercased\r
524      *\r
525      * @return   array\r
526      */\r
527     public function getHeaders()\r
528     {\r
529         return $this->headers;\r
530     }\r
531 \r
532     /**\r
533      * Adds a cookie to the request\r
534      *\r
535      * If the request does not have a CookieJar object set, this method simply\r
536      * appends a cookie to "Cookie:" header.\r
537      *\r
538      * If a CookieJar object is available, the cookie is stored in that object.\r
539      * Data from request URL will be used for setting its 'domain' and 'path'\r
540      * parameters, 'expires' and 'secure' will be set to null and false,\r
541      * respectively. If you need further control, use CookieJar's methods.\r
542      *\r
543      * @param string $name  cookie name\r
544      * @param string $value cookie value\r
545      *\r
546      * @return   HTTP_Request2\r
547      * @throws   HTTP_Request2_LogicException\r
548      * @see      setCookieJar()\r
549      */\r
550     public function addCookie($name, $value)\r
551     {\r
552         if (!empty($this->cookieJar)) {\r
553             $this->cookieJar->store(\r
554                 array('name' => $name, 'value' => $value), $this->url\r
555             );\r
556 \r
557         } else {\r
558             $cookie = $name . '=' . $value;\r
559             if (preg_match(self::REGEXP_INVALID_COOKIE, $cookie)) {\r
560                 throw new HTTP_Request2_LogicException(\r
561                     "Invalid cookie: '{$cookie}'",\r
562                     HTTP_Request2_Exception::INVALID_ARGUMENT\r
563                 );\r
564             }\r
565             $cookies = empty($this->headers['cookie'])? '': $this->headers['cookie'] . '; ';\r
566             $this->setHeader('cookie', $cookies . $cookie);\r
567         }\r
568 \r
569         return $this;\r
570     }\r
571 \r
572     /**\r
573      * Sets the request body\r
574      *\r
575      * If you provide file pointer rather than file name, it should support\r
576      * fstat() and rewind() operations.\r
577      *\r
578      * @param string|resource|HTTP_Request2_MultipartBody $body       Either a\r
579      *               string with the body or filename containing body or\r
580      *               pointer to an open file or object with multipart body data\r
581      * @param bool                                        $isFilename Whether\r
582      *               first parameter is a filename\r
583      *\r
584      * @return   HTTP_Request2\r
585      * @throws   HTTP_Request2_LogicException\r
586      */\r
587     public function setBody($body, $isFilename = false)\r
588     {\r
589         if (!$isFilename && !is_resource($body)) {\r
590             if (!$body instanceof HTTP_Request2_MultipartBody) {\r
591                 $this->body = (string)$body;\r
592             } else {\r
593                 $this->body = $body;\r
594             }\r
595         } else {\r
596             $fileData = $this->fopenWrapper($body, empty($this->headers['content-type']));\r
597             $this->body = $fileData['fp'];\r
598             if (empty($this->headers['content-type'])) {\r
599                 $this->setHeader('content-type', $fileData['type']);\r
600             }\r
601         }\r
602         $this->postParams = $this->uploads = array();\r
603 \r
604         return $this;\r
605     }\r
606 \r
607     /**\r
608      * Returns the request body\r
609      *\r
610      * @return   string|resource|HTTP_Request2_MultipartBody\r
611      */\r
612     public function getBody()\r
613     {\r
614         if (self::METHOD_POST == $this->method\r
615             && (!empty($this->postParams) || !empty($this->uploads))\r
616         ) {\r
617             if (0 === strpos($this->headers['content-type'], 'application/x-www-form-urlencoded')) {\r
618                 $body = http_build_query($this->postParams, '', '&');\r
619                 if (!$this->getConfig('use_brackets')) {\r
620                     $body = preg_replace('/%5B\d+%5D=/', '=', $body);\r
621                 }\r
622                 // support RFC 3986 by not encoding '~' symbol (request #15368)\r
623                 return str_replace('%7E', '~', $body);\r
624 \r
625             } elseif (0 === strpos($this->headers['content-type'], 'multipart/form-data')) {\r
626                 require_once 'HTTP/Request2/MultipartBody.php';\r
627                 return new HTTP_Request2_MultipartBody(\r
628                     $this->postParams, $this->uploads, $this->getConfig('use_brackets')\r
629                 );\r
630             }\r
631         }\r
632         return $this->body;\r
633     }\r
634 \r
635     /**\r
636      * Adds a file to form-based file upload\r
637      *\r
638      * Used to emulate file upload via a HTML form. The method also sets\r
639      * Content-Type of HTTP request to 'multipart/form-data'.\r
640      *\r
641      * If you just want to send the contents of a file as the body of HTTP\r
642      * request you should use setBody() method.\r
643      *\r
644      * If you provide file pointers rather than file names, they should support\r
645      * fstat() and rewind() operations.\r
646      *\r
647      * @param string                $fieldName    name of file-upload field\r
648      * @param string|resource|array $filename     full name of local file,\r
649      *               pointer to open file or an array of files\r
650      * @param string                $sendFilename filename to send in the request\r
651      * @param string                $contentType  content-type of file being uploaded\r
652      *\r
653      * @return   HTTP_Request2\r
654      * @throws   HTTP_Request2_LogicException\r
655      */\r
656     public function addUpload(\r
657         $fieldName, $filename, $sendFilename = null, $contentType = null\r
658     ) {\r
659         if (!is_array($filename)) {\r
660             $fileData = $this->fopenWrapper($filename, empty($contentType));\r
661             $this->uploads[$fieldName] = array(\r
662                 'fp'        => $fileData['fp'],\r
663                 'filename'  => !empty($sendFilename)? $sendFilename\r
664                                 :(is_string($filename)? basename($filename): 'anonymous.blob') ,\r
665                 'size'      => $fileData['size'],\r
666                 'type'      => empty($contentType)? $fileData['type']: $contentType\r
667             );\r
668         } else {\r
669             $fps = $names = $sizes = $types = array();\r
670             foreach ($filename as $f) {\r
671                 if (!is_array($f)) {\r
672                     $f = array($f);\r
673                 }\r
674                 $fileData = $this->fopenWrapper($f[0], empty($f[2]));\r
675                 $fps[]   = $fileData['fp'];\r
676                 $names[] = !empty($f[1])? $f[1]\r
677                             :(is_string($f[0])? basename($f[0]): 'anonymous.blob');\r
678                 $sizes[] = $fileData['size'];\r
679                 $types[] = empty($f[2])? $fileData['type']: $f[2];\r
680             }\r
681             $this->uploads[$fieldName] = array(\r
682                 'fp' => $fps, 'filename' => $names, 'size' => $sizes, 'type' => $types\r
683             );\r
684         }\r
685         if (empty($this->headers['content-type'])\r
686             || 'application/x-www-form-urlencoded' == $this->headers['content-type']\r
687         ) {\r
688             $this->setHeader('content-type', 'multipart/form-data');\r
689         }\r
690 \r
691         return $this;\r
692     }\r
693 \r
694     /**\r
695      * Adds POST parameter(s) to the request.\r
696      *\r
697      * @param string|array $name  parameter name or array ('name' => 'value')\r
698      * @param mixed        $value parameter value (can be an array)\r
699      *\r
700      * @return   HTTP_Request2\r
701      */\r
702     public function addPostParameter($name, $value = null)\r
703     {\r
704         if (!is_array($name)) {\r
705             $this->postParams[$name] = $value;\r
706         } else {\r
707             foreach ($name as $k => $v) {\r
708                 $this->addPostParameter($k, $v);\r
709             }\r
710         }\r
711         if (empty($this->headers['content-type'])) {\r
712             $this->setHeader('content-type', 'application/x-www-form-urlencoded');\r
713         }\r
714 \r
715         return $this;\r
716     }\r
717 \r
718     /**\r
719      * Attaches a new observer\r
720      *\r
721      * @param SplObserver $observer any object implementing SplObserver\r
722      */\r
723     public function attach(SplObserver $observer)\r
724     {\r
725         foreach ($this->observers as $attached) {\r
726             if ($attached === $observer) {\r
727                 return;\r
728             }\r
729         }\r
730         $this->observers[] = $observer;\r
731     }\r
732 \r
733     /**\r
734      * Detaches an existing observer\r
735      *\r
736      * @param SplObserver $observer any object implementing SplObserver\r
737      */\r
738     public function detach(SplObserver $observer)\r
739     {\r
740         foreach ($this->observers as $key => $attached) {\r
741             if ($attached === $observer) {\r
742                 unset($this->observers[$key]);\r
743                 return;\r
744             }\r
745         }\r
746     }\r
747 \r
748     /**\r
749      * Notifies all observers\r
750      */\r
751     public function notify()\r
752     {\r
753         foreach ($this->observers as $observer) {\r
754             $observer->update($this);\r
755         }\r
756     }\r
757 \r
758     /**\r
759      * Sets the last event\r
760      *\r
761      * Adapters should use this method to set the current state of the request\r
762      * and notify the observers.\r
763      *\r
764      * @param string $name event name\r
765      * @param mixed  $data event data\r
766      */\r
767     public function setLastEvent($name, $data = null)\r
768     {\r
769         $this->lastEvent = array(\r
770             'name' => $name,\r
771             'data' => $data\r
772         );\r
773         $this->notify();\r
774     }\r
775 \r
776     /**\r
777      * Returns the last event\r
778      *\r
779      * Observers should use this method to access the last change in request.\r
780      * The following event names are possible:\r
781      * <ul>\r
782      *   <li>'connect'                 - after connection to remote server,\r
783      *                                   data is the destination (string)</li>\r
784      *   <li>'disconnect'              - after disconnection from server</li>\r
785      *   <li>'sentHeaders'             - after sending the request headers,\r
786      *                                   data is the headers sent (string)</li>\r
787      *   <li>'sentBodyPart'            - after sending a part of the request body,\r
788      *                                   data is the length of that part (int)</li>\r
789      *   <li>'sentBody'                - after sending the whole request body,\r
790      *                                   data is request body length (int)</li>\r
791      *   <li>'receivedHeaders'         - after receiving the response headers,\r
792      *                                   data is HTTP_Request2_Response object</li>\r
793      *   <li>'receivedBodyPart'        - after receiving a part of the response\r
794      *                                   body, data is that part (string)</li>\r
795      *   <li>'receivedEncodedBodyPart' - as 'receivedBodyPart', but data is still\r
796      *                                   encoded by Content-Encoding</li>\r
797      *   <li>'receivedBody'            - after receiving the complete response\r
798      *                                   body, data is HTTP_Request2_Response object</li>\r
799      *   <li>'warning'                 - a problem arose during the request\r
800      *                                   that is not severe enough to throw\r
801      *                                   an Exception, data is the warning\r
802      *                                   message (string). Currently dispatched if\r
803      *                                   response body was received incompletely.</li>\r
804      * </ul>\r
805      * Different adapters may not send all the event types. Mock adapter does\r
806      * not send any events to the observers.\r
807      *\r
808      * @return   array   The array has two keys: 'name' and 'data'\r
809      */\r
810     public function getLastEvent()\r
811     {\r
812         return $this->lastEvent;\r
813     }\r
814 \r
815     /**\r
816      * Sets the adapter used to actually perform the request\r
817      *\r
818      * You can pass either an instance of a class implementing HTTP_Request2_Adapter\r
819      * or a class name. The method will only try to include a file if the class\r
820      * name starts with HTTP_Request2_Adapter_, it will also try to prepend this\r
821      * prefix to the class name if it doesn't contain any underscores, so that\r
822      * <code>\r
823      * $request->setAdapter('curl');\r
824      * </code>\r
825      * will work.\r
826      *\r
827      * @param string|HTTP_Request2_Adapter $adapter Adapter to use\r
828      *\r
829      * @return   HTTP_Request2\r
830      * @throws   HTTP_Request2_LogicException\r
831      */\r
832     public function setAdapter($adapter)\r
833     {\r
834         if (is_string($adapter)) {\r
835             if (!class_exists($adapter, false)) {\r
836                 if (false === strpos($adapter, '_')) {\r
837                     $adapter = 'HTTP_Request2_Adapter_' . ucfirst($adapter);\r
838                 }\r
839                 if (!class_exists($adapter, false)\r
840                     && preg_match('/^HTTP_Request2_Adapter_([a-zA-Z0-9]+)$/', $adapter)\r
841                 ) {\r
842                     include_once str_replace('_', DIRECTORY_SEPARATOR, $adapter) . '.php';\r
843                 }\r
844                 if (!class_exists($adapter, false)) {\r
845                     throw new HTTP_Request2_LogicException(\r
846                         "Class {$adapter} not found",\r
847                         HTTP_Request2_Exception::MISSING_VALUE\r
848                     );\r
849                 }\r
850             }\r
851             $adapter = new $adapter;\r
852         }\r
853         if (!$adapter instanceof HTTP_Request2_Adapter) {\r
854             throw new HTTP_Request2_LogicException(\r
855                 'Parameter is not a HTTP request adapter',\r
856                 HTTP_Request2_Exception::INVALID_ARGUMENT\r
857             );\r
858         }\r
859         $this->adapter = $adapter;\r
860 \r
861         return $this;\r
862     }\r
863 \r
864     /**\r
865      * Sets the cookie jar\r
866      *\r
867      * A cookie jar is used to maintain cookies across HTTP requests and\r
868      * responses. Cookies from jar will be automatically added to the request\r
869      * headers based on request URL.\r
870      *\r
871      * @param HTTP_Request2_CookieJar|bool $jar Existing CookieJar object, true to\r
872      *                                          create a new one, false to remove\r
873      *\r
874      * @return HTTP_Request2\r
875      * @throws HTTP_Request2_LogicException\r
876      */\r
877     public function setCookieJar($jar = true)\r
878     {\r
879         if (!class_exists('HTTP_Request2_CookieJar', false)) {\r
880             require_once 'HTTP/Request2/CookieJar.php';\r
881         }\r
882 \r
883         if ($jar instanceof HTTP_Request2_CookieJar) {\r
884             $this->cookieJar = $jar;\r
885         } elseif (true === $jar) {\r
886             $this->cookieJar = new HTTP_Request2_CookieJar();\r
887         } elseif (!$jar) {\r
888             $this->cookieJar = null;\r
889         } else {\r
890             throw new HTTP_Request2_LogicException(\r
891                 'Invalid parameter passed to setCookieJar()',\r
892                 HTTP_Request2_Exception::INVALID_ARGUMENT\r
893             );\r
894         }\r
895 \r
896         return $this;\r
897     }\r
898 \r
899     /**\r
900      * Returns current CookieJar object or null if none\r
901      *\r
902      * @return HTTP_Request2_CookieJar|null\r
903      */\r
904     public function getCookieJar()\r
905     {\r
906         return $this->cookieJar;\r
907     }\r
908 \r
909     /**\r
910      * Sends the request and returns the response\r
911      *\r
912      * @throws   HTTP_Request2_Exception\r
913      * @return   HTTP_Request2_Response\r
914      */\r
915     public function send()\r
916     {\r
917         // Sanity check for URL\r
918         if (!$this->url instanceof Net_URL2\r
919             || !$this->url->isAbsolute()\r
920             || !in_array(strtolower($this->url->getScheme()), array('https', 'http'))\r
921         ) {\r
922             throw new HTTP_Request2_LogicException(\r
923                 'HTTP_Request2 needs an absolute HTTP(S) request URL, '\r
924                 . ($this->url instanceof Net_URL2\r
925                    ? "'" . $this->url->__toString() . "'" : 'none')\r
926                 . ' given',\r
927                 HTTP_Request2_Exception::INVALID_ARGUMENT\r
928             );\r
929         }\r
930         if (empty($this->adapter)) {\r
931             $this->setAdapter($this->getConfig('adapter'));\r
932         }\r
933         // magic_quotes_runtime may break file uploads and chunked response\r
934         // processing; see bug #4543. Don't use ini_get() here; see bug #16440.\r
935         if ($magicQuotes = get_magic_quotes_runtime()) {\r
936             set_magic_quotes_runtime(false);\r
937         }\r
938         // force using single byte encoding if mbstring extension overloads\r
939         // strlen() and substr(); see bug #1781, bug #10605\r
940         if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {\r
941             $oldEncoding = mb_internal_encoding();\r
942             mb_internal_encoding('8bit');\r
943         }\r
944 \r
945         try {\r
946             $response = $this->adapter->sendRequest($this);\r
947         } catch (Exception $e) {\r
948         }\r
949         // cleanup in either case (poor man's "finally" clause)\r
950         if ($magicQuotes) {\r
951             set_magic_quotes_runtime(true);\r
952         }\r
953         if (!empty($oldEncoding)) {\r
954             mb_internal_encoding($oldEncoding);\r
955         }\r
956         // rethrow the exception\r
957         if (!empty($e)) {\r
958             throw $e;\r
959         }\r
960         return $response;\r
961     }\r
962 \r
963     /**\r
964      * Wrapper around fopen()/fstat() used by setBody() and addUpload()\r
965      *\r
966      * @param string|resource $file       file name or pointer to open file\r
967      * @param bool            $detectType whether to try autodetecting MIME\r
968      *                        type of file, will only work if $file is a\r
969      *                        filename, not pointer\r
970      *\r
971      * @return array array('fp' => file pointer, 'size' => file size, 'type' => MIME type)\r
972      * @throws HTTP_Request2_LogicException\r
973      */\r
974     protected function fopenWrapper($file, $detectType = false)\r
975     {\r
976         if (!is_string($file) && !is_resource($file)) {\r
977             throw new HTTP_Request2_LogicException(\r
978                 "Filename or file pointer resource expected",\r
979                 HTTP_Request2_Exception::INVALID_ARGUMENT\r
980             );\r
981         }\r
982         $fileData = array(\r
983             'fp'   => is_string($file)? null: $file,\r
984             'type' => 'application/octet-stream',\r
985             'size' => 0\r
986         );\r
987         if (is_string($file)) {\r
988             if (!($fileData['fp'] = @fopen($file, 'rb'))) {\r
989                 $error = error_get_last();\r
990                 throw new HTTP_Request2_LogicException(\r
991                     $error['message'], HTTP_Request2_Exception::READ_ERROR\r
992                 );\r
993             }\r
994             if ($detectType) {\r
995                 $fileData['type'] = self::detectMimeType($file);\r
996             }\r
997         }\r
998         if (!($stat = fstat($fileData['fp']))) {\r
999             throw new HTTP_Request2_LogicException(\r
1000                 "fstat() call failed", HTTP_Request2_Exception::READ_ERROR\r
1001             );\r
1002         }\r
1003         $fileData['size'] = $stat['size'];\r
1004 \r
1005         return $fileData;\r
1006     }\r
1007 \r
1008     /**\r
1009      * Tries to detect MIME type of a file\r
1010      *\r
1011      * The method will try to use fileinfo extension if it is available,\r
1012      * deprecated mime_content_type() function in the other case. If neither\r
1013      * works, default 'application/octet-stream' MIME type is returned\r
1014      *\r
1015      * @param string $filename file name\r
1016      *\r
1017      * @return   string  file MIME type\r
1018      */\r
1019     protected static function detectMimeType($filename)\r
1020     {\r
1021         // finfo extension from PECL available\r
1022         if (function_exists('finfo_open')) {\r
1023             if (!isset(self::$_fileinfoDb)) {\r
1024                 self::$_fileinfoDb = @finfo_open(FILEINFO_MIME);\r
1025             }\r
1026             if (self::$_fileinfoDb) {\r
1027                 $info = finfo_file(self::$_fileinfoDb, $filename);\r
1028             }\r
1029         }\r
1030         // (deprecated) mime_content_type function available\r
1031         if (empty($info) && function_exists('mime_content_type')) {\r
1032             $info = mime_content_type($filename);\r
1033         }\r
1034         return empty($info)? 'application/octet-stream': $info;\r
1035     }\r
1036 }\r
1037 ?>\r