3 * Class representing a HTTP request message
\r
9 * Copyright (c) 2008-2012, Alexey Borzov <avb@php.net>
\r
10 * All rights reserved.
\r
12 * Redistribution and use in source and binary forms, with or without
\r
13 * modification, are permitted provided that the following conditions
\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
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
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
45 * A class representing an URL as per RFC 3986.
\r
47 require_once 'Net/URL2.php';
\r
50 * Exception class for HTTP_Request2 package
\r
52 require_once 'HTTP/Request2/Exception.php';
\r
55 * Class representing a HTTP request message
\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
65 class HTTP_Request2 implements SplSubject
\r
68 * Constants for HTTP request methods
\r
70 * @link http://tools.ietf.org/html/rfc2616#section-5.1.1
\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
83 * Constants for HTTP authentication schemes
\r
85 * @link http://tools.ietf.org/html/rfc2617
\r
87 const AUTH_BASIC = 'basic';
\r
88 const AUTH_DIGEST = 'digest';
\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
95 const REGEXP_INVALID_TOKEN = '![\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]!';
\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
102 const REGEXP_INVALID_COOKIE = '/[\s,;]/';
\r
105 * Fileinfo magic database resource
\r
107 * @see detectMimeType()
\r
109 private static $_fileinfoDb;
\r
112 * Observers attached to the request (instances of SplObserver)
\r
115 protected $observers = array();
\r
127 protected $method = self::METHOD_GET;
\r
130 * Authentication data
\r
140 protected $headers = array();
\r
143 * Configuration parameters
\r
147 protected $config = array(
\r
148 'adapter' => 'HTTP_Request2_Adapter_Socket',
\r
149 'connect_timeout' => 10,
\r
151 'use_brackets' => true,
\r
152 'protocol_version' => '1.1',
\r
153 'buffer_size' => 16384,
\r
154 'store_body' => true,
\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
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
170 'digest_compat_ie' => false,
\r
172 'follow_redirects' => false,
\r
173 'max_redirects' => 5,
\r
174 'strict_redirects' => false
\r
178 * Last event in request / response handling, intended for observers
\r
180 * @see getLastEvent()
\r
182 protected $lastEvent = array(
\r
189 * @var string|resource
\r
192 protected $body = '';
\r
195 * Array of POST parameters
\r
198 protected $postParams = array();
\r
201 * Array of file uploads (for multipart/form-data POST requests)
\r
204 protected $uploads = array();
\r
207 * Adapter used to perform actual HTTP request
\r
208 * @var HTTP_Request2_Adapter
\r
210 protected $adapter;
\r
213 * Cookie jar to persist cookies between requests
\r
214 * @var HTTP_Request2_CookieJar
\r
216 protected $cookieJar = null;
\r
219 * Constructor. Can set request URL, method and configuration array.
\r
221 * Also sets a default value for User-Agent header.
\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
227 public function __construct(
\r
228 $url = null, $method = self::METHOD_GET, array $config = array()
\r
230 $this->setConfig($config);
\r
231 if (!empty($url)) {
\r
232 $this->setUrl($url);
\r
234 if (!empty($method)) {
\r
235 $this->setMethod($method);
\r
238 'user-agent', 'HTTP_Request2/2.1.1 ' .
\r
239 '(http://pear.php.net/package/http_request2) PHP/' . phpversion()
\r
244 * Sets the URL for this request
\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
250 * @param string|Net_URL2 $url Request URL
\r
252 * @return HTTP_Request2
\r
253 * @throws HTTP_Request2_LogicException
\r
255 public function setUrl($url)
\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
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
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
275 if ('' == $url->getPath()) {
\r
276 $url->setPath('/');
\r
284 * Returns the request URL
\r
288 public function getUrl()
\r
294 * Sets the request method
\r
296 * @param string $method one of the methods defined in RFC 2616
\r
298 * @return HTTP_Request2
\r
299 * @throws HTTP_Request2_LogicException if the method name is invalid
\r
301 public function setMethod($method)
\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
310 $this->method = $method;
\r
316 * Returns the request method
\r
320 public function getMethod()
\r
322 return $this->method;
\r
326 * Sets the configuration parameter(s)
\r
328 * The following parameters are available:
\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
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
374 * @return HTTP_Request2
\r
375 * @throws HTTP_Request2_LogicException If the parameter is unknown
\r
377 public function setConfig($nameOrConfig, $value = null)
\r
379 if (is_array($nameOrConfig)) {
\r
380 foreach ($nameOrConfig as $name => $value) {
\r
381 $this->setConfig($name, $value);
\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
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
401 $this->config[$nameOrConfig] = $value;
\r
408 * Returns the value(s) of the configuration parameter(s)
\r
410 * @param string $name parameter name
\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
416 public function getConfig($name = null)
\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
426 return $this->config[$name];
\r
430 * Sets the autentification data
\r
432 * @param string $user user name
\r
433 * @param string $password password
\r
434 * @param string $scheme authentication scheme
\r
436 * @return HTTP_Request2
\r
438 public function setAuth($user, $password = '', $scheme = self::AUTH_BASIC)
\r
440 if (empty($user)) {
\r
441 $this->auth = null;
\r
443 $this->auth = array(
\r
444 'user' => (string)$user,
\r
445 'password' => (string)$password,
\r
446 'scheme' => $scheme
\r
454 * Returns the authentication data
\r
456 * The array has the keys 'user', 'password' and 'scheme', where 'scheme'
\r
457 * is one of the HTTP_Request2::AUTH_* constants.
\r
461 public function getAuth()
\r
463 return $this->auth;
\r
467 * Sets request header(s)
\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
475 * Note that headers are treated case insensitively as per RFC 2616.
\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
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
491 * @return HTTP_Request2
\r
492 * @throws HTTP_Request2_LogicException
\r
494 public function setHeader($name, $value = null, $replace = true)
\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
501 $this->setHeader($v, null, $replace);
\r
505 if (null === $value && strpos($name, ':')) {
\r
506 list($name, $value) = array_map('trim', explode(':', $name, 2));
\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
515 // Header names are case insensitive anyway
\r
516 $name = strtolower($name);
\r
517 if (null === $value) {
\r
518 unset($this->headers[$name]);
\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
526 if (!isset($this->headers[$name]) || $replace) {
\r
527 $this->headers[$name] = $value;
\r
529 $this->headers[$name] .= ', ' . $value;
\r
538 * Returns the request headers
\r
540 * The array is of the form ('header name' => 'header value'), header names
\r
545 public function getHeaders()
\r
547 return $this->headers;
\r
551 * Adds a cookie to the request
\r
553 * If the request does not have a CookieJar object set, this method simply
\r
554 * appends a cookie to "Cookie:" header.
\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
561 * @param string $name cookie name
\r
562 * @param string $value cookie value
\r
564 * @return HTTP_Request2
\r
565 * @throws HTTP_Request2_LogicException
\r
566 * @see setCookieJar()
\r
568 public function addCookie($name, $value)
\r
570 if (!empty($this->cookieJar)) {
\r
571 $this->cookieJar->store(
\r
572 array('name' => $name, 'value' => $value), $this->url
\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
583 $cookies = empty($this->headers['cookie'])? '': $this->headers['cookie'] . '; ';
\r
584 $this->setHeader('cookie', $cookies . $cookie);
\r
591 * Sets the request body
\r
593 * If you provide file pointer rather than file name, it should support
\r
594 * fstat() and rewind() operations.
\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
602 * @return HTTP_Request2
\r
603 * @throws HTTP_Request2_LogicException
\r
605 public function setBody($body, $isFilename = false)
\r
607 if (!$isFilename && !is_resource($body)) {
\r
608 if (!$body instanceof HTTP_Request2_MultipartBody) {
\r
609 $this->body = (string)$body;
\r
611 $this->body = $body;
\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
620 $this->postParams = $this->uploads = array();
\r
626 * Returns the request body
\r
628 * @return string|resource|HTTP_Request2_MultipartBody
\r
630 public function getBody()
\r
632 if (self::METHOD_POST == $this->method
\r
633 && (!empty($this->postParams) || !empty($this->uploads))
\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
640 // support RFC 3986 by not encoding '~' symbol (request #15368)
\r
641 return str_replace('%7E', '~', $body);
\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
650 return $this->body;
\r
654 * Adds a file to form-based file upload
\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
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
662 * If you provide file pointers rather than file names, they should support
\r
663 * fstat() and rewind() operations.
\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
671 * @return HTTP_Request2
\r
672 * @throws HTTP_Request2_LogicException
\r
674 public function addUpload(
\r
675 $fieldName, $filename, $sendFilename = null, $contentType = null
\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
687 $fps = $names = $sizes = $types = array();
\r
688 foreach ($filename as $f) {
\r
689 if (!is_array($f)) {
\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
699 $this->uploads[$fieldName] = array(
\r
700 'fp' => $fps, 'filename' => $names, 'size' => $sizes, 'type' => $types
\r
703 if (empty($this->headers['content-type'])
\r
704 || 'application/x-www-form-urlencoded' == $this->headers['content-type']
\r
706 $this->setHeader('content-type', 'multipart/form-data');
\r
713 * Adds POST parameter(s) to the request.
\r
715 * @param string|array $name parameter name or array ('name' => 'value')
\r
716 * @param mixed $value parameter value (can be an array)
\r
718 * @return HTTP_Request2
\r
720 public function addPostParameter($name, $value = null)
\r
722 if (!is_array($name)) {
\r
723 $this->postParams[$name] = $value;
\r
725 foreach ($name as $k => $v) {
\r
726 $this->addPostParameter($k, $v);
\r
729 if (empty($this->headers['content-type'])) {
\r
730 $this->setHeader('content-type', 'application/x-www-form-urlencoded');
\r
737 * Attaches a new observer
\r
739 * @param SplObserver $observer any object implementing SplObserver
\r
741 public function attach(SplObserver $observer)
\r
743 foreach ($this->observers as $attached) {
\r
744 if ($attached === $observer) {
\r
748 $this->observers[] = $observer;
\r
752 * Detaches an existing observer
\r
754 * @param SplObserver $observer any object implementing SplObserver
\r
756 public function detach(SplObserver $observer)
\r
758 foreach ($this->observers as $key => $attached) {
\r
759 if ($attached === $observer) {
\r
760 unset($this->observers[$key]);
\r
767 * Notifies all observers
\r
769 public function notify()
\r
771 foreach ($this->observers as $observer) {
\r
772 $observer->update($this);
\r
777 * Sets the last event
\r
779 * Adapters should use this method to set the current state of the request
\r
780 * and notify the observers.
\r
782 * @param string $name event name
\r
783 * @param mixed $data event data
\r
785 public function setLastEvent($name, $data = null)
\r
787 $this->lastEvent = array(
\r
795 * Returns the last event
\r
797 * Observers should use this method to access the last change in request.
\r
798 * The following event names are possible:
\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
818 * Different adapters may not send all the event types. Mock adapter does
\r
819 * not send any events to the observers.
\r
821 * @return array The array has two keys: 'name' and 'data'
\r
823 public function getLastEvent()
\r
825 return $this->lastEvent;
\r
829 * Sets the adapter used to actually perform the request
\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
836 * $request->setAdapter('curl');
\r
840 * @param string|HTTP_Request2_Adapter $adapter Adapter to use
\r
842 * @return HTTP_Request2
\r
843 * @throws HTTP_Request2_LogicException
\r
845 public function setAdapter($adapter)
\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
852 if (!class_exists($adapter, false)
\r
853 && preg_match('/^HTTP_Request2_Adapter_([a-zA-Z0-9]+)$/', $adapter)
\r
855 include_once str_replace('_', DIRECTORY_SEPARATOR, $adapter) . '.php';
\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
864 $adapter = new $adapter;
\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
872 $this->adapter = $adapter;
\r
878 * Sets the cookie jar
\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
884 * @param HTTP_Request2_CookieJar|bool $jar Existing CookieJar object, true to
\r
885 * create a new one, false to remove
\r
887 * @return HTTP_Request2
\r
888 * @throws HTTP_Request2_LogicException
\r
890 public function setCookieJar($jar = true)
\r
892 if (!class_exists('HTTP_Request2_CookieJar', false)) {
\r
893 require_once 'HTTP/Request2/CookieJar.php';
\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
901 $this->cookieJar = null;
\r
903 throw new HTTP_Request2_LogicException(
\r
904 'Invalid parameter passed to setCookieJar()',
\r
905 HTTP_Request2_Exception::INVALID_ARGUMENT
\r
913 * Returns current CookieJar object or null if none
\r
915 * @return HTTP_Request2_CookieJar|null
\r
917 public function getCookieJar()
\r
919 return $this->cookieJar;
\r
923 * Sends the request and returns the response
\r
925 * @throws HTTP_Request2_Exception
\r
926 * @return HTTP_Request2_Response
\r
928 public function send()
\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
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
940 HTTP_Request2_Exception::INVALID_ARGUMENT
\r
943 if (empty($this->adapter)) {
\r
944 $this->setAdapter($this->getConfig('adapter'));
\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
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
959 $response = $this->adapter->sendRequest($this);
\r
960 } catch (Exception $e) {
\r
962 // cleanup in either case (poor man's "finally" clause)
\r
963 if ($magicQuotes) {
\r
964 set_magic_quotes_runtime(true);
\r
966 if (!empty($oldEncoding)) {
\r
967 mb_internal_encoding($oldEncoding);
\r
969 // rethrow the exception
\r
977 * Wrapper around fopen()/fstat() used by setBody() and addUpload()
\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
984 * @return array array('fp' => file pointer, 'size' => file size, 'type' => MIME type)
\r
985 * @throws HTTP_Request2_LogicException
\r
987 protected function fopenWrapper($file, $detectType = false)
\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
996 'fp' => is_string($file)? null: $file,
\r
997 'type' => 'application/octet-stream',
\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
1007 if ($detectType) {
\r
1008 $fileData['type'] = self::detectMimeType($file);
\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
1016 $fileData['size'] = $stat['size'];
\r
1022 * Tries to detect MIME type of a file
\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
1028 * @param string $filename file name
\r
1030 * @return string file MIME type
\r
1032 protected static function detectMimeType($filename)
\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
1039 if (self::$_fileinfoDb) {
\r
1040 $info = finfo_file(self::$_fileinfoDb, $filename);
\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
1047 return empty($info)? 'application/octet-stream': $info;
\r