Request2.php 36 KB

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