Request2.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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)
  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)
  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()
  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. // magic_quotes_runtime may break file uploads and chunked response
  869. // processing; see bug #4543. Don't use ini_get() here; see bug #16440.
  870. if ($magicQuotes = get_magic_quotes_runtime()) {
  871. set_magic_quotes_runtime(false);
  872. }
  873. // force using single byte encoding if mbstring extension overloads
  874. // strlen() and substr(); see bug #1781, bug #10605
  875. if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {
  876. $oldEncoding = mb_internal_encoding();
  877. mb_internal_encoding('8bit');
  878. }
  879. try {
  880. $response = $this->adapter->sendRequest($this);
  881. } catch (Exception $e) {
  882. }
  883. // cleanup in either case (poor man's "finally" clause)
  884. if ($magicQuotes) {
  885. set_magic_quotes_runtime(true);
  886. }
  887. if (!empty($oldEncoding)) {
  888. mb_internal_encoding($oldEncoding);
  889. }
  890. // rethrow the exception
  891. if (!empty($e)) {
  892. throw $e;
  893. }
  894. return $response;
  895. }
  896. /**
  897. * Wrapper around fopen()/fstat() used by setBody() and addUpload()
  898. *
  899. * @param string|resource $file file name or pointer to open file
  900. * @param bool $detectType whether to try autodetecting MIME
  901. * type of file, will only work if $file is a
  902. * filename, not pointer
  903. *
  904. * @return array array('fp' => file pointer, 'size' => file size, 'type' => MIME type)
  905. * @throws HTTP_Request2_LogicException
  906. */
  907. protected function fopenWrapper($file, $detectType = false)
  908. {
  909. if (!is_string($file) && !is_resource($file)) {
  910. throw new HTTP_Request2_LogicException(
  911. "Filename or file pointer resource expected",
  912. HTTP_Request2_Exception::INVALID_ARGUMENT
  913. );
  914. }
  915. $fileData = array(
  916. 'fp' => is_string($file)? null: $file,
  917. 'type' => 'application/octet-stream',
  918. 'size' => 0
  919. );
  920. if (is_string($file)) {
  921. if (!($fileData['fp'] = @fopen($file, 'rb'))) {
  922. $error = error_get_last();
  923. throw new HTTP_Request2_LogicException(
  924. $error['message'], HTTP_Request2_Exception::READ_ERROR
  925. );
  926. }
  927. if ($detectType) {
  928. $fileData['type'] = self::detectMimeType($file);
  929. }
  930. }
  931. if (!($stat = fstat($fileData['fp']))) {
  932. throw new HTTP_Request2_LogicException(
  933. "fstat() call failed", HTTP_Request2_Exception::READ_ERROR
  934. );
  935. }
  936. $fileData['size'] = $stat['size'];
  937. return $fileData;
  938. }
  939. /**
  940. * Tries to detect MIME type of a file
  941. *
  942. * The method will try to use fileinfo extension if it is available,
  943. * deprecated mime_content_type() function in the other case. If neither
  944. * works, default 'application/octet-stream' MIME type is returned
  945. *
  946. * @param string $filename file name
  947. *
  948. * @return string file MIME type
  949. */
  950. protected static function detectMimeType($filename)
  951. {
  952. // finfo extension from PECL available
  953. if (function_exists('finfo_open')) {
  954. if (!isset(self::$_fileinfoDb)) {
  955. self::$_fileinfoDb = @finfo_open(FILEINFO_MIME);
  956. }
  957. if (self::$_fileinfoDb) {
  958. $info = finfo_file(self::$_fileinfoDb, $filename);
  959. }
  960. }
  961. // (deprecated) mime_content_type function available
  962. if (empty($info) && function_exists('mime_content_type')) {
  963. $info = mime_content_type($filename);
  964. }
  965. return empty($info)? 'application/octet-stream': $info;
  966. }
  967. }
  968. ?>