3 * Class representing a HTTP request message
\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
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
22 * A class representing an URL as per RFC 3986.
\r
24 if (!class_exists('Net_URL2', true)) {
\r
25 require_once 'Net/URL2.php';
\r
29 * Exception class for HTTP_Request2 package
\r
31 require_once 'HTTP/Request2/Exception.php';
\r
34 * Class representing a HTTP request message
\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
44 class HTTP_Request2 implements SplSubject
\r
47 * Constants for HTTP request methods
\r
49 * @link http://tools.ietf.org/html/rfc2616#section-5.1.1
\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
62 * Constants for HTTP authentication schemes
\r
64 * @link http://tools.ietf.org/html/rfc2617
\r
66 const AUTH_BASIC = 'basic';
\r
67 const AUTH_DIGEST = 'digest';
\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
74 const REGEXP_INVALID_TOKEN = '![\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]!';
\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
81 const REGEXP_INVALID_COOKIE = '/[\s,;]/';
\r
84 * Fileinfo magic database resource
\r
86 * @see detectMimeType()
\r
88 private static $_fileinfoDb;
\r
91 * Observers attached to the request (instances of SplObserver)
\r
94 protected $observers = array();
\r
106 protected $method = self::METHOD_GET;
\r
109 * Authentication data
\r
119 protected $headers = array();
\r
122 * Configuration parameters
\r
126 protected $config = array(
\r
127 'adapter' => 'HTTP_Request2_Adapter_Socket',
\r
128 'connect_timeout' => 10,
\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
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
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
150 'digest_compat_ie' => false,
\r
152 'follow_redirects' => false,
\r
153 'max_redirects' => 5,
\r
154 'strict_redirects' => false
\r
158 * Last event in request / response handling, intended for observers
\r
160 * @see getLastEvent()
\r
162 protected $lastEvent = array(
\r
169 * @var string|resource
\r
172 protected $body = '';
\r
175 * Array of POST parameters
\r
178 protected $postParams = array();
\r
181 * Array of file uploads (for multipart/form-data POST requests)
\r
184 protected $uploads = array();
\r
187 * Adapter used to perform actual HTTP request
\r
188 * @var HTTP_Request2_Adapter
\r
190 protected $adapter;
\r
193 * Cookie jar to persist cookies between requests
\r
194 * @var HTTP_Request2_CookieJar
\r
196 protected $cookieJar = null;
\r
199 * Constructor. Can set request URL, method and configuration array.
\r
201 * Also sets a default value for User-Agent header.
\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
207 public function __construct(
\r
208 $url = null, $method = self::METHOD_GET, array $config = array()
\r
210 $this->setConfig($config);
\r
211 if (!empty($url)) {
\r
212 $this->setUrl($url);
\r
214 if (!empty($method)) {
\r
215 $this->setMethod($method);
\r
218 'user-agent', 'HTTP_Request2/2.3.0 ' .
\r
219 '(http://pear.php.net/package/http_request2) PHP/' . phpversion()
\r
224 * Sets the URL for this request
\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
230 * @param string|Net_URL2 $url Request URL
\r
232 * @return HTTP_Request2
\r
233 * @throws HTTP_Request2_LogicException
\r
235 public function setUrl($url)
\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
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
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
255 if ('' == $url->getPath()) {
\r
256 $url->setPath('/');
\r
264 * Returns the request URL
\r
268 public function getUrl()
\r
274 * Sets the request method
\r
276 * @param string $method one of the methods defined in RFC 2616
\r
278 * @return HTTP_Request2
\r
279 * @throws HTTP_Request2_LogicException if the method name is invalid
\r
281 public function setMethod($method)
\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
290 $this->method = $method;
\r
296 * Returns the request method
\r
300 public function getMethod()
\r
302 return $this->method;
\r
306 * Sets the configuration parameter(s)
\r
308 * The following parameters are available:
\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
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
356 * @return HTTP_Request2
\r
357 * @throws HTTP_Request2_LogicException If the parameter is unknown
\r
359 public function setConfig($nameOrConfig, $value = null)
\r
361 if (is_array($nameOrConfig)) {
\r
362 foreach ($nameOrConfig as $name => $value) {
\r
363 $this->setConfig($name, $value);
\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
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
383 $this->config[$nameOrConfig] = $value;
\r
390 * Returns the value(s) of the configuration parameter(s)
\r
392 * @param string $name parameter name
\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
398 public function getConfig($name = null)
\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
408 return $this->config[$name];
\r
412 * Sets the autentification data
\r
414 * @param string $user user name
\r
415 * @param string $password password
\r
416 * @param string $scheme authentication scheme
\r
418 * @return HTTP_Request2
\r
420 public function setAuth($user, $password = '', $scheme = self::AUTH_BASIC)
\r
422 if (empty($user)) {
\r
423 $this->auth = null;
\r
425 $this->auth = array(
\r
426 'user' => (string)$user,
\r
427 'password' => (string)$password,
\r
428 'scheme' => $scheme
\r
436 * Returns the authentication data
\r
438 * The array has the keys 'user', 'password' and 'scheme', where 'scheme'
\r
439 * is one of the HTTP_Request2::AUTH_* constants.
\r
443 public function getAuth()
\r
445 return $this->auth;
\r
449 * Sets request header(s)
\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
457 * Note that headers are treated case insensitively as per RFC 2616.
\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
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
473 * @return HTTP_Request2
\r
474 * @throws HTTP_Request2_LogicException
\r
476 public function setHeader($name, $value = null, $replace = true)
\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
483 $this->setHeader($v, null, $replace);
\r
487 if (null === $value && strpos($name, ':')) {
\r
488 list($name, $value) = array_map('trim', explode(':', $name, 2));
\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
497 // Header names are case insensitive anyway
\r
498 $name = strtolower($name);
\r
499 if (null === $value) {
\r
500 unset($this->headers[$name]);
\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
508 if (!isset($this->headers[$name]) || $replace) {
\r
509 $this->headers[$name] = $value;
\r
511 $this->headers[$name] .= ', ' . $value;
\r
520 * Returns the request headers
\r
522 * The array is of the form ('header name' => 'header value'), header names
\r
527 public function getHeaders()
\r
529 return $this->headers;
\r
533 * Adds a cookie to the request
\r
535 * If the request does not have a CookieJar object set, this method simply
\r
536 * appends a cookie to "Cookie:" header.
\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
543 * @param string $name cookie name
\r
544 * @param string $value cookie value
\r
546 * @return HTTP_Request2
\r
547 * @throws HTTP_Request2_LogicException
\r
548 * @see setCookieJar()
\r
550 public function addCookie($name, $value)
\r
552 if (!empty($this->cookieJar)) {
\r
553 $this->cookieJar->store(
\r
554 array('name' => $name, 'value' => $value), $this->url
\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
565 $cookies = empty($this->headers['cookie'])? '': $this->headers['cookie'] . '; ';
\r
566 $this->setHeader('cookie', $cookies . $cookie);
\r
573 * Sets the request body
\r
575 * If you provide file pointer rather than file name, it should support
\r
576 * fstat() and rewind() operations.
\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
584 * @return HTTP_Request2
\r
585 * @throws HTTP_Request2_LogicException
\r
587 public function setBody($body, $isFilename = false)
\r
589 if (!$isFilename && !is_resource($body)) {
\r
590 if (!$body instanceof HTTP_Request2_MultipartBody) {
\r
591 $this->body = (string)$body;
\r
593 $this->body = $body;
\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
602 $this->postParams = $this->uploads = array();
\r
608 * Returns the request body
\r
610 * @return string|resource|HTTP_Request2_MultipartBody
\r
612 public function getBody()
\r
614 if (self::METHOD_POST == $this->method
\r
615 && (!empty($this->postParams) || !empty($this->uploads))
\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
622 // support RFC 3986 by not encoding '~' symbol (request #15368)
\r
623 return str_replace('%7E', '~', $body);
\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
632 return $this->body;
\r
636 * Adds a file to form-based file upload
\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
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
644 * If you provide file pointers rather than file names, they should support
\r
645 * fstat() and rewind() operations.
\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
653 * @return HTTP_Request2
\r
654 * @throws HTTP_Request2_LogicException
\r
656 public function addUpload(
\r
657 $fieldName, $filename, $sendFilename = null, $contentType = null
\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
669 $fps = $names = $sizes = $types = array();
\r
670 foreach ($filename as $f) {
\r
671 if (!is_array($f)) {
\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
681 $this->uploads[$fieldName] = array(
\r
682 'fp' => $fps, 'filename' => $names, 'size' => $sizes, 'type' => $types
\r
685 if (empty($this->headers['content-type'])
\r
686 || 'application/x-www-form-urlencoded' == $this->headers['content-type']
\r
688 $this->setHeader('content-type', 'multipart/form-data');
\r
695 * Adds POST parameter(s) to the request.
\r
697 * @param string|array $name parameter name or array ('name' => 'value')
\r
698 * @param mixed $value parameter value (can be an array)
\r
700 * @return HTTP_Request2
\r
702 public function addPostParameter($name, $value = null)
\r
704 if (!is_array($name)) {
\r
705 $this->postParams[$name] = $value;
\r
707 foreach ($name as $k => $v) {
\r
708 $this->addPostParameter($k, $v);
\r
711 if (empty($this->headers['content-type'])) {
\r
712 $this->setHeader('content-type', 'application/x-www-form-urlencoded');
\r
719 * Attaches a new observer
\r
721 * @param SplObserver $observer any object implementing SplObserver
\r
723 public function attach(SplObserver $observer)
\r
725 foreach ($this->observers as $attached) {
\r
726 if ($attached === $observer) {
\r
730 $this->observers[] = $observer;
\r
734 * Detaches an existing observer
\r
736 * @param SplObserver $observer any object implementing SplObserver
\r
738 public function detach(SplObserver $observer)
\r
740 foreach ($this->observers as $key => $attached) {
\r
741 if ($attached === $observer) {
\r
742 unset($this->observers[$key]);
\r
749 * Notifies all observers
\r
751 public function notify()
\r
753 foreach ($this->observers as $observer) {
\r
754 $observer->update($this);
\r
759 * Sets the last event
\r
761 * Adapters should use this method to set the current state of the request
\r
762 * and notify the observers.
\r
764 * @param string $name event name
\r
765 * @param mixed $data event data
\r
767 public function setLastEvent($name, $data = null)
\r
769 $this->lastEvent = array(
\r
777 * Returns the last event
\r
779 * Observers should use this method to access the last change in request.
\r
780 * The following event names are possible:
\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
805 * Different adapters may not send all the event types. Mock adapter does
\r
806 * not send any events to the observers.
\r
808 * @return array The array has two keys: 'name' and 'data'
\r
810 public function getLastEvent()
\r
812 return $this->lastEvent;
\r
816 * Sets the adapter used to actually perform the request
\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
823 * $request->setAdapter('curl');
\r
827 * @param string|HTTP_Request2_Adapter $adapter Adapter to use
\r
829 * @return HTTP_Request2
\r
830 * @throws HTTP_Request2_LogicException
\r
832 public function setAdapter($adapter)
\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
839 if (!class_exists($adapter, false)
\r
840 && preg_match('/^HTTP_Request2_Adapter_([a-zA-Z0-9]+)$/', $adapter)
\r
842 include_once str_replace('_', DIRECTORY_SEPARATOR, $adapter) . '.php';
\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
851 $adapter = new $adapter;
\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
859 $this->adapter = $adapter;
\r
865 * Sets the cookie jar
\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
871 * @param HTTP_Request2_CookieJar|bool $jar Existing CookieJar object, true to
\r
872 * create a new one, false to remove
\r
874 * @return HTTP_Request2
\r
875 * @throws HTTP_Request2_LogicException
\r
877 public function setCookieJar($jar = true)
\r
879 if (!class_exists('HTTP_Request2_CookieJar', false)) {
\r
880 require_once 'HTTP/Request2/CookieJar.php';
\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
888 $this->cookieJar = null;
\r
890 throw new HTTP_Request2_LogicException(
\r
891 'Invalid parameter passed to setCookieJar()',
\r
892 HTTP_Request2_Exception::INVALID_ARGUMENT
\r
900 * Returns current CookieJar object or null if none
\r
902 * @return HTTP_Request2_CookieJar|null
\r
904 public function getCookieJar()
\r
906 return $this->cookieJar;
\r
910 * Sends the request and returns the response
\r
912 * @throws HTTP_Request2_Exception
\r
913 * @return HTTP_Request2_Response
\r
915 public function send()
\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
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
927 HTTP_Request2_Exception::INVALID_ARGUMENT
\r
930 if (empty($this->adapter)) {
\r
931 $this->setAdapter($this->getConfig('adapter'));
\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
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
946 $response = $this->adapter->sendRequest($this);
\r
947 } catch (Exception $e) {
\r
949 // cleanup in either case (poor man's "finally" clause)
\r
950 if ($magicQuotes) {
\r
951 set_magic_quotes_runtime(true);
\r
953 if (!empty($oldEncoding)) {
\r
954 mb_internal_encoding($oldEncoding);
\r
956 // rethrow the exception
\r
964 * Wrapper around fopen()/fstat() used by setBody() and addUpload()
\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
971 * @return array array('fp' => file pointer, 'size' => file size, 'type' => MIME type)
\r
972 * @throws HTTP_Request2_LogicException
\r
974 protected function fopenWrapper($file, $detectType = false)
\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
983 'fp' => is_string($file)? null: $file,
\r
984 'type' => 'application/octet-stream',
\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
995 $fileData['type'] = self::detectMimeType($file);
\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
1003 $fileData['size'] = $stat['size'];
\r
1009 * Tries to detect MIME type of a file
\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
1015 * @param string $filename file name
\r
1017 * @return string file MIME type
\r
1019 protected static function detectMimeType($filename)
\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
1026 if (self::$_fileinfoDb) {
\r
1027 $info = finfo_file(self::$_fileinfoDb, $filename);
\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
1034 return empty($info)? 'application/octet-stream': $info;
\r