PageRenderTime 55ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Zend/Http/Client.php

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