PageRenderTime 63ms CodeModel.GetById 35ms RepoModel.GetById 1ms app.codeStats 0ms

/Zend/Http/Client.php

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