PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Zend/Http/Client.php

https://bitbucket.org/sunil_nextbits/magento2
PHP | 1457 lines | 685 code | 188 blank | 584 comment | 168 complexity | fec80146cf44ae998200fc143a04ef21 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Http
  17. * @subpackage Client
  18. * @version $Id: Client.php 23443 2010-11-24 11:53:13Z shahar $
  19. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  20. * @license http://framework.zend.com/license/new-bsd New BSD License
  21. */
  22. /**
  23. * @see Zend_Loader
  24. */
  25. #require_once 'Zend/Loader.php';
  26. /**
  27. * @see Zend_Uri
  28. */
  29. #require_once 'Zend/Uri.php';
  30. /**
  31. * @see Zend_Http_Client_Adapter_Interface
  32. */
  33. #require_once 'Zend/Http/Client/Adapter/Interface.php';
  34. /**
  35. * @see Zend_Http_Response
  36. */
  37. #require_once 'Zend/Http/Response.php';
  38. /**
  39. * @see Zend_Http_Response_Stream
  40. */
  41. #require_once 'Zend/Http/Response/Stream.php';
  42. /**
  43. * Zend_Http_Client is an implementation of an HTTP client in PHP. The client
  44. * supports basic features like sending different HTTP requests and handling
  45. * redirections, as well as more advanced features like proxy settings, HTTP
  46. * authentication and cookie persistence (using a Zend_Http_CookieJar object)
  47. *
  48. * @todo Implement proxy settings
  49. * @category Zend
  50. * @package Zend_Http
  51. * @subpackage Client
  52. * @throws Zend_Http_Client_Exception
  53. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  54. * @license http://framework.zend.com/license/new-bsd New BSD License
  55. */
  56. class Zend_Http_Client
  57. {
  58. /**
  59. * HTTP request methods
  60. */
  61. const GET = 'GET';
  62. const POST = 'POST';
  63. const PUT = 'PUT';
  64. const HEAD = 'HEAD';
  65. const DELETE = 'DELETE';
  66. const TRACE = 'TRACE';
  67. const OPTIONS = 'OPTIONS';
  68. const CONNECT = 'CONNECT';
  69. const MERGE = 'MERGE';
  70. /**
  71. * Supported HTTP Authentication methods
  72. */
  73. const AUTH_BASIC = 'basic';
  74. //const AUTH_DIGEST = 'digest'; <-- not implemented yet
  75. /**
  76. * HTTP protocol versions
  77. */
  78. const HTTP_1 = '1.1';
  79. const HTTP_0 = '1.0';
  80. /**
  81. * Content attributes
  82. */
  83. const CONTENT_TYPE = 'Content-Type';
  84. const CONTENT_LENGTH = 'Content-Length';
  85. /**
  86. * POST data encoding methods
  87. */
  88. const ENC_URLENCODED = 'application/x-www-form-urlencoded';
  89. const ENC_FORMDATA = 'multipart/form-data';
  90. /**
  91. * Configuration array, set using the constructor or using ::setConfig()
  92. *
  93. * @var array
  94. */
  95. protected $config = array(
  96. 'maxredirects' => 5,
  97. 'strictredirects' => false,
  98. 'useragent' => 'Zend_Http_Client',
  99. 'timeout' => 10,
  100. 'adapter' => 'Zend_Http_Client_Adapter_Socket',
  101. 'httpversion' => self::HTTP_1,
  102. 'keepalive' => false,
  103. 'storeresponse' => true,
  104. 'strict' => true,
  105. 'output_stream' => false,
  106. 'encodecookies' => true,
  107. 'rfc3986_strict' => false
  108. );
  109. /**
  110. * The adapter used to perform the actual connection to the server
  111. *
  112. * @var Zend_Http_Client_Adapter_Interface
  113. */
  114. protected $adapter = null;
  115. /**
  116. * Request URI
  117. *
  118. * @var Zend_Uri_Http
  119. */
  120. protected $uri = null;
  121. /**
  122. * Associative array of request headers
  123. *
  124. * @var array
  125. */
  126. protected $headers = array();
  127. /**
  128. * HTTP request method
  129. *
  130. * @var string
  131. */
  132. protected $method = self::GET;
  133. /**
  134. * Associative array of GET parameters
  135. *
  136. * @var array
  137. */
  138. protected $paramsGet = array();
  139. /**
  140. * Associative array of POST parameters
  141. *
  142. * @var array
  143. */
  144. protected $paramsPost = array();
  145. /**
  146. * Request body content type (for POST requests)
  147. *
  148. * @var string
  149. */
  150. protected $enctype = null;
  151. /**
  152. * The raw post data to send. Could be set by setRawData($data, $enctype).
  153. *
  154. * @var string
  155. */
  156. protected $raw_post_data = null;
  157. /**
  158. * HTTP Authentication settings
  159. *
  160. * Expected to be an associative array with this structure:
  161. * $this->auth = array('user' => 'username', 'password' => 'password', 'type' => 'basic')
  162. * Where 'type' should be one of the supported authentication types (see the AUTH_*
  163. * constants), for example 'basic' or 'digest'.
  164. *
  165. * If null, no authentication will be used.
  166. *
  167. * @var array|null
  168. */
  169. protected $auth;
  170. /**
  171. * File upload arrays (used in POST requests)
  172. *
  173. * An associative array, where each element is of the format:
  174. * 'name' => array('filename.txt', 'text/plain', 'This is the actual file contents')
  175. *
  176. * @var array
  177. */
  178. protected $files = array();
  179. /**
  180. * The client's cookie jar
  181. *
  182. * @var Zend_Http_CookieJar
  183. */
  184. protected $cookiejar = null;
  185. /**
  186. * The last HTTP request sent by the client, as string
  187. *
  188. * @var string
  189. */
  190. protected $last_request = null;
  191. /**
  192. * The last HTTP response received by the client
  193. *
  194. * @var Zend_Http_Response
  195. */
  196. protected $last_response = null;
  197. /**
  198. * Redirection counter
  199. *
  200. * @var int
  201. */
  202. protected $redirectCounter = 0;
  203. /**
  204. * Fileinfo magic database resource
  205. *
  206. * This variable is populated the first time _detectFileMimeType is called
  207. * and is then reused on every call to this method
  208. *
  209. * @var resource
  210. */
  211. static protected $_fileInfoDb = null;
  212. /**
  213. * Constructor method. Will create a new HTTP client. Accepts the target
  214. * URL and optionally configuration array.
  215. *
  216. * @param Zend_Uri_Http|string $uri
  217. * @param array $config Configuration key-value pairs.
  218. */
  219. public function __construct($uri = null, $config = null)
  220. {
  221. if ($uri !== null) {
  222. $this->setUri($uri);
  223. }
  224. if ($config !== null) {
  225. $this->setConfig($config);
  226. }
  227. }
  228. /**
  229. * Set the URI for the next request
  230. *
  231. * @param Zend_Uri_Http|string $uri
  232. * @return Zend_Http_Client
  233. * @throws Zend_Http_Client_Exception
  234. */
  235. public function setUri($uri)
  236. {
  237. if (is_string($uri)) {
  238. $uri = Zend_Uri::factory($uri);
  239. }
  240. if (!$uri instanceof Zend_Uri_Http) {
  241. /** @see Zend_Http_Client_Exception */
  242. #require_once 'Zend/Http/Client/Exception.php';
  243. throw new Zend_Http_Client_Exception('Passed parameter is not a valid HTTP URI.');
  244. }
  245. // Set auth if username and password has been specified in the uri
  246. if ($uri->getUsername() && $uri->getPassword()) {
  247. $this->setAuth($uri->getUsername(), $uri->getPassword());
  248. }
  249. // We have no ports, set the defaults
  250. if (! $uri->getPort()) {
  251. $uri->setPort(($uri->getScheme() == 'https' ? 443 : 80));
  252. }
  253. $this->uri = $uri;
  254. return $this;
  255. }
  256. /**
  257. * Get the URI for the next request
  258. *
  259. * @param boolean $as_string If true, will return the URI as a string
  260. * @return Zend_Uri_Http|string
  261. */
  262. public function getUri($as_string = false)
  263. {
  264. if ($as_string && $this->uri instanceof Zend_Uri_Http) {
  265. return $this->uri->__toString();
  266. } else {
  267. return $this->uri;
  268. }
  269. }
  270. /**
  271. * Set configuration parameters for this HTTP client
  272. *
  273. * @param Zend_Config | array $config
  274. * @return Zend_Http_Client
  275. * @throws Zend_Http_Client_Exception
  276. */
  277. public function setConfig($config = array())
  278. {
  279. if ($config instanceof Zend_Config) {
  280. $config = $config->toArray();
  281. } elseif (! is_array($config)) {
  282. /** @see Zend_Http_Client_Exception */
  283. #require_once 'Zend/Http/Client/Exception.php';
  284. throw new Zend_Http_Client_Exception('Array or Zend_Config object expected, got ' . gettype($config));
  285. }
  286. foreach ($config as $k => $v) {
  287. $this->config[strtolower($k)] = $v;
  288. }
  289. // Pass configuration options to the adapter if it exists
  290. if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) {
  291. $this->adapter->setConfig($config);
  292. }
  293. return $this;
  294. }
  295. /**
  296. * Set the next request's method
  297. *
  298. * Validated the passed method and sets it. If we have files set for
  299. * POST requests, and the new method is not POST, the files are silently
  300. * dropped.
  301. *
  302. * @param string $method
  303. * @return Zend_Http_Client
  304. * @throws Zend_Http_Client_Exception
  305. */
  306. public function setMethod($method = self::GET)
  307. {
  308. if (! preg_match('/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/', $method)) {
  309. /** @see Zend_Http_Client_Exception */
  310. #require_once 'Zend/Http/Client/Exception.php';
  311. throw new Zend_Http_Client_Exception("'{$method}' is not a valid HTTP request method.");
  312. }
  313. if ($method == self::POST && $this->enctype === null) {
  314. $this->setEncType(self::ENC_URLENCODED);
  315. }
  316. $this->method = $method;
  317. return $this;
  318. }
  319. /**
  320. * Set one or more request headers
  321. *
  322. * This function can be used in several ways to set the client's request
  323. * headers:
  324. * 1. By providing two parameters: $name as the header to set (e.g. 'Host')
  325. * and $value as it's value (e.g. 'www.example.com').
  326. * 2. By providing a single header string as the only parameter
  327. * e.g. 'Host: www.example.com'
  328. * 3. By providing an array of headers as the first parameter
  329. * e.g. array('host' => 'www.example.com', 'x-foo: bar'). In This case
  330. * the function will call itself recursively for each array item.
  331. *
  332. * @param string|array $name Header name, full header string ('Header: value')
  333. * or an array of headers
  334. * @param mixed $value Header value or null
  335. * @return Zend_Http_Client
  336. * @throws Zend_Http_Client_Exception
  337. */
  338. public function setHeaders($name, $value = null)
  339. {
  340. // If we got an array, go recursive!
  341. if (is_array($name)) {
  342. foreach ($name as $k => $v) {
  343. if (is_string($k)) {
  344. $this->setHeaders($k, $v);
  345. } else {
  346. $this->setHeaders($v, null);
  347. }
  348. }
  349. } else {
  350. // Check if $name needs to be split
  351. if ($value === null && (strpos($name, ':') > 0)) {
  352. list($name, $value) = explode(':', $name, 2);
  353. }
  354. // Make sure the name is valid if we are in strict mode
  355. if ($this->config['strict'] && (! preg_match('/^[a-zA-Z0-9-]+$/', $name))) {
  356. /** @see Zend_Http_Client_Exception */
  357. #require_once 'Zend/Http/Client/Exception.php';
  358. throw new Zend_Http_Client_Exception("{$name} is not a valid HTTP header name");
  359. }
  360. $normalized_name = strtolower($name);
  361. // If $value is null or false, unset the header
  362. if ($value === null || $value === false) {
  363. unset($this->headers[$normalized_name]);
  364. // Else, set the header
  365. } else {
  366. // Header names are stored lowercase internally.
  367. if (is_string($value)) {
  368. $value = trim($value);
  369. }
  370. $this->headers[$normalized_name] = array($name, $value);
  371. }
  372. }
  373. return $this;
  374. }
  375. /**
  376. * Get the value of a specific header
  377. *
  378. * Note that if the header has more than one value, an array
  379. * will be returned.
  380. *
  381. * @param string $key
  382. * @return string|array|null The header value or null if it is not set
  383. */
  384. public function getHeader($key)
  385. {
  386. $key = strtolower($key);
  387. if (isset($this->headers[$key])) {
  388. return $this->headers[$key][1];
  389. } else {
  390. return null;
  391. }
  392. }
  393. /**
  394. * Set a GET parameter for the request. Wrapper around _setParameter
  395. *
  396. * @param string|array $name
  397. * @param string $value
  398. * @return Zend_Http_Client
  399. */
  400. public function setParameterGet($name, $value = null)
  401. {
  402. if (is_array($name)) {
  403. foreach ($name as $k => $v)
  404. $this->_setParameter('GET', $k, $v);
  405. } else {
  406. $this->_setParameter('GET', $name, $value);
  407. }
  408. return $this;
  409. }
  410. /**
  411. * Set a POST parameter for the request. Wrapper around _setParameter
  412. *
  413. * @param string|array $name
  414. * @param string $value
  415. * @return Zend_Http_Client
  416. */
  417. public function setParameterPost($name, $value = null)
  418. {
  419. if (is_array($name)) {
  420. foreach ($name as $k => $v)
  421. $this->_setParameter('POST', $k, $v);
  422. } else {
  423. $this->_setParameter('POST', $name, $value);
  424. }
  425. return $this;
  426. }
  427. /**
  428. * Set a GET or POST parameter - used by SetParameterGet and SetParameterPost
  429. *
  430. * @param string $type GET or POST
  431. * @param string $name
  432. * @param string $value
  433. * @return null
  434. */
  435. protected function _setParameter($type, $name, $value)
  436. {
  437. $parray = array();
  438. $type = strtolower($type);
  439. switch ($type) {
  440. case 'get':
  441. $parray = &$this->paramsGet;
  442. break;
  443. case 'post':
  444. $parray = &$this->paramsPost;
  445. break;
  446. }
  447. if ($value === null) {
  448. if (isset($parray[$name])) unset($parray[$name]);
  449. } else {
  450. $parray[$name] = $value;
  451. }
  452. }
  453. /**
  454. * Get the number of redirections done on the last request
  455. *
  456. * @return int
  457. */
  458. public function getRedirectionsCount()
  459. {
  460. return $this->redirectCounter;
  461. }
  462. /**
  463. * Set HTTP authentication parameters
  464. *
  465. * $type should be one of the supported types - see the self::AUTH_*
  466. * constants.
  467. *
  468. * To enable authentication:
  469. * <code>
  470. * $this->setAuth('shahar', 'secret', Zend_Http_Client::AUTH_BASIC);
  471. * </code>
  472. *
  473. * To disable authentication:
  474. * <code>
  475. * $this->setAuth(false);
  476. * </code>
  477. *
  478. * @see http://www.faqs.org/rfcs/rfc2617.html
  479. * @param string|false $user User name or false disable authentication
  480. * @param string $password Password
  481. * @param string $type Authentication type
  482. * @return Zend_Http_Client
  483. * @throws Zend_Http_Client_Exception
  484. */
  485. public function setAuth($user, $password = '', $type = self::AUTH_BASIC)
  486. {
  487. // If we got false or null, disable authentication
  488. if ($user === false || $user === null) {
  489. $this->auth = null;
  490. // Clear the auth information in the uri instance as well
  491. if ($this->uri instanceof Zend_Uri_Http) {
  492. $this->getUri()->setUsername('');
  493. $this->getUri()->setPassword('');
  494. }
  495. // Else, set up authentication
  496. } else {
  497. // Check we got a proper authentication type
  498. if (! defined('self::AUTH_' . strtoupper($type))) {
  499. /** @see Zend_Http_Client_Exception */
  500. #require_once 'Zend/Http/Client/Exception.php';
  501. throw new Zend_Http_Client_Exception("Invalid or not supported authentication type: '$type'");
  502. }
  503. $this->auth = array(
  504. 'user' => (string) $user,
  505. 'password' => (string) $password,
  506. 'type' => $type
  507. );
  508. }
  509. return $this;
  510. }
  511. /**
  512. * Set the HTTP client's cookie jar.
  513. *
  514. * A cookie jar is an object that holds and maintains cookies across HTTP requests
  515. * and responses.
  516. *
  517. * @param Zend_Http_CookieJar|boolean $cookiejar Existing cookiejar object, true to create a new one, false to disable
  518. * @return Zend_Http_Client
  519. * @throws Zend_Http_Client_Exception
  520. */
  521. public function setCookieJar($cookiejar = true)
  522. {
  523. Zend_Loader::loadClass('Zend_Http_CookieJar');
  524. if ($cookiejar instanceof Zend_Http_CookieJar) {
  525. $this->cookiejar = $cookiejar;
  526. } elseif ($cookiejar === true) {
  527. $this->cookiejar = new Zend_Http_CookieJar();
  528. } elseif (! $cookiejar) {
  529. $this->cookiejar = null;
  530. } else {
  531. /** @see Zend_Http_Client_Exception */
  532. #require_once 'Zend/Http/Client/Exception.php';
  533. throw new Zend_Http_Client_Exception('Invalid parameter type passed as CookieJar');
  534. }
  535. return $this;
  536. }
  537. /**
  538. * Return the current cookie jar or null if none.
  539. *
  540. * @return Zend_Http_CookieJar|null
  541. */
  542. public function getCookieJar()
  543. {
  544. return $this->cookiejar;
  545. }
  546. /**
  547. * Add a cookie to the request. If the client has no Cookie Jar, the cookies
  548. * will be added directly to the headers array as "Cookie" headers.
  549. *
  550. * @param Zend_Http_Cookie|string $cookie
  551. * @param string|null $value If "cookie" is a string, this is the cookie value.
  552. * @return Zend_Http_Client
  553. * @throws Zend_Http_Client_Exception
  554. */
  555. public function setCookie($cookie, $value = null)
  556. {
  557. Zend_Loader::loadClass('Zend_Http_Cookie');
  558. if (is_array($cookie)) {
  559. foreach ($cookie as $c => $v) {
  560. if (is_string($c)) {
  561. $this->setCookie($c, $v);
  562. } else {
  563. $this->setCookie($v);
  564. }
  565. }
  566. return $this;
  567. }
  568. if ($value !== null && $this->config['encodecookies']) {
  569. $value = urlencode($value);
  570. }
  571. if (isset($this->cookiejar)) {
  572. if ($cookie instanceof Zend_Http_Cookie) {
  573. $this->cookiejar->addCookie($cookie);
  574. } elseif (is_string($cookie) && $value !== null) {
  575. $cookie = Zend_Http_Cookie::fromString("{$cookie}={$value}",
  576. $this->uri,
  577. $this->config['encodecookies']);
  578. $this->cookiejar->addCookie($cookie);
  579. }
  580. } else {
  581. if ($cookie instanceof Zend_Http_Cookie) {
  582. $name = $cookie->getName();
  583. $value = $cookie->getValue();
  584. $cookie = $name;
  585. }
  586. if (preg_match("/[=,; \t\r\n\013\014]/", $cookie)) {
  587. /** @see Zend_Http_Client_Exception */
  588. #require_once 'Zend/Http/Client/Exception.php';
  589. throw new Zend_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\013\014 ({$cookie})");
  590. }
  591. $value = addslashes($value);
  592. if (! isset($this->headers['cookie'])) {
  593. $this->headers['cookie'] = array('Cookie', '');
  594. }
  595. $this->headers['cookie'][1] .= $cookie . '=' . $value . '; ';
  596. }
  597. return $this;
  598. }
  599. /**
  600. * Set a file to upload (using a POST request)
  601. *
  602. * Can be used in two ways:
  603. *
  604. * 1. $data is null (default): $filename is treated as the name if a local file which
  605. * will be read and sent. Will try to guess the content type using mime_content_type().
  606. * 2. $data is set - $filename is sent as the file name, but $data is sent as the file
  607. * contents and no file is read from the file system. In this case, you need to
  608. * manually set the Content-Type ($ctype) or it will default to
  609. * application/octet-stream.
  610. *
  611. * @param string $filename Name of file to upload, or name to save as
  612. * @param string $formname Name of form element to send as
  613. * @param string $data Data to send (if null, $filename is read and sent)
  614. * @param string $ctype Content type to use (if $data is set and $ctype is
  615. * null, will be application/octet-stream)
  616. * @return Zend_Http_Client
  617. * @throws Zend_Http_Client_Exception
  618. */
  619. public function setFileUpload($filename, $formname, $data = null, $ctype = null)
  620. {
  621. if ($data === null) {
  622. if (($data = @file_get_contents($filename)) === false) {
  623. /** @see Zend_Http_Client_Exception */
  624. #require_once 'Zend/Http/Client/Exception.php';
  625. throw new Zend_Http_Client_Exception("Unable to read file '{$filename}' for upload");
  626. }
  627. if (! $ctype) {
  628. $ctype = $this->_detectFileMimeType($filename);
  629. }
  630. }
  631. // Force enctype to multipart/form-data
  632. $this->setEncType(self::ENC_FORMDATA);
  633. $this->files[] = array(
  634. 'formname' => $formname,
  635. 'filename' => basename($filename),
  636. 'ctype' => $ctype,
  637. 'data' => $data
  638. );
  639. return $this;
  640. }
  641. /**
  642. * Set the encoding type for POST data
  643. *
  644. * @param string $enctype
  645. * @return Zend_Http_Client
  646. */
  647. public function setEncType($enctype = self::ENC_URLENCODED)
  648. {
  649. $this->enctype = $enctype;
  650. return $this;
  651. }
  652. /**
  653. * Set the raw (already encoded) POST data.
  654. *
  655. * This function is here for two reasons:
  656. * 1. For advanced user who would like to set their own data, already encoded
  657. * 2. For backwards compatibilty: If someone uses the old post($data) method.
  658. * this method will be used to set the encoded data.
  659. *
  660. * $data can also be stream (such as file) from which the data will be read.
  661. *
  662. * @param string|resource $data
  663. * @param string $enctype
  664. * @return Zend_Http_Client
  665. */
  666. public function setRawData($data, $enctype = null)
  667. {
  668. $this->raw_post_data = $data;
  669. $this->setEncType($enctype);
  670. if (is_resource($data)) {
  671. // We've got stream data
  672. $stat = @fstat($data);
  673. if($stat) {
  674. $this->setHeaders(self::CONTENT_LENGTH, $stat['size']);
  675. }
  676. }
  677. return $this;
  678. }
  679. /**
  680. * Clear all GET and POST parameters
  681. *
  682. * Should be used to reset the request parameters if the client is
  683. * used for several concurrent requests.
  684. *
  685. * clearAll parameter controls if we clean just parameters or also
  686. * headers and last_*
  687. *
  688. * @param bool $clearAll Should all data be cleared?
  689. * @return Zend_Http_Client
  690. */
  691. public function resetParameters($clearAll = false)
  692. {
  693. // Reset parameter data
  694. $this->paramsGet = array();
  695. $this->paramsPost = array();
  696. $this->files = array();
  697. $this->raw_post_data = null;
  698. if($clearAll) {
  699. $this->headers = array();
  700. $this->last_request = null;
  701. $this->last_response = null;
  702. } else {
  703. // Clear outdated headers
  704. if (isset($this->headers[strtolower(self::CONTENT_TYPE)])) {
  705. unset($this->headers[strtolower(self::CONTENT_TYPE)]);
  706. }
  707. if (isset($this->headers[strtolower(self::CONTENT_LENGTH)])) {
  708. unset($this->headers[strtolower(self::CONTENT_LENGTH)]);
  709. }
  710. }
  711. return $this;
  712. }
  713. /**
  714. * Get the last HTTP request as string
  715. *
  716. * @return string
  717. */
  718. public function getLastRequest()
  719. {
  720. return $this->last_request;
  721. }
  722. /**
  723. * Get the last HTTP response received by this client
  724. *
  725. * If $config['storeresponse'] is set to false, or no response was
  726. * stored yet, will return null
  727. *
  728. * @return Zend_Http_Response or null if none
  729. */
  730. public function getLastResponse()
  731. {
  732. return $this->last_response;
  733. }
  734. /**
  735. * Load the connection adapter
  736. *
  737. * While this method is not called more than one for a client, it is
  738. * seperated from ->request() to preserve logic and readability
  739. *
  740. * @param Zend_Http_Client_Adapter_Interface|string $adapter
  741. * @return null
  742. * @throws Zend_Http_Client_Exception
  743. */
  744. public function setAdapter($adapter)
  745. {
  746. if (is_string($adapter)) {
  747. try {
  748. Zend_Loader::loadClass($adapter);
  749. } catch (Zend_Exception $e) {
  750. /** @see Zend_Http_Client_Exception */
  751. #require_once 'Zend/Http/Client/Exception.php';
  752. throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}", 0, $e);
  753. }
  754. $adapter = new $adapter;
  755. }
  756. if (! $adapter instanceof Zend_Http_Client_Adapter_Interface) {
  757. /** @see Zend_Http_Client_Exception */
  758. #require_once 'Zend/Http/Client/Exception.php';
  759. throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
  760. }
  761. $this->adapter = $adapter;
  762. $config = $this->config;
  763. unset($config['adapter']);
  764. $this->adapter->setConfig($config);
  765. }
  766. /**
  767. * Load the connection adapter
  768. *
  769. * @return Zend_Http_Client_Adapter_Interface $adapter
  770. */
  771. public function getAdapter()
  772. {
  773. return $this->adapter;
  774. }
  775. /**
  776. * Set streaming for received data
  777. *
  778. * @param string|boolean $streamfile Stream file, true for temp file, false/null for no streaming
  779. * @return Zend_Http_Client
  780. */
  781. public function setStream($streamfile = true)
  782. {
  783. $this->setConfig(array("output_stream" => $streamfile));
  784. return $this;
  785. }
  786. /**
  787. * Get status of streaming for received data
  788. * @return boolean|string
  789. */
  790. public function getStream()
  791. {
  792. return $this->config["output_stream"];
  793. }
  794. /**
  795. * Create temporary stream
  796. *
  797. * @return resource
  798. */
  799. protected function _openTempStream()
  800. {
  801. $this->_stream_name = $this->config['output_stream'];
  802. if(!is_string($this->_stream_name)) {
  803. // If name is not given, create temp name
  804. $this->_stream_name = tempnam(isset($this->config['stream_tmp_dir'])?$this->config['stream_tmp_dir']:sys_get_temp_dir(),
  805. 'Zend_Http_Client');
  806. }
  807. if (false === ($fp = @fopen($this->_stream_name, "w+b"))) {
  808. if ($this->adapter instanceof Zend_Http_Client_Adapter_Interface) {
  809. $this->adapter->close();
  810. }
  811. #require_once 'Zend/Http/Client/Exception.php';
  812. throw new Zend_Http_Client_Exception("Could not open temp file {$this->_stream_name}");
  813. }
  814. return $fp;
  815. }
  816. /**
  817. * Send the HTTP request and return an HTTP response object
  818. *
  819. * @param string $method
  820. * @return Zend_Http_Response
  821. * @throws Zend_Http_Client_Exception
  822. */
  823. public function request($method = null)
  824. {
  825. if (! $this->uri instanceof Zend_Uri_Http) {
  826. /** @see Zend_Http_Client_Exception */
  827. #require_once 'Zend/Http/Client/Exception.php';
  828. throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
  829. }
  830. if ($method) {
  831. $this->setMethod($method);
  832. }
  833. $this->redirectCounter = 0;
  834. $response = null;
  835. // Make sure the adapter is loaded
  836. if ($this->adapter == null) {
  837. $this->setAdapter($this->config['adapter']);
  838. }
  839. // Send the first request. If redirected, continue.
  840. do {
  841. // Clone the URI and add the additional GET parameters to it
  842. $uri = clone $this->uri;
  843. if (! empty($this->paramsGet)) {
  844. $query = $uri->getQuery();
  845. if (! empty($query)) {
  846. $query .= '&';
  847. }
  848. $query .= http_build_query($this->paramsGet, null, '&');
  849. if ($this->config['rfc3986_strict']) {
  850. $query = str_replace('+', '%20', $query);
  851. }
  852. $uri->setQuery($query);
  853. }
  854. $body = $this->_prepareBody();
  855. $headers = $this->_prepareHeaders();
  856. // check that adapter supports streaming before using it
  857. if(is_resource($body) && !($this->adapter instanceof Zend_Http_Client_Adapter_Stream)) {
  858. /** @see Zend_Http_Client_Exception */
  859. #require_once 'Zend/Http/Client/Exception.php';
  860. throw new Zend_Http_Client_Exception('Adapter does not support streaming');
  861. }
  862. // Open the connection, send the request and read the response
  863. $this->adapter->connect($uri->getHost(), $uri->getPort(),
  864. ($uri->getScheme() == 'https' ? true : false));
  865. if($this->config['output_stream']) {
  866. if($this->adapter instanceof Zend_Http_Client_Adapter_Stream) {
  867. $stream = $this->_openTempStream();
  868. $this->adapter->setOutputStream($stream);
  869. } else {
  870. /** @see Zend_Http_Client_Exception */
  871. #require_once 'Zend/Http/Client/Exception.php';
  872. throw new Zend_Http_Client_Exception('Adapter does not support streaming');
  873. }
  874. }
  875. $this->last_request = $this->adapter->write($this->method,
  876. $uri, $this->config['httpversion'], $headers, $body);
  877. $response = $this->adapter->read();
  878. if (! $response) {
  879. /** @see Zend_Http_Client_Exception */
  880. #require_once 'Zend/Http/Client/Exception.php';
  881. throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
  882. }
  883. if($this->config['output_stream']) {
  884. rewind($stream);
  885. // cleanup the adapter
  886. $this->adapter->setOutputStream(null);
  887. $response = Zend_Http_Response_Stream::fromStream($response, $stream);
  888. $response->setStreamName($this->_stream_name);
  889. if(!is_string($this->config['output_stream'])) {
  890. // we used temp name, will need to clean up
  891. $response->setCleanup(true);
  892. }
  893. } else {
  894. $response = Zend_Http_Response::fromString($response);
  895. }
  896. if ($this->config['storeresponse']) {
  897. $this->last_response = $response;
  898. }
  899. // Load cookies into cookie jar
  900. if (isset($this->cookiejar)) {
  901. $this->cookiejar->addCookiesFromResponse($response, $uri, $this->config['encodecookies']);
  902. }
  903. // If we got redirected, look for the Location header
  904. if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
  905. // Check whether we send the exact same request again, or drop the parameters
  906. // and send a GET request
  907. if ($response->getStatus() == 303 ||
  908. ((! $this->config['strictredirects']) && ($response->getStatus() == 302 ||
  909. $response->getStatus() == 301))) {
  910. $this->resetParameters();
  911. $this->setMethod(self::GET);
  912. }
  913. // If we got a well formed absolute URI
  914. if (Zend_Uri_Http::check($location)) {
  915. $this->setHeaders('host', null);
  916. $this->setUri($location);
  917. } else {
  918. // Split into path and query and set the query
  919. if (strpos($location, '?') !== false) {
  920. list($location, $query) = explode('?', $location, 2);
  921. } else {
  922. $query = '';
  923. }
  924. $this->uri->setQuery($query);
  925. // Else, if we got just an absolute path, set it
  926. if(strpos($location, '/') === 0) {
  927. $this->uri->setPath($location);
  928. // Else, assume we have a relative path
  929. } else {
  930. // Get the current path directory, removing any trailing slashes
  931. $path = $this->uri->getPath();
  932. $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
  933. $this->uri->setPath($path . '/' . $location);
  934. }
  935. }
  936. ++$this->redirectCounter;
  937. } else {
  938. // If we didn't get any location, stop redirecting
  939. break;
  940. }
  941. } while ($this->redirectCounter < $this->config['maxredirects']);
  942. return $response;
  943. }
  944. /**
  945. * Prepare the request headers
  946. *
  947. * @return array
  948. */
  949. protected function _prepareHeaders()
  950. {
  951. $headers = array();
  952. // Set the host header
  953. if (! isset($this->headers['host'])) {
  954. $host = $this->uri->getHost();
  955. // If the port is not default, add it
  956. if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) ||
  957. ($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) {
  958. $host .= ':' . $this->uri->getPort();
  959. }
  960. $headers[] = "Host: {$host}";
  961. }
  962. // Set the connection header
  963. if (! isset($this->headers['connection'])) {
  964. if (! $this->config['keepalive']) {
  965. $headers[] = "Connection: close";
  966. }
  967. }
  968. // Set the Accept-encoding header if not set - depending on whether
  969. // zlib is available or not.
  970. if (! isset($this->headers['accept-encoding'])) {
  971. if (function_exists('gzinflate')) {
  972. $headers[] = 'Accept-encoding: gzip, deflate';
  973. } else {
  974. $headers[] = 'Accept-encoding: identity';
  975. }
  976. }
  977. // Set the Content-Type header
  978. if (($this->method == self::POST || $this->method == self::PUT) &&
  979. (! isset($this->headers[strtolower(self::CONTENT_TYPE)]) && isset($this->enctype))) {
  980. $headers[] = self::CONTENT_TYPE . ': ' . $this->enctype;
  981. }
  982. // Set the user agent header
  983. if (! isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
  984. $headers[] = "User-Agent: {$this->config['useragent']}";
  985. }
  986. // Set HTTP authentication if needed
  987. if (is_array($this->auth)) {
  988. $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
  989. $headers[] = "Authorization: {$auth}";
  990. }
  991. // Load cookies from cookie jar
  992. if (isset($this->cookiejar)) {
  993. $cookstr = $this->cookiejar->getMatchingCookies($this->uri,
  994. true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
  995. if ($cookstr) {
  996. $headers[] = "Cookie: {$cookstr}";
  997. }
  998. }
  999. // Add all other user defined headers
  1000. foreach ($this->headers as $header) {
  1001. list($name, $value) = $header;
  1002. if (is_array($value)) {
  1003. $value = implode(', ', $value);
  1004. }
  1005. $headers[] = "$name: $value";
  1006. }
  1007. return $headers;
  1008. }
  1009. /**
  1010. * Prepare the request body (for POST and PUT requests)
  1011. *
  1012. * @return string
  1013. * @throws Zend_Http_Client_Exception
  1014. */
  1015. protected function _prepareBody()
  1016. {
  1017. // According to RFC2616, a TRACE request should not have a body.
  1018. if ($this->method == self::TRACE) {
  1019. return '';
  1020. }
  1021. if (isset($this->raw_post_data) && is_resource($this->raw_post_data)) {
  1022. return $this->raw_post_data;
  1023. }
  1024. // If mbstring overloads substr and strlen functions, we have to
  1025. // override it's internal encoding
  1026. if (function_exists('mb_internal_encoding') &&
  1027. ((int) ini_get('mbstring.func_overload')) & 2) {
  1028. $mbIntEnc = mb_internal_encoding();
  1029. mb_internal_encoding('ASCII');
  1030. }
  1031. // If we have raw_post_data set, just use it as the body.
  1032. if (isset($this->raw_post_data)) {
  1033. $this->setHeaders(self::CONTENT_LENGTH, strlen($this->raw_post_data));
  1034. if (isset($mbIntEnc)) {
  1035. mb_internal_encoding($mbIntEnc);
  1036. }
  1037. return $this->raw_post_data;
  1038. }
  1039. $body = '';
  1040. // If we have files to upload, force enctype to multipart/form-data
  1041. if (count ($this->files) > 0) {
  1042. $this->setEncType(self::ENC_FORMDATA);
  1043. }
  1044. // If we have POST parameters or files, encode and add them to the body
  1045. if (count($this->paramsPost) > 0 || count($this->files) > 0) {
  1046. switch($this->enctype) {
  1047. case self::ENC_FORMDATA:
  1048. // Encode body as multipart/form-data
  1049. $boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
  1050. $this->setHeaders(self::CONTENT_TYPE, self::ENC_FORMDATA . "; boundary={$boundary}");
  1051. // Get POST parameters and encode them
  1052. $params = self::_flattenParametersArray($this->paramsPost);
  1053. foreach ($params as $pp) {
  1054. $body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
  1055. }
  1056. // Encode files
  1057. foreach ($this->files as $file) {
  1058. $fhead = array(self::CONTENT_TYPE => $file['ctype']);
  1059. $body .= self::encodeFormData($boundary, $file['formname'], $file['data'], $file['filename'], $fhead);
  1060. }
  1061. $body .= "--{$boundary}--\r\n";
  1062. break;
  1063. case self::ENC_URLENCODED:
  1064. // Encode body as application/x-www-form-urlencoded
  1065. $this->setHeaders(self::CONTENT_TYPE, self::ENC_URLENCODED);
  1066. $body = http_build_query($this->paramsPost, '', '&');
  1067. break;
  1068. default:
  1069. if (isset($mbIntEnc)) {
  1070. mb_internal_encoding($mbIntEnc);
  1071. }
  1072. /** @see Zend_Http_Client_Exception */
  1073. #require_once 'Zend/Http/Client/Exception.php';
  1074. throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." .
  1075. " Please use Zend_Http_Client::setRawData to send this kind of content.");
  1076. break;
  1077. }
  1078. }
  1079. // Set the Content-Length if we have a body or if request is POST/PUT
  1080. if ($body || $this->method == self::POST || $this->method == self::PUT) {
  1081. $this->setHeaders(self::CONTENT_LENGTH, strlen($body));
  1082. }
  1083. if (isset($mbIntEnc)) {
  1084. mb_internal_encoding($mbIntEnc);
  1085. }
  1086. return $body;
  1087. }
  1088. /**
  1089. * Helper method that gets a possibly multi-level parameters array (get or
  1090. * post) and flattens it.
  1091. *
  1092. * The method returns an array of (key, value) pairs (because keys are not
  1093. * necessarily unique. If one of the parameters in as array, it will also
  1094. * add a [] suffix to the key.
  1095. *
  1096. * This method is deprecated since Zend Framework 1.9 in favour of
  1097. * self::_flattenParametersArray() and will be dropped in 2.0
  1098. *
  1099. * @deprecated since 1.9
  1100. *
  1101. * @param array $parray The parameters array
  1102. * @param bool $urlencode Whether to urlencode the name and value
  1103. * @return array
  1104. */
  1105. protected function _getParametersRecursive($parray, $urlencode = false)
  1106. {
  1107. // Issue a deprecated notice
  1108. trigger_error("The " . __METHOD__ . " method is deprecated and will be dropped in 2.0.",
  1109. E_USER_NOTICE);
  1110. if (! is_array($parray)) {
  1111. return $parray;
  1112. }
  1113. $parameters = array();
  1114. foreach ($parray as $name => $value) {
  1115. if ($urlencode) {
  1116. $name = urlencode($name);
  1117. }
  1118. // If $value is an array, iterate over it
  1119. if (is_array($value)) {
  1120. $name .= ($urlencode ? '%5B%5D' : '[]');
  1121. foreach ($value as $subval) {
  1122. if ($urlencode) {
  1123. $subval = urlencode($subval);
  1124. }
  1125. $parameters[] = array($name, $subval);
  1126. }
  1127. } else {
  1128. if ($urlencode) {
  1129. $value = urlencode($value);
  1130. }
  1131. $parameters[] = array($name, $value);
  1132. }
  1133. }
  1134. return $parameters;
  1135. }
  1136. /**
  1137. * Attempt to detect the MIME type of a file using available extensions
  1138. *
  1139. * This method will try to detect the MIME type of a file. If the fileinfo
  1140. * extension is available, it will be used. If not, the mime_magic
  1141. * extension which is deprected but is still available in many PHP setups
  1142. * will be tried.
  1143. *
  1144. * If neither extension is available, the default application/octet-stream
  1145. * MIME type will be returned
  1146. *
  1147. * @param string $file File path
  1148. * @return string MIME type
  1149. */
  1150. protected function _detectFileMimeType($file)
  1151. {
  1152. $type = null;
  1153. // First try with fileinfo functions
  1154. if (function_exists('finfo_open')) {
  1155. if (self::$_fileInfoDb === null) {
  1156. self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
  1157. }
  1158. if (self::$_fileInfoDb) {
  1159. $type = finfo_file(self::$_fileInfoDb, $file);
  1160. }
  1161. } elseif (function_exists('mime_content_type')) {
  1162. $type = mime_content_type($file);
  1163. }
  1164. // Fallback to the default application/octet-stream
  1165. if (! $type) {
  1166. $type = 'application/octet-stream';
  1167. }
  1168. return $type;
  1169. }
  1170. /**
  1171. * Encode data to a multipart/form-data part suitable for a POST request.
  1172. *
  1173. * @param string $boundary
  1174. * @param string $name
  1175. * @param mixed $value
  1176. * @param string $filename
  1177. * @param array $headers Associative array of optional headers @example ("Content-Transfer-Encoding" => "binary")
  1178. * @return string
  1179. */
  1180. public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
  1181. $ret = "--{$boundary}\r\n" .
  1182. 'Content-Disposition: form-data; name="' . $name .'"';
  1183. if ($filename) {
  1184. $ret .= '; filename="' . $filename . '"';
  1185. }
  1186. $ret .= "\r\n";
  1187. foreach ($headers as $hname => $hvalue) {
  1188. $ret .= "{$hname}: {$hvalue}\r\n";
  1189. }
  1190. $ret .= "\r\n";
  1191. $ret .= "{$value}\r\n";
  1192. return $ret;
  1193. }
  1194. /**
  1195. * Create a HTTP authentication "Authorization:" header according to the
  1196. * specified user, password and authentication method.
  1197. *
  1198. * @see http://www.faqs.org/rfcs/rfc2617.html
  1199. * @param string $user
  1200. * @param string $password
  1201. * @param string $type
  1202. * @return string
  1203. * @throws Zend_Http_Client_Exception
  1204. */
  1205. public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
  1206. {
  1207. $authHeader = null;
  1208. switch ($type) {
  1209. case self::AUTH_BASIC:
  1210. // In basic authentication, the user name cannot contain ":"
  1211. if (strpos($user, ':') !== false) {
  1212. /** @see Zend_Http_Client_Exception */
  1213. #require_once 'Zend/Http/Client/Exception.php';
  1214. throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
  1215. }
  1216. $authHeader = 'Basic ' . base64_encode($user . ':' . $password);
  1217. break;
  1218. //case self::AUTH_DIGEST:
  1219. /**
  1220. * @todo Implement digest authentication
  1221. */
  1222. // break;
  1223. default:
  1224. /** @see Zend_Http_Client_Exception */
  1225. #require_once 'Zend/Http/Client/Exception.php';
  1226. throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");
  1227. }
  1228. return $authHeader;
  1229. }
  1230. /**
  1231. * Convert an array of parameters into a flat array of (key, value) pairs
  1232. *
  1233. * Will flatten a potentially multi-dimentional array of parameters (such
  1234. * as POST parameters) into a flat array of (key, value) paris. In case
  1235. * of multi-dimentional arrays, square brackets ([]) will be added to the
  1236. * key to indicate an array.
  1237. *
  1238. * @since 1.9
  1239. *
  1240. * @param array $parray
  1241. * @param string $prefix
  1242. * @return array
  1243. */
  1244. static protected function _flattenParametersArray($parray, $prefix = null)
  1245. {
  1246. if (! is_array($parray)) {
  1247. return $parray;
  1248. }
  1249. $parameters = array();
  1250. foreach($parray as $name => $value) {
  1251. // Calculate array key
  1252. if ($prefix) {
  1253. if (is_int($name)) {
  1254. $key = $prefix . '[]';
  1255. } else {
  1256. $key = $prefix . "[$name]";
  1257. }
  1258. } else {
  1259. $key = $name;
  1260. }
  1261. if (is_array($value)) {
  1262. $parameters = array_merge($parameters, self::_flattenParametersArray($value, $key));
  1263. } else {
  1264. $parameters[] = array($key, $value);
  1265. }
  1266. }
  1267. return $parameters;
  1268. }
  1269. }