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