PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/libs/Zend/Http/Client/Adapter/Curl.php

https://github.com/quarkness/piwik
PHP | 510 lines | 255 code | 62 blank | 193 comment | 55 complexity | 803ed0c556673286cbb366f3de637222 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_Adapter
  18. * @version $Id: Curl.php 24272 2011-07-27 21:12:08Z mcleod@spaceweb.nl $
  19. * @copyright Copyright (c) 2005-2011 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_Uri_Http
  24. */
  25. // require_once 'Zend/Uri/Http.php';
  26. /**
  27. * @see Zend_Http_Client_Adapter_Interface
  28. */
  29. // require_once 'Zend/Http/Client/Adapter/Interface.php';
  30. /**
  31. * @see Zend_Http_Client_Adapter_Stream
  32. */
  33. // require_once 'Zend/Http/Client/Adapter/Stream.php';
  34. /**
  35. * An adapter class for Zend_Http_Client based on the curl extension.
  36. * Curl requires libcurl. See for full requirements the PHP manual: http://php.net/curl
  37. *
  38. * @category Zend
  39. * @package Zend_Http
  40. * @subpackage Client_Adapter
  41. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  42. * @license http://framework.zend.com/license/new-bsd New BSD License
  43. */
  44. class Zend_Http_Client_Adapter_Curl implements Zend_Http_Client_Adapter_Interface, Zend_Http_Client_Adapter_Stream
  45. {
  46. /**
  47. * Parameters array
  48. *
  49. * @var array
  50. */
  51. protected $_config = array();
  52. /**
  53. * What host/port are we connected to?
  54. *
  55. * @var array
  56. */
  57. protected $_connected_to = array(null, null);
  58. /**
  59. * The curl session handle
  60. *
  61. * @var resource|null
  62. */
  63. protected $_curl = null;
  64. /**
  65. * List of cURL options that should never be overwritten
  66. *
  67. * @var array
  68. */
  69. protected $_invalidOverwritableCurlOptions;
  70. /**
  71. * Response gotten from server
  72. *
  73. * @var string
  74. */
  75. protected $_response = null;
  76. /**
  77. * Stream for storing output
  78. *
  79. * @var resource
  80. */
  81. protected $out_stream;
  82. /**
  83. * Adapter constructor
  84. *
  85. * Config is set using setConfig()
  86. *
  87. * @return void
  88. * @throws Zend_Http_Client_Adapter_Exception
  89. */
  90. public function __construct()
  91. {
  92. if (!extension_loaded('curl')) {
  93. // require_once 'Zend/Http/Client/Adapter/Exception.php';
  94. throw new Zend_Http_Client_Adapter_Exception('cURL extension has to be loaded to use this Zend_Http_Client adapter.');
  95. }
  96. $this->_invalidOverwritableCurlOptions = array(
  97. CURLOPT_HTTPGET,
  98. CURLOPT_POST,
  99. CURLOPT_PUT,
  100. CURLOPT_CUSTOMREQUEST,
  101. CURLOPT_HEADER,
  102. CURLOPT_RETURNTRANSFER,
  103. CURLOPT_HTTPHEADER,
  104. CURLOPT_POSTFIELDS,
  105. CURLOPT_INFILE,
  106. CURLOPT_INFILESIZE,
  107. CURLOPT_PORT,
  108. CURLOPT_MAXREDIRS,
  109. CURLOPT_CONNECTTIMEOUT,
  110. CURL_HTTP_VERSION_1_1,
  111. CURL_HTTP_VERSION_1_0,
  112. );
  113. }
  114. /**
  115. * Set the configuration array for the adapter
  116. *
  117. * @throws Zend_Http_Client_Adapter_Exception
  118. * @param Zend_Config | array $config
  119. * @return Zend_Http_Client_Adapter_Curl
  120. */
  121. public function setConfig($config = array())
  122. {
  123. if ($config instanceof Zend_Config) {
  124. $config = $config->toArray();
  125. } elseif (! is_array($config)) {
  126. // require_once 'Zend/Http/Client/Adapter/Exception.php';
  127. throw new Zend_Http_Client_Adapter_Exception(
  128. 'Array or Zend_Config object expected, got ' . gettype($config)
  129. );
  130. }
  131. if(isset($config['proxy_user']) && isset($config['proxy_pass'])) {
  132. $this->setCurlOption(CURLOPT_PROXYUSERPWD, $config['proxy_user'].":".$config['proxy_pass']);
  133. unset($config['proxy_user'], $config['proxy_pass']);
  134. }
  135. foreach ($config as $k => $v) {
  136. $option = strtolower($k);
  137. switch($option) {
  138. case 'proxy_host':
  139. $this->setCurlOption(CURLOPT_PROXY, $v);
  140. break;
  141. case 'proxy_port':
  142. $this->setCurlOption(CURLOPT_PROXYPORT, $v);
  143. break;
  144. default:
  145. $this->_config[$option] = $v;
  146. break;
  147. }
  148. }
  149. return $this;
  150. }
  151. /**
  152. * Retrieve the array of all configuration options
  153. *
  154. * @return array
  155. */
  156. public function getConfig()
  157. {
  158. return $this->_config;
  159. }
  160. /**
  161. * Direct setter for cURL adapter related options.
  162. *
  163. * @param string|int $option
  164. * @param mixed $value
  165. * @return Zend_Http_Adapter_Curl
  166. */
  167. public function setCurlOption($option, $value)
  168. {
  169. if (!isset($this->_config['curloptions'])) {
  170. $this->_config['curloptions'] = array();
  171. }
  172. $this->_config['curloptions'][$option] = $value;
  173. return $this;
  174. }
  175. /**
  176. * Initialize curl
  177. *
  178. * @param string $host
  179. * @param int $port
  180. * @param boolean $secure
  181. * @return void
  182. * @throws Zend_Http_Client_Adapter_Exception if unable to connect
  183. */
  184. public function connect($host, $port = 80, $secure = false)
  185. {
  186. // If we're already connected, disconnect first
  187. if ($this->_curl) {
  188. $this->close();
  189. }
  190. // If we are connected to a different server or port, disconnect first
  191. if ($this->_curl
  192. && is_array($this->_connected_to)
  193. && ($this->_connected_to[0] != $host
  194. || $this->_connected_to[1] != $port)
  195. ) {
  196. $this->close();
  197. }
  198. // Do the actual connection
  199. $this->_curl = curl_init();
  200. if ($port != 80) {
  201. curl_setopt($this->_curl, CURLOPT_PORT, intval($port));
  202. }
  203. // Set timeout
  204. curl_setopt($this->_curl, CURLOPT_CONNECTTIMEOUT, $this->_config['timeout']);
  205. // Set Max redirects
  206. curl_setopt($this->_curl, CURLOPT_MAXREDIRS, $this->_config['maxredirects']);
  207. if (!$this->_curl) {
  208. $this->close();
  209. // require_once 'Zend/Http/Client/Adapter/Exception.php';
  210. throw new Zend_Http_Client_Adapter_Exception('Unable to Connect to ' . $host . ':' . $port);
  211. }
  212. if ($secure !== false) {
  213. // Behave the same like Zend_Http_Adapter_Socket on SSL options.
  214. if (isset($this->_config['sslcert'])) {
  215. curl_setopt($this->_curl, CURLOPT_SSLCERT, $this->_config['sslcert']);
  216. }
  217. if (isset($this->_config['sslpassphrase'])) {
  218. curl_setopt($this->_curl, CURLOPT_SSLCERTPASSWD, $this->_config['sslpassphrase']);
  219. }
  220. }
  221. // Update connected_to
  222. $this->_connected_to = array($host, $port);
  223. }
  224. /**
  225. * Send request to the remote server
  226. *
  227. * @param string $method
  228. * @param Zend_Uri_Http $uri
  229. * @param float $http_ver
  230. * @param array $headers
  231. * @param string $body
  232. * @return string $request
  233. * @throws Zend_Http_Client_Adapter_Exception If connection fails, connected to wrong host, no PUT file defined, unsupported method, or unsupported cURL option
  234. */
  235. public function write($method, $uri, $httpVersion = 1.1, $headers = array(), $body = '')
  236. {
  237. // Make sure we're properly connected
  238. if (!$this->_curl) {
  239. // require_once 'Zend/Http/Client/Adapter/Exception.php';
  240. throw new Zend_Http_Client_Adapter_Exception("Trying to write but we are not connected");
  241. }
  242. if ($this->_connected_to[0] != $uri->getHost() || $this->_connected_to[1] != $uri->getPort()) {
  243. // require_once 'Zend/Http/Client/Adapter/Exception.php';
  244. throw new Zend_Http_Client_Adapter_Exception("Trying to write but we are connected to the wrong host");
  245. }
  246. // set URL
  247. curl_setopt($this->_curl, CURLOPT_URL, $uri->__toString());
  248. // ensure correct curl call
  249. $curlValue = true;
  250. switch ($method) {
  251. case Zend_Http_Client::GET:
  252. $curlMethod = CURLOPT_HTTPGET;
  253. break;
  254. case Zend_Http_Client::POST:
  255. $curlMethod = CURLOPT_POST;
  256. break;
  257. case Zend_Http_Client::PUT:
  258. // There are two different types of PUT request, either a Raw Data string has been set
  259. // or CURLOPT_INFILE and CURLOPT_INFILESIZE are used.
  260. if(is_resource($body)) {
  261. $this->_config['curloptions'][CURLOPT_INFILE] = $body;
  262. }
  263. if (isset($this->_config['curloptions'][CURLOPT_INFILE])) {
  264. // Now we will probably already have Content-Length set, so that we have to delete it
  265. // from $headers at this point:
  266. foreach ($headers AS $k => $header) {
  267. if (preg_match('/Content-Length:\s*(\d+)/i', $header, $m)) {
  268. if(is_resource($body)) {
  269. $this->_config['curloptions'][CURLOPT_INFILESIZE] = (int)$m[1];
  270. }
  271. unset($headers[$k]);
  272. }
  273. }
  274. if (!isset($this->_config['curloptions'][CURLOPT_INFILESIZE])) {
  275. // require_once 'Zend/Http/Client/Adapter/Exception.php';
  276. throw new Zend_Http_Client_Adapter_Exception("Cannot set a file-handle for cURL option CURLOPT_INFILE without also setting its size in CURLOPT_INFILESIZE.");
  277. }
  278. if(is_resource($body)) {
  279. $body = '';
  280. }
  281. $curlMethod = CURLOPT_PUT;
  282. } else {
  283. $curlMethod = CURLOPT_CUSTOMREQUEST;
  284. $curlValue = "PUT";
  285. }
  286. break;
  287. case Zend_Http_Client::DELETE:
  288. $curlMethod = CURLOPT_CUSTOMREQUEST;
  289. $curlValue = "DELETE";
  290. break;
  291. case Zend_Http_Client::OPTIONS:
  292. $curlMethod = CURLOPT_CUSTOMREQUEST;
  293. $curlValue = "OPTIONS";
  294. break;
  295. case Zend_Http_Client::TRACE:
  296. $curlMethod = CURLOPT_CUSTOMREQUEST;
  297. $curlValue = "TRACE";
  298. break;
  299. case Zend_Http_Client::HEAD:
  300. $curlMethod = CURLOPT_CUSTOMREQUEST;
  301. $curlValue = "HEAD";
  302. break;
  303. default:
  304. // For now, through an exception for unsupported request methods
  305. // require_once 'Zend/Http/Client/Adapter/Exception.php';
  306. throw new Zend_Http_Client_Adapter_Exception("Method currently not supported");
  307. }
  308. if(is_resource($body) && $curlMethod != CURLOPT_PUT) {
  309. // require_once 'Zend/Http/Client/Adapter/Exception.php';
  310. throw new Zend_Http_Client_Adapter_Exception("Streaming requests are allowed only with PUT");
  311. }
  312. // get http version to use
  313. $curlHttp = ($httpVersion == 1.1) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0;
  314. // mark as HTTP request and set HTTP method
  315. curl_setopt($this->_curl, $curlHttp, true);
  316. curl_setopt($this->_curl, $curlMethod, $curlValue);
  317. if($this->out_stream) {
  318. // headers will be read into the response
  319. curl_setopt($this->_curl, CURLOPT_HEADER, false);
  320. curl_setopt($this->_curl, CURLOPT_HEADERFUNCTION, array($this, "readHeader"));
  321. // and data will be written into the file
  322. curl_setopt($this->_curl, CURLOPT_FILE, $this->out_stream);
  323. } else {
  324. // ensure headers are also returned
  325. curl_setopt($this->_curl, CURLOPT_HEADER, true);
  326. // ensure actual response is returned
  327. curl_setopt($this->_curl, CURLOPT_RETURNTRANSFER, true);
  328. }
  329. // set additional headers
  330. $headers['Accept'] = '';
  331. curl_setopt($this->_curl, CURLOPT_HTTPHEADER, $headers);
  332. /**
  333. * Make sure POSTFIELDS is set after $curlMethod is set:
  334. * @link http://de2.php.net/manual/en/function.curl-setopt.php#81161
  335. */
  336. if ($method == Zend_Http_Client::POST) {
  337. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  338. } elseif ($curlMethod == CURLOPT_PUT) {
  339. // this covers a PUT by file-handle:
  340. // Make the setting of this options explicit (rather than setting it through the loop following a bit lower)
  341. // to group common functionality together.
  342. curl_setopt($this->_curl, CURLOPT_INFILE, $this->_config['curloptions'][CURLOPT_INFILE]);
  343. curl_setopt($this->_curl, CURLOPT_INFILESIZE, $this->_config['curloptions'][CURLOPT_INFILESIZE]);
  344. unset($this->_config['curloptions'][CURLOPT_INFILE]);
  345. unset($this->_config['curloptions'][CURLOPT_INFILESIZE]);
  346. } elseif ($method == Zend_Http_Client::PUT) {
  347. // This is a PUT by a setRawData string, not by file-handle
  348. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  349. } elseif ($method == Zend_Http_Client::DELETE) {
  350. // This is a DELETE by a setRawData string
  351. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  352. }
  353. // set additional curl options
  354. if (isset($this->_config['curloptions'])) {
  355. foreach ((array)$this->_config['curloptions'] as $k => $v) {
  356. if (!in_array($k, $this->_invalidOverwritableCurlOptions)) {
  357. if (curl_setopt($this->_curl, $k, $v) == false) {
  358. // require_once 'Zend/Http/Client/Exception.php';
  359. throw new Zend_Http_Client_Exception(sprintf("Unknown or erroreous cURL option '%s' set", $k));
  360. }
  361. }
  362. }
  363. }
  364. // send the request
  365. $response = curl_exec($this->_curl);
  366. // if we used streaming, headers are already there
  367. if(!is_resource($this->out_stream)) {
  368. $this->_response = $response;
  369. }
  370. $request = curl_getinfo($this->_curl, CURLINFO_HEADER_OUT);
  371. $request .= $body;
  372. if (empty($this->_response)) {
  373. // require_once 'Zend/Http/Client/Exception.php';
  374. throw new Zend_Http_Client_Exception("Error in cURL request: " . curl_error($this->_curl));
  375. }
  376. // cURL automatically decodes chunked-messages, this means we have to disallow the Zend_Http_Response to do it again
  377. if (stripos($this->_response, "Transfer-Encoding: chunked\r\n")) {
  378. $this->_response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $this->_response);
  379. }
  380. // Eliminate multiple HTTP responses.
  381. do {
  382. $parts = preg_split('|(?:\r?\n){2}|m', $this->_response, 2);
  383. $again = false;
  384. if (isset($parts[1]) && preg_match("|^HTTP/1\.[01](.*?)\r\n|mi", $parts[1])) {
  385. $this->_response = $parts[1];
  386. $again = true;
  387. }
  388. } while ($again);
  389. // cURL automatically handles Proxy rewrites, remove the "HTTP/1.0 200 Connection established" string:
  390. if (stripos($this->_response, "HTTP/1.0 200 Connection established\r\n\r\n") !== false) {
  391. $this->_response = str_ireplace("HTTP/1.0 200 Connection established\r\n\r\n", '', $this->_response);
  392. }
  393. return $request;
  394. }
  395. /**
  396. * Return read response from server
  397. *
  398. * @return string
  399. */
  400. public function read()
  401. {
  402. return $this->_response;
  403. }
  404. /**
  405. * Close the connection to the server
  406. *
  407. */
  408. public function close()
  409. {
  410. if(is_resource($this->_curl)) {
  411. curl_close($this->_curl);
  412. }
  413. $this->_curl = null;
  414. $this->_connected_to = array(null, null);
  415. }
  416. /**
  417. * Get cUrl Handle
  418. *
  419. * @return resource
  420. */
  421. public function getHandle()
  422. {
  423. return $this->_curl;
  424. }
  425. /**
  426. * Set output stream for the response
  427. *
  428. * @param resource $stream
  429. * @return Zend_Http_Client_Adapter_Socket
  430. */
  431. public function setOutputStream($stream)
  432. {
  433. $this->out_stream = $stream;
  434. return $this;
  435. }
  436. /**
  437. * Header reader function for CURL
  438. *
  439. * @param resource $curl
  440. * @param string $header
  441. * @return int
  442. */
  443. public function readHeader($curl, $header)
  444. {
  445. $this->_response .= $header;
  446. return strlen($header);
  447. }
  448. }