Request2.php 36 KB

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