PageRenderTime 75ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/Http/Client.php

https://bitbucket.org/baruffaldi/cms-php-bfcms
PHP | 1186 lines | 529 code | 161 blank | 496 comment | 134 complexity | 29db64d10d0164b162951b0dbcd5fb31 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 9906 2008-07-02 21:20:10Z shahar $
  19. * @copyright Copyright (c) 2005-2008 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. * Zend_Http_Client is an implemetation of an HTTP client in PHP. The client
  40. * supports basic features like sending different HTTP requests and handling
  41. * redirections, as well as more advanced features like proxy settings, HTTP
  42. * authentication and cookie persistance (using a Zend_Http_CookieJar object)
  43. *
  44. * @todo Implement proxy settings
  45. * @category Zend
  46. * @package Zend_Http
  47. * @subpackage Client
  48. * @throws Zend_Http_Client_Exception
  49. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  50. * @license http://framework.zend.com/license/new-bsd New BSD License
  51. */
  52. class Zend_Http_Client
  53. {
  54. /**
  55. * HTTP request methods
  56. */
  57. const GET = 'GET';
  58. const POST = 'POST';
  59. const PUT = 'PUT';
  60. const HEAD = 'HEAD';
  61. const DELETE = 'DELETE';
  62. const TRACE = 'TRACE';
  63. const OPTIONS = 'OPTIONS';
  64. const CONNECT = 'CONNECT';
  65. /**
  66. * Supported HTTP Authentication methods
  67. */
  68. const AUTH_BASIC = 'basic';
  69. //const AUTH_DIGEST = 'digest'; <-- not implemented yet
  70. /**
  71. * HTTP protocol versions
  72. */
  73. const HTTP_1 = '1.1';
  74. const HTTP_0 = '1.0';
  75. /**
  76. * POST data encoding methods
  77. */
  78. const ENC_URLENCODED = 'application/x-www-form-urlencoded';
  79. const ENC_FORMDATA = 'multipart/form-data';
  80. /**
  81. * Configuration array, set using the constructor or using ::setConfig()
  82. *
  83. * @var array
  84. */
  85. protected $config = array(
  86. 'maxredirects' => 5,
  87. 'strictredirects' => false,
  88. 'useragent' => 'Zend_Http_Client',
  89. 'timeout' => 10,
  90. 'adapter' => 'Zend_Http_Client_Adapter_Socket',
  91. 'httpversion' => self::HTTP_1,
  92. 'keepalive' => false,
  93. 'storeresponse' => true,
  94. 'strict' => true
  95. );
  96. /**
  97. * The adapter used to preform the actual connection to the server
  98. *
  99. * @var Zend_Http_Client_Adapter_Interface
  100. */
  101. protected $adapter = null;
  102. /**
  103. * Request URI
  104. *
  105. * @var Zend_Uri_Http
  106. */
  107. protected $uri;
  108. /**
  109. * Associative array of request headers
  110. *
  111. * @var array
  112. */
  113. protected $headers = array();
  114. /**
  115. * HTTP request method
  116. *
  117. * @var string
  118. */
  119. protected $method = self::GET;
  120. /**
  121. * Associative array of GET parameters
  122. *
  123. * @var array
  124. */
  125. protected $paramsGet = array();
  126. /**
  127. * Assiciative array of POST parameters
  128. *
  129. * @var array
  130. */
  131. protected $paramsPost = array();
  132. /**
  133. * Request body content type (for POST requests)
  134. *
  135. * @var string
  136. */
  137. protected $enctype = null;
  138. /**
  139. * The raw post data to send. Could be set by setRawData($data, $enctype).
  140. *
  141. * @var string
  142. */
  143. protected $raw_post_data = null;
  144. /**
  145. * HTTP Authentication settings
  146. *
  147. * Expected to be an associative array with this structure:
  148. * $this->auth = array('user' => 'username', 'password' => 'password', 'type' => 'basic')
  149. * Where 'type' should be one of the supported authentication types (see the AUTH_*
  150. * constants), for example 'basic' or 'digest'.
  151. *
  152. * If null, no authentication will be used.
  153. *
  154. * @var array|null
  155. */
  156. protected $auth;
  157. /**
  158. * File upload arrays (used in POST requests)
  159. *
  160. * An associative array, where each element is of the format:
  161. * 'name' => array('filename.txt', 'text/plain', 'This is the actual file contents')
  162. *
  163. * @var array
  164. */
  165. protected $files = array();
  166. /**
  167. * The client's cookie jar
  168. *
  169. * @var Zend_Http_CookieJar
  170. */
  171. protected $cookiejar = null;
  172. /**
  173. * The last HTTP request sent by the client, as string
  174. *
  175. * @var string
  176. */
  177. protected $last_request = null;
  178. /**
  179. * The last HTTP response received by the client
  180. *
  181. * @var Zend_Http_Response
  182. */
  183. protected $last_response = null;
  184. /**
  185. * Redirection counter
  186. *
  187. * @var int
  188. */
  189. protected $redirectCounter = 0;
  190. /**
  191. * Fileinfo magic database resource
  192. *
  193. * This varaiable is populated the first time _detectFileMimeType is called
  194. * and is then reused on every call to this method
  195. *
  196. * @var resource
  197. */
  198. static protected $_fileInfoDb = null;
  199. /**
  200. * Contructor method. Will create a new HTTP client. Accepts the target
  201. * URL and optionally configuration array.
  202. *
  203. * @param Zend_Uri_Http|string $uri
  204. * @param array $config Configuration key-value pairs.
  205. */
  206. public function __construct($uri = null, $config = null)
  207. {
  208. if ($uri !== null) $this->setUri($uri);
  209. if ($config !== null) $this->setConfig($config);
  210. }
  211. /**
  212. * Set the URI for the next request
  213. *
  214. * @param Zend_Uri_Http|string $uri
  215. * @return Zend_Http_Client
  216. * @throws Zend_Http_Client_Exception
  217. */
  218. public function setUri($uri)
  219. {
  220. if (is_string($uri)) {
  221. $uri = Zend_Uri::factory($uri);
  222. }
  223. if (!$uri instanceof Zend_Uri_Http) {
  224. /** @see Zend_Http_Client_Exception */
  225. require_once 'Zend/Http/Client/Exception.php';
  226. throw new Zend_Http_Client_Exception('Passed parameter is not a valid HTTP URI.');
  227. }
  228. // We have no ports, set the defaults
  229. if (! $uri->getPort()) {
  230. $uri->setPort(($uri->getScheme() == 'https' ? 443 : 80));
  231. }
  232. $this->uri = $uri;
  233. return $this;
  234. }
  235. /**
  236. * Get the URI for the next request
  237. *
  238. * @param boolean $as_string If true, will return the URI as a string
  239. * @return Zend_Uri_Http|string
  240. */
  241. public function getUri($as_string = false)
  242. {
  243. if ($as_string && $this->uri instanceof Zend_Uri_Http) {
  244. return $this->uri->__toString();
  245. } else {
  246. return $this->uri;
  247. }
  248. }
  249. /**
  250. * Set configuration parameters for this HTTP client
  251. *
  252. * @param array $config
  253. * @return Zend_Http_Client
  254. * @throws Zend_Http_Client_Exception
  255. */
  256. public function setConfig($config = array())
  257. {
  258. if (! is_array($config)) {
  259. /** @see Zend_Http_Client_Exception */
  260. require_once 'Zend/Http/Client/Exception.php';
  261. throw new Zend_Http_Client_Exception('Expected array parameter, given ' . gettype($config));
  262. }
  263. foreach ($config as $k => $v)
  264. $this->config[strtolower($k)] = $v;
  265. return $this;
  266. }
  267. /**
  268. * Set the next request's method
  269. *
  270. * Validated the passed method and sets it. If we have files set for
  271. * POST requests, and the new method is not POST, the files are silently
  272. * dropped.
  273. *
  274. * @param string $method
  275. * @return Zend_Http_Client
  276. * @throws Zend_Http_Client_Exception
  277. */
  278. public function setMethod($method = self::GET)
  279. {
  280. $regex = '/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/';
  281. if (! preg_match($regex, $method)) {
  282. /** @see Zend_Http_Client_Exception */
  283. require_once 'Zend/Http/Client/Exception.php';
  284. throw new Zend_Http_Client_Exception("'{$method}' is not a valid HTTP request method.");
  285. }
  286. if ($method == self::POST && $this->enctype === null)
  287. $this->setEncType(self::ENC_URLENCODED);
  288. $this->method = $method;
  289. return $this;
  290. }
  291. /**
  292. * Set one or more request headers
  293. *
  294. * This function can be used in several ways to set the client's request
  295. * headers:
  296. * 1. By providing two parameters: $name as the header to set (eg. 'Host')
  297. * and $value as it's value (eg. 'www.example.com').
  298. * 2. By providing a single header string as the only parameter
  299. * eg. 'Host: www.example.com'
  300. * 3. By providing an array of headers as the first parameter
  301. * eg. array('host' => 'www.example.com', 'x-foo: bar'). In This case
  302. * the function will call itself recursively for each array item.
  303. *
  304. * @param string|array $name Header name, full header string ('Header: value')
  305. * or an array of headers
  306. * @param mixed $value Header value or null
  307. * @return Zend_Http_Client
  308. * @throws Zend_Http_Client_Exception
  309. */
  310. public function setHeaders($name, $value = null)
  311. {
  312. // If we got an array, go recusive!
  313. if (is_array($name)) {
  314. foreach ($name as $k => $v) {
  315. if (is_string($k)) {
  316. $this->setHeaders($k, $v);
  317. } else {
  318. $this->setHeaders($v, null);
  319. }
  320. }
  321. } else {
  322. // Check if $name needs to be split
  323. if ($value === null && (strpos($name, ':') > 0))
  324. list($name, $value) = explode(':', $name, 2);
  325. // Make sure the name is valid if we are in strict mode
  326. if ($this->config['strict'] && (! preg_match('/^[a-zA-Z0-9-]+$/', $name))) {
  327. /** @see Zend_Http_Client_Exception */
  328. require_once 'Zend/Http/Client/Exception.php';
  329. throw new Zend_Http_Client_Exception("{$name} is not a valid HTTP header name");
  330. }
  331. $normalized_name = strtolower($name);
  332. // If $value is null or false, unset the header
  333. if ($value === null || $value === false) {
  334. unset($this->headers[$normalized_name]);
  335. // Else, set the header
  336. } else {
  337. // Header names are storred lowercase internally.
  338. if (is_string($value)) $value = trim($value);
  339. $this->headers[$normalized_name] = array($name, $value);
  340. }
  341. }
  342. return $this;
  343. }
  344. /**
  345. * Get the value of a specific header
  346. *
  347. * Note that if the header has more than one value, an array
  348. * will be returned.
  349. *
  350. * @param string $key
  351. * @return string|array|null The header value or null if it is not set
  352. */
  353. public function getHeader($key)
  354. {
  355. $key = strtolower($key);
  356. if (isset($this->headers[$key])) {
  357. return $this->headers[$key][1];
  358. } else {
  359. return null;
  360. }
  361. }
  362. /**
  363. * Set a GET parameter for the request. Wrapper around _setParameter
  364. *
  365. * @param string|array $name
  366. * @param string $value
  367. * @return Zend_Http_Client
  368. */
  369. public function setParameterGet($name, $value = null)
  370. {
  371. if (is_array($name)) {
  372. foreach ($name as $k => $v)
  373. $this->_setParameter('GET', $k, $v);
  374. } else {
  375. $this->_setParameter('GET', $name, $value);
  376. }
  377. return $this;
  378. }
  379. /**
  380. * Set a POST parameter for the request. Wrapper around _setParameter
  381. *
  382. * @param string|array $name
  383. * @param string $value
  384. * @return Zend_Http_Client
  385. */
  386. public function setParameterPost($name, $value = null)
  387. {
  388. if (is_array($name)) {
  389. foreach ($name as $k => $v)
  390. $this->_setParameter('POST', $k, $v);
  391. } else {
  392. $this->_setParameter('POST', $name, $value);
  393. }
  394. return $this;
  395. }
  396. /**
  397. * Set a GET or POST parameter - used by SetParameterGet and SetParameterPost
  398. *
  399. * @param string $type GET or POST
  400. * @param string $name
  401. * @param string $value
  402. * @return null
  403. */
  404. protected function _setParameter($type, $name, $value)
  405. {
  406. $parray = array();
  407. $type = strtolower($type);
  408. switch ($type) {
  409. case 'get':
  410. $parray = &$this->paramsGet;
  411. break;
  412. case 'post':
  413. $parray = &$this->paramsPost;
  414. break;
  415. }
  416. if ($value === null) {
  417. if (isset($parray[$name])) unset($parray[$name]);
  418. } else {
  419. $parray[$name] = $value;
  420. }
  421. }
  422. /**
  423. * Get the number of redirections done on the last request
  424. *
  425. * @return int
  426. */
  427. public function getRedirectionsCount()
  428. {
  429. return $this->redirectCounter;
  430. }
  431. /**
  432. * Set HTTP authentication parameters
  433. *
  434. * $type should be one of the supported types - see the self::AUTH_*
  435. * constants.
  436. *
  437. * To enable authentication:
  438. * <code>
  439. * $this->setAuth('shahar', 'secret', Zend_Http_Client::AUTH_BASIC);
  440. * </code>
  441. *
  442. * To disable authentication:
  443. * <code>
  444. * $this->setAuth(false);
  445. * </code>
  446. *
  447. * @see http://www.faqs.org/rfcs/rfc2617.html
  448. * @param string|false $user User name or false disable authentication
  449. * @param string $password Password
  450. * @param string $type Authentication type
  451. * @return Zend_Http_Client
  452. * @throws Zend_Http_Client_Exception
  453. */
  454. public function setAuth($user, $password = '', $type = self::AUTH_BASIC)
  455. {
  456. // If we got false or null, disable authentication
  457. if ($user === false || $user === null) {
  458. $this->auth = null;
  459. // Else, set up authentication
  460. } else {
  461. // Check we got a proper authentication type
  462. if (! defined('self::AUTH_' . strtoupper($type))) {
  463. /** @see Zend_Http_Client_Exception */
  464. require_once 'Zend/Http/Client/Exception.php';
  465. throw new Zend_Http_Client_Exception("Invalid or not supported authentication type: '$type'");
  466. }
  467. $this->auth = array(
  468. 'user' => (string) $user,
  469. 'password' => (string) $password,
  470. 'type' => $type
  471. );
  472. }
  473. return $this;
  474. }
  475. /**
  476. * Set the HTTP client's cookie jar.
  477. *
  478. * A cookie jar is an object that holds and maintains cookies across HTTP requests
  479. * and responses.
  480. *
  481. * @param Zend_Http_CookieJar|boolean $cookiejar Existing cookiejar object, true to create a new one, false to disable
  482. * @return Zend_Http_Client
  483. * @throws Zend_Http_Client_Exception
  484. */
  485. public function setCookieJar($cookiejar = true)
  486. {
  487. if (! class_exists('Zend_Http_CookieJar'))
  488. require_once 'Zend/Http/CookieJar.php';
  489. if ($cookiejar instanceof Zend_Http_CookieJar) {
  490. $this->cookiejar = $cookiejar;
  491. } elseif ($cookiejar === true) {
  492. $this->cookiejar = new Zend_Http_CookieJar();
  493. } elseif (! $cookiejar) {
  494. $this->cookiejar = null;
  495. } else {
  496. /** @see Zend_Http_Client_Exception */
  497. require_once 'Zend/Http/Client/Exception.php';
  498. throw new Zend_Http_Client_Exception('Invalid parameter type passed as CookieJar');
  499. }
  500. return $this;
  501. }
  502. /**
  503. * Return the current cookie jar or null if none.
  504. *
  505. * @return Zend_Http_CookieJar|null
  506. */
  507. public function getCookieJar()
  508. {
  509. return $this->cookiejar;
  510. }
  511. /**
  512. * Add a cookie to the request. If the client has no Cookie Jar, the cookies
  513. * will be added directly to the headers array as "Cookie" headers.
  514. *
  515. * @param Zend_Http_Cookie|string $cookie
  516. * @param string|null $value If "cookie" is a string, this is the cookie value.
  517. * @return Zend_Http_Client
  518. * @throws Zend_Http_Client_Exception
  519. */
  520. public function setCookie($cookie, $value = null)
  521. {
  522. if (! class_exists('Zend_Http_Cookie'))
  523. require_once 'Zend/Http/Cookie.php';
  524. if (is_array($cookie)) {
  525. foreach ($cookie as $c => $v) {
  526. if (is_string($c)) {
  527. $this->setCookie($c, $v);
  528. } else {
  529. $this->setCookie($v);
  530. }
  531. }
  532. return $this;
  533. }
  534. if ($value !== null) $value = urlencode($value);
  535. if (isset($this->cookiejar)) {
  536. if ($cookie instanceof Zend_Http_Cookie) {
  537. $this->cookiejar->addCookie($cookie);
  538. } elseif (is_string($cookie) && $value !== null) {
  539. $cookie = Zend_Http_Cookie::fromString("{$cookie}={$value}", $this->uri);
  540. $this->cookiejar->addCookie($cookie);
  541. }
  542. } else {
  543. if ($cookie instanceof Zend_Http_Cookie) {
  544. $name = $cookie->getName();
  545. $value = $cookie->getValue();
  546. $cookie = $name;
  547. }
  548. if (preg_match("/[=,; \t\r\n\013\014]/", $cookie)) {
  549. /** @see Zend_Http_Client_Exception */
  550. require_once 'Zend/Http/Client/Exception.php';
  551. throw new Zend_Http_Client_Exception("Cookie name cannot contain these characters: =,; \t\r\n\013\014 ({$cookie})");
  552. }
  553. $value = addslashes($value);
  554. if (! isset($this->headers['cookie'])) $this->headers['cookie'] = array('Cookie', '');
  555. $this->headers['cookie'][1] .= $cookie . '=' . $value . '; ';
  556. }
  557. return $this;
  558. }
  559. /**
  560. * Set a file to upload (using a POST request)
  561. *
  562. * Can be used in two ways:
  563. *
  564. * 1. $data is null (default): $filename is treated as the name if a local file which
  565. * will be read and sent. Will try to guess the content type using mime_content_type().
  566. * 2. $data is set - $filename is sent as the file name, but $data is sent as the file
  567. * contents and no file is read from the file system. In this case, you need to
  568. * manually set the content-type ($ctype) or it will default to
  569. * application/octet-stream.
  570. *
  571. * @param string $filename Name of file to upload, or name to save as
  572. * @param string $formname Name of form element to send as
  573. * @param string $data Data to send (if null, $filename is read and sent)
  574. * @param string $ctype Content type to use (if $data is set and $ctype is
  575. * null, will be application/octet-stream)
  576. * @return Zend_Http_Client
  577. * @throws Zend_Http_Client_Exception
  578. */
  579. public function setFileUpload($filename, $formname, $data = null, $ctype = null)
  580. {
  581. if ($data === null) {
  582. if (($data = @file_get_contents($filename)) === false) {
  583. /** @see Zend_Http_Client_Exception */
  584. require_once 'Zend/Http/Client/Exception.php';
  585. throw new Zend_Http_Client_Exception("Unable to read file '{$filename}' for upload");
  586. }
  587. if (! $ctype) $ctype = $this->_detectFileMimeType($filename);
  588. }
  589. // Force enctype to multipart/form-data
  590. $this->setEncType(self::ENC_FORMDATA);
  591. $this->files[$formname] = array(basename($filename), $ctype, $data);
  592. return $this;
  593. }
  594. /**
  595. * Set the encoding type for POST data
  596. *
  597. * @param string $enctype
  598. * @return Zend_Http_Client
  599. */
  600. public function setEncType($enctype = self::ENC_URLENCODED)
  601. {
  602. $this->enctype = $enctype;
  603. return $this;
  604. }
  605. /**
  606. * Set the raw (already encoded) POST data.
  607. *
  608. * This function is here for two reasons:
  609. * 1. For advanced user who would like to set their own data, already encoded
  610. * 2. For backwards compatibilty: If someone uses the old post($data) method.
  611. * this method will be used to set the encoded data.
  612. *
  613. * @param string $data
  614. * @param string $enctype
  615. * @return Zend_Http_Client
  616. */
  617. public function setRawData($data, $enctype = null)
  618. {
  619. $this->raw_post_data = $data;
  620. $this->setEncType($enctype);
  621. return $this;
  622. }
  623. /**
  624. * Clear all GET and POST parameters
  625. *
  626. * Should be used to reset the request parameters if the client is
  627. * used for several concurrent requests.
  628. *
  629. * @return Zend_Http_Client
  630. */
  631. public function resetParameters()
  632. {
  633. // Reset parameter data
  634. $this->paramsGet = array();
  635. $this->paramsPost = array();
  636. $this->files = array();
  637. $this->raw_post_data = null;
  638. // Clear outdated headers
  639. if (isset($this->headers['content-type'])) unset($this->headers['content-type']);
  640. if (isset($this->headers['content-length'])) unset($this->headers['content-length']);
  641. return $this;
  642. }
  643. /**
  644. * Get the last HTTP request as string
  645. *
  646. * @return string
  647. */
  648. public function getLastRequest()
  649. {
  650. return $this->last_request;
  651. }
  652. /**
  653. * Get the last HTTP response received by this client
  654. *
  655. * If $config['storeresponse'] is set to false, or no response was
  656. * stored yet, will return null
  657. *
  658. * @return Zend_Http_Response or null if none
  659. */
  660. public function getLastResponse()
  661. {
  662. return $this->last_response;
  663. }
  664. /**
  665. * Load the connection adapter
  666. *
  667. * While this method is not called more than one for a client, it is
  668. * seperated from ->request() to preserve logic and readability
  669. *
  670. * @param Zend_Http_Client_Adapter_Interface|string $adapter
  671. * @return null
  672. * @throws Zend_Http_Client_Exception
  673. */
  674. public function setAdapter($adapter)
  675. {
  676. if (is_string($adapter)) {
  677. try {
  678. Zend_Loader::loadClass($adapter);
  679. } catch (Zend_Exception $e) {
  680. /** @see Zend_Http_Client_Exception */
  681. require_once 'Zend/Http/Client/Exception.php';
  682. throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}");
  683. }
  684. $adapter = new $adapter;
  685. }
  686. if (! $adapter instanceof Zend_Http_Client_Adapter_Interface) {
  687. /** @see Zend_Http_Client_Exception */
  688. require_once 'Zend/Http/Client/Exception.php';
  689. throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
  690. }
  691. $this->adapter = $adapter;
  692. $config = $this->config;
  693. unset($config['adapter']);
  694. $this->adapter->setConfig($config);
  695. }
  696. /**
  697. * Send the HTTP request and return an HTTP response object
  698. *
  699. * @param string $method
  700. * @return Zend_Http_Response
  701. * @throws Zend_Http_Client_Exception
  702. */
  703. public function request($method = null)
  704. {
  705. if (! $this->uri instanceof Zend_Uri_Http) {
  706. /** @see Zend_Http_Client_Exception */
  707. require_once 'Zend/Http/Client/Exception.php';
  708. throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
  709. }
  710. if ($method) $this->setMethod($method);
  711. $this->redirectCounter = 0;
  712. $response = null;
  713. // Make sure the adapter is loaded
  714. if ($this->adapter == null) $this->setAdapter($this->config['adapter']);
  715. // Send the first request. If redirected, continue.
  716. do {
  717. // Clone the URI and add the additional GET parameters to it
  718. $uri = clone $this->uri;
  719. if (! empty($this->paramsGet)) {
  720. $query = $uri->getQuery();
  721. if (! empty($query)) $query .= '&';
  722. $query .= http_build_query($this->paramsGet, null, '&');
  723. $uri->setQuery($query);
  724. }
  725. $body = $this->_prepareBody();
  726. $headers = $this->_prepareHeaders();
  727. // Open the connection, send the request and read the response
  728. $this->adapter->connect($uri->getHost(), $uri->getPort(),
  729. ($uri->getScheme() == 'https' ? true : false));
  730. $this->last_request = $this->adapter->write($this->method,
  731. $uri, $this->config['httpversion'], $headers, $body);
  732. $response = $this->adapter->read();
  733. if (! $response) {
  734. /** @see Zend_Http_Client_Exception */
  735. require_once 'Zend/Http/Client/Exception.php';
  736. throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
  737. }
  738. $response = Zend_Http_Response::fromString($response);
  739. if ($this->config['storeresponse']) $this->last_response = $response;
  740. // Load cookies into cookie jar
  741. if (isset($this->cookiejar)) $this->cookiejar->addCookiesFromResponse($response, $uri);
  742. // If we got redirected, look for the Location header
  743. if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
  744. // Check whether we send the exact same request again, or drop the parameters
  745. // and send a GET request
  746. if ($response->getStatus() == 303 ||
  747. ((! $this->config['strictredirects']) && ($response->getStatus() == 302 ||
  748. $response->getStatus() == 301))) {
  749. $this->resetParameters();
  750. $this->setMethod(self::GET);
  751. }
  752. // If we got a well formed absolute URI
  753. if (Zend_Uri_Http::check($location)) {
  754. $this->setHeaders('host', null);
  755. $this->setUri($location);
  756. } else {
  757. // Split into path and query and set the query
  758. if (strpos($location, '?') !== false) {
  759. list($location, $query) = explode('?', $location, 2);
  760. } else {
  761. $query = '';
  762. }
  763. $this->uri->setQuery($query);
  764. // Else, if we got just an absolute path, set it
  765. if(strpos($location, '/') === 0) {
  766. $this->uri->setPath($location);
  767. // Else, assume we have a relative path
  768. } else {
  769. // Get the current path directory, removing any trailing slashes
  770. $path = $this->uri->getPath();
  771. $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
  772. $this->uri->setPath($path . '/' . $location);
  773. }
  774. }
  775. ++$this->redirectCounter;
  776. } else {
  777. // If we didn't get any location, stop redirecting
  778. break;
  779. }
  780. } while ($this->redirectCounter < $this->config['maxredirects']);
  781. return $response;
  782. }
  783. /**
  784. * Prepare the request headers
  785. *
  786. * @return array
  787. */
  788. protected function _prepareHeaders()
  789. {
  790. $headers = array();
  791. // Set the host header
  792. if (! isset($this->headers['host'])) {
  793. $host = $this->uri->getHost();
  794. // If the port is not default, add it
  795. if (! (($this->uri->getScheme() == 'http' && $this->uri->getPort() == 80) ||
  796. ($this->uri->getScheme() == 'https' && $this->uri->getPort() == 443))) {
  797. $host .= ':' . $this->uri->getPort();
  798. }
  799. $headers[] = "Host: {$host}";
  800. }
  801. // Set the connection header
  802. if (! isset($this->headers['connection'])) {
  803. if (! $this->config['keepalive']) $headers[] = "Connection: close";
  804. }
  805. // Set the Accept-encoding header if not set - depending on whether
  806. // zlib is available or not.
  807. if (! isset($this->headers['accept-encoding'])) {
  808. if (function_exists('gzinflate')) {
  809. $headers[] = 'Accept-encoding: gzip, deflate';
  810. } else {
  811. $headers[] = 'Accept-encoding: identity';
  812. }
  813. }
  814. // Set the content-type header
  815. if ($this->method == self::POST &&
  816. (! isset($this->headers['content-type']) && isset($this->enctype))) {
  817. $headers[] = "Content-type: {$this->enctype}";
  818. }
  819. // Set the user agent header
  820. if (! isset($this->headers['user-agent']) && isset($this->config['useragent'])) {
  821. $headers[] = "User-agent: {$this->config['useragent']}";
  822. }
  823. // Set HTTP authentication if needed
  824. if (is_array($this->auth)) {
  825. $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'], $this->auth['type']);
  826. $headers[] = "Authorization: {$auth}";
  827. }
  828. // Load cookies from cookie jar
  829. if (isset($this->cookiejar)) {
  830. $cookstr = $this->cookiejar->getMatchingCookies($this->uri,
  831. true, Zend_Http_CookieJar::COOKIE_STRING_CONCAT);
  832. if ($cookstr) $headers[] = "Cookie: {$cookstr}";
  833. }
  834. // Add all other user defined headers
  835. foreach ($this->headers as $header) {
  836. list($name, $value) = $header;
  837. if (is_array($value))
  838. $value = implode(', ', $value);
  839. $headers[] = "$name: $value";
  840. }
  841. return $headers;
  842. }
  843. /**
  844. * Prepare the request body (for POST and PUT requests)
  845. *
  846. * @return string
  847. * @throws Zend_Http_Client_Exception
  848. */
  849. protected function _prepareBody()
  850. {
  851. // According to RFC2616, a TRACE request should not have a body.
  852. if ($this->method == self::TRACE) {
  853. return '';
  854. }
  855. // If we have raw_post_data set, just use it as the body.
  856. if (isset($this->raw_post_data)) {
  857. $this->setHeaders('Content-length', strlen($this->raw_post_data));
  858. return $this->raw_post_data;
  859. }
  860. $body = '';
  861. // If we have files to upload, force enctype to multipart/form-data
  862. if (count ($this->files) > 0) $this->setEncType(self::ENC_FORMDATA);
  863. // If we have POST parameters or files, encode and add them to the body
  864. if (count($this->paramsPost) > 0 || count($this->files) > 0) {
  865. switch($this->enctype) {
  866. case self::ENC_FORMDATA:
  867. // Encode body as multipart/form-data
  868. $boundary = '---ZENDHTTPCLIENT-' . md5(microtime());
  869. $this->setHeaders('Content-type', self::ENC_FORMDATA . "; boundary={$boundary}");
  870. // Get POST parameters and encode them
  871. $params = $this->_getParametersRecursive($this->paramsPost);
  872. foreach ($params as $pp) {
  873. $body .= self::encodeFormData($boundary, $pp[0], $pp[1]);
  874. }
  875. // Encode files
  876. foreach ($this->files as $name => $file) {
  877. $fhead = array('Content-type' => $file[1]);
  878. $body .= self::encodeFormData($boundary, $name, $file[2], $file[0], $fhead);
  879. }
  880. $body .= "--{$boundary}--\r\n";
  881. break;
  882. case self::ENC_URLENCODED:
  883. // Encode body as application/x-www-form-urlencoded
  884. $this->setHeaders('Content-type', self::ENC_URLENCODED);
  885. $body = http_build_query($this->paramsPost, '', '&');
  886. break;
  887. default:
  888. /** @see Zend_Http_Client_Exception */
  889. require_once 'Zend/Http/Client/Exception.php';
  890. throw new Zend_Http_Client_Exception("Cannot handle content type '{$this->enctype}' automatically." .
  891. " Please use Zend_Http_Client::setRawData to send this kind of content.");
  892. break;
  893. }
  894. }
  895. // Set the content-length if we have a body or if request is POST/PUT
  896. if ($body || $this->method == self::POST || $this->method == self::PUT) {
  897. $this->setHeaders('Content-length', strlen($body));
  898. }
  899. return $body;
  900. }
  901. /**
  902. * Helper method that gets a possibly multi-level parameters array (get or
  903. * post) and flattens it.
  904. *
  905. * The method returns an array of (key, value) pairs (because keys are not
  906. * necessarily unique. If one of the parameters in as array, it will also
  907. * add a [] suffix to the key.
  908. *
  909. * @param array $parray The parameters array
  910. * @param bool $urlencode Whether to urlencode the name and value
  911. * @return array
  912. */
  913. protected function _getParametersRecursive($parray, $urlencode = false)
  914. {
  915. if (! is_array($parray)) return $parray;
  916. $parameters = array();
  917. foreach ($parray as $name => $value) {
  918. if ($urlencode) $name = urlencode($name);
  919. // If $value is an array, iterate over it
  920. if (is_array($value)) {
  921. $name .= ($urlencode ? '%5B%5D' : '[]');
  922. foreach ($value as $subval) {
  923. if ($urlencode) $subval = urlencode($subval);
  924. $parameters[] = array($name, $subval);
  925. }
  926. } else {
  927. if ($urlencode) $value = urlencode($value);
  928. $parameters[] = array($name, $value);
  929. }
  930. }
  931. return $parameters;
  932. }
  933. /**
  934. * Attempt to detect the MIME type of a file using available extensions
  935. *
  936. * This method will try to detect the MIME type of a file. If the fileinfo
  937. * extension is available, it will be used. If not, the mime_magic
  938. * extension which is deprected but is still available in many PHP setups
  939. * will be tried.
  940. *
  941. * If neither extension is available, the default application/octet-stream
  942. * MIME type will be returned
  943. *
  944. * @param string $file File path
  945. * @return string MIME type
  946. */
  947. protected function _detectFileMimeType($file)
  948. {
  949. $type = null;
  950. // First try with fileinfo functions
  951. if (function_exists('finfo_open')) {
  952. if (self::$_fileInfoDb === null) {
  953. self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
  954. }
  955. if (self::$_fileInfoDb) {
  956. $type = finfo_file(self::$_fileInfoDb, $file);
  957. }
  958. } elseif (function_exists('mime_content_type')) {
  959. $type = mime_content_type($file);
  960. }
  961. // Fallback to the default application/octet-stream
  962. if (! $type) {
  963. $type = 'application/octet-stream';
  964. }
  965. return $type;
  966. }
  967. /**
  968. * Encode data to a multipart/form-data part suitable for a POST request.
  969. *
  970. * @param string $boundary
  971. * @param string $name
  972. * @param mixed $value
  973. * @param string $filename
  974. * @param array $headers Associative array of optional headers @example ("Content-transfer-encoding" => "binary")
  975. * @return string
  976. */
  977. public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array()) {
  978. $ret = "--{$boundary}\r\n" .
  979. 'Content-disposition: form-data; name="' . $name .'"';
  980. if ($filename) $ret .= '; filename="' . $filename . '"';
  981. $ret .= "\r\n";
  982. foreach ($headers as $hname => $hvalue) {
  983. $ret .= "{$hname}: {$hvalue}\r\n";
  984. }
  985. $ret .= "\r\n";
  986. $ret .= "{$value}\r\n";
  987. return $ret;
  988. }
  989. /**
  990. * Create a HTTP authentication "Authorization:" header according to the
  991. * specified user, password and authentication method.
  992. *
  993. * @see http://www.faqs.org/rfcs/rfc2617.html
  994. * @param string $user
  995. * @param string $password
  996. * @param string $type
  997. * @return string
  998. * @throws Zend_Http_Client_Exception
  999. */
  1000. public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
  1001. {
  1002. $authHeader = null;
  1003. switch ($type) {
  1004. case self::AUTH_BASIC:
  1005. // In basic authentication, the user name cannot contain ":"
  1006. if (strpos($user, ':') !== false) {
  1007. /** @see Zend_Http_Client_Exception */
  1008. require_once 'Zend/Http/Client/Exception.php';
  1009. throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
  1010. }
  1011. $authHeader = 'Basic ' . base64_encode($user . ':' . $password);
  1012. break;
  1013. //case self::AUTH_DIGEST:
  1014. /**
  1015. * @todo Implement digest authentication
  1016. */
  1017. // break;
  1018. default:
  1019. /** @see Zend_Http_Client_Exception */
  1020. require_once 'Zend/Http/Client/Exception.php';
  1021. throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");
  1022. }
  1023. return $authHeader;
  1024. }
  1025. }