2
0

Curl.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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$
  19. * @copyright Copyright (c) 2005-2014 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-2014 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. if (defined('CURLOPT_CONNECTTIMEOUT_MS')) {
  205. curl_setopt($this->_curl, CURLOPT_CONNECTTIMEOUT_MS, $this->_config['timeout'] * 1000);
  206. } else {
  207. curl_setopt($this->_curl, CURLOPT_CONNECTTIMEOUT, $this->_config['timeout']);
  208. }
  209. if (defined('CURLOPT_TIMEOUT_MS')) {
  210. curl_setopt($this->_curl, CURLOPT_TIMEOUT_MS, $this->_config['timeout'] * 1000);
  211. } else {
  212. curl_setopt($this->_curl, CURLOPT_TIMEOUT, $this->_config['timeout']);
  213. }
  214. // Set Max redirects
  215. curl_setopt($this->_curl, CURLOPT_MAXREDIRS, $this->_config['maxredirects']);
  216. if (!$this->_curl) {
  217. $this->close();
  218. require_once 'Zend/Http/Client/Adapter/Exception.php';
  219. throw new Zend_Http_Client_Adapter_Exception('Unable to Connect to ' . $host . ':' . $port);
  220. }
  221. if ($secure !== false) {
  222. // Behave the same like Zend_Http_Adapter_Socket on SSL options.
  223. if (isset($this->_config['sslcert'])) {
  224. curl_setopt($this->_curl, CURLOPT_SSLCERT, $this->_config['sslcert']);
  225. }
  226. if (isset($this->_config['sslpassphrase'])) {
  227. curl_setopt($this->_curl, CURLOPT_SSLCERTPASSWD, $this->_config['sslpassphrase']);
  228. }
  229. }
  230. // Update connected_to
  231. $this->_connected_to = array($host, $port);
  232. }
  233. /**
  234. * Send request to the remote server
  235. *
  236. * @param string $method
  237. * @param Zend_Uri_Http $uri
  238. * @param float $http_ver
  239. * @param array $headers
  240. * @param string $body
  241. * @return string $request
  242. * @throws Zend_Http_Client_Adapter_Exception If connection fails, connected to wrong host, no PUT file defined, unsupported method, or unsupported cURL option
  243. */
  244. public function write($method, $uri, $httpVersion = 1.1, $headers = array(), $body = '')
  245. {
  246. // Make sure we're properly connected
  247. if (!$this->_curl) {
  248. require_once 'Zend/Http/Client/Adapter/Exception.php';
  249. throw new Zend_Http_Client_Adapter_Exception("Trying to write but we are not connected");
  250. }
  251. if ($this->_connected_to[0] != $uri->getHost() || $this->_connected_to[1] != $uri->getPort()) {
  252. require_once 'Zend/Http/Client/Adapter/Exception.php';
  253. throw new Zend_Http_Client_Adapter_Exception("Trying to write but we are connected to the wrong host");
  254. }
  255. // set URL
  256. curl_setopt($this->_curl, CURLOPT_URL, $uri->__toString());
  257. // ensure correct curl call
  258. $curlValue = true;
  259. switch ($method) {
  260. case Zend_Http_Client::GET:
  261. $curlMethod = CURLOPT_HTTPGET;
  262. break;
  263. case Zend_Http_Client::POST:
  264. $curlMethod = CURLOPT_POST;
  265. break;
  266. case Zend_Http_Client::PUT:
  267. // There are two different types of PUT request, either a Raw Data string has been set
  268. // or CURLOPT_INFILE and CURLOPT_INFILESIZE are used.
  269. if(is_resource($body)) {
  270. $this->_config['curloptions'][CURLOPT_INFILE] = $body;
  271. }
  272. if (isset($this->_config['curloptions'][CURLOPT_INFILE])) {
  273. // Now we will probably already have Content-Length set, so that we have to delete it
  274. // from $headers at this point:
  275. foreach ($headers AS $k => $header) {
  276. if (preg_match('/Content-Length:\s*(\d+)/i', $header, $m)) {
  277. if(is_resource($body)) {
  278. $this->_config['curloptions'][CURLOPT_INFILESIZE] = (int)$m[1];
  279. }
  280. unset($headers[$k]);
  281. }
  282. }
  283. if (!isset($this->_config['curloptions'][CURLOPT_INFILESIZE])) {
  284. require_once 'Zend/Http/Client/Adapter/Exception.php';
  285. 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.");
  286. }
  287. if(is_resource($body)) {
  288. $body = '';
  289. }
  290. $curlMethod = CURLOPT_PUT;
  291. } else {
  292. $curlMethod = CURLOPT_CUSTOMREQUEST;
  293. $curlValue = "PUT";
  294. }
  295. break;
  296. case Zend_Http_Client::PATCH:
  297. $curlMethod = CURLOPT_CUSTOMREQUEST;
  298. $curlValue = "PATCH";
  299. break;
  300. case Zend_Http_Client::DELETE:
  301. $curlMethod = CURLOPT_CUSTOMREQUEST;
  302. $curlValue = "DELETE";
  303. break;
  304. case Zend_Http_Client::OPTIONS:
  305. $curlMethod = CURLOPT_CUSTOMREQUEST;
  306. $curlValue = "OPTIONS";
  307. break;
  308. case Zend_Http_Client::TRACE:
  309. $curlMethod = CURLOPT_CUSTOMREQUEST;
  310. $curlValue = "TRACE";
  311. break;
  312. case Zend_Http_Client::HEAD:
  313. $curlMethod = CURLOPT_CUSTOMREQUEST;
  314. $curlValue = "HEAD";
  315. break;
  316. default:
  317. // For now, through an exception for unsupported request methods
  318. require_once 'Zend/Http/Client/Adapter/Exception.php';
  319. throw new Zend_Http_Client_Adapter_Exception("Method currently not supported");
  320. }
  321. if(is_resource($body) && $curlMethod != CURLOPT_PUT) {
  322. require_once 'Zend/Http/Client/Adapter/Exception.php';
  323. throw new Zend_Http_Client_Adapter_Exception("Streaming requests are allowed only with PUT");
  324. }
  325. // get http version to use
  326. $curlHttp = ($httpVersion == 1.1) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0;
  327. // mark as HTTP request and set HTTP method
  328. curl_setopt($this->_curl, CURLOPT_HTTP_VERSION, $curlHttp);
  329. curl_setopt($this->_curl, $curlMethod, $curlValue);
  330. if($this->out_stream) {
  331. // headers will be read into the response
  332. curl_setopt($this->_curl, CURLOPT_HEADER, false);
  333. curl_setopt($this->_curl, CURLOPT_HEADERFUNCTION, array($this, "readHeader"));
  334. // and data will be written into the file
  335. curl_setopt($this->_curl, CURLOPT_FILE, $this->out_stream);
  336. } else {
  337. // ensure headers are also returned
  338. curl_setopt($this->_curl, CURLOPT_HEADER, true);
  339. curl_setopt($this->_curl, CURLINFO_HEADER_OUT, true);
  340. // ensure actual response is returned
  341. curl_setopt($this->_curl, CURLOPT_RETURNTRANSFER, true);
  342. }
  343. // set additional headers
  344. $headers['Accept'] = '';
  345. curl_setopt($this->_curl, CURLOPT_HTTPHEADER, $headers);
  346. /**
  347. * Make sure POSTFIELDS is set after $curlMethod is set:
  348. * @link http://de2.php.net/manual/en/function.curl-setopt.php#81161
  349. */
  350. if ($method == Zend_Http_Client::POST) {
  351. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  352. } elseif ($curlMethod == CURLOPT_PUT) {
  353. // this covers a PUT by file-handle:
  354. // Make the setting of this options explicit (rather than setting it through the loop following a bit lower)
  355. // to group common functionality together.
  356. curl_setopt($this->_curl, CURLOPT_INFILE, $this->_config['curloptions'][CURLOPT_INFILE]);
  357. curl_setopt($this->_curl, CURLOPT_INFILESIZE, $this->_config['curloptions'][CURLOPT_INFILESIZE]);
  358. unset($this->_config['curloptions'][CURLOPT_INFILE]);
  359. unset($this->_config['curloptions'][CURLOPT_INFILESIZE]);
  360. } elseif ($method == Zend_Http_Client::PUT) {
  361. // This is a PUT by a setRawData string, not by file-handle
  362. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  363. } elseif ($method == Zend_Http_Client::PATCH) {
  364. // This is a PATCH by a setRawData string
  365. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  366. } elseif ($method == Zend_Http_Client::DELETE) {
  367. // This is a DELETE by a setRawData string
  368. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  369. } elseif ($method == Zend_Http_Client::OPTIONS) {
  370. // This is an OPTIONS by a setRawData string
  371. curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $body);
  372. }
  373. // set additional curl options
  374. if (isset($this->_config['curloptions'])) {
  375. foreach ((array)$this->_config['curloptions'] as $k => $v) {
  376. if (!in_array($k, $this->_invalidOverwritableCurlOptions)) {
  377. if (curl_setopt($this->_curl, $k, $v) == false) {
  378. require_once 'Zend/Http/Client/Exception.php';
  379. throw new Zend_Http_Client_Exception(sprintf("Unknown or erroreous cURL option '%s' set", $k));
  380. }
  381. }
  382. }
  383. }
  384. // send the request
  385. $response = curl_exec($this->_curl);
  386. // if we used streaming, headers are already there
  387. if(!is_resource($this->out_stream)) {
  388. $this->_response = $response;
  389. }
  390. $request = curl_getinfo($this->_curl, CURLINFO_HEADER_OUT);
  391. $request .= $body;
  392. if (empty($this->_response)) {
  393. require_once 'Zend/Http/Client/Exception.php';
  394. throw new Zend_Http_Client_Exception("Error in cURL request: " . curl_error($this->_curl));
  395. }
  396. // cURL automatically decodes chunked-messages, this means we have to disallow the Zend_Http_Response to do it again
  397. if (stripos($this->_response, "Transfer-Encoding: chunked\r\n")) {
  398. $this->_response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $this->_response);
  399. }
  400. // Eliminate multiple HTTP responses.
  401. do {
  402. $parts = preg_split('|(?:\r?\n){2}|m', $this->_response, 2);
  403. $again = false;
  404. if (isset($parts[1]) && preg_match("|^HTTP/1\.[01](.*?)\r\n|mi", $parts[1])) {
  405. $this->_response = $parts[1];
  406. $again = true;
  407. }
  408. } while ($again);
  409. // cURL automatically handles Proxy rewrites, remove the "HTTP/1.0 200 Connection established" string:
  410. if (stripos($this->_response, "HTTP/1.0 200 Connection established\r\n\r\n") !== false) {
  411. $this->_response = str_ireplace("HTTP/1.0 200 Connection established\r\n\r\n", '', $this->_response);
  412. }
  413. return $request;
  414. }
  415. /**
  416. * Return read response from server
  417. *
  418. * @return string
  419. */
  420. public function read()
  421. {
  422. return $this->_response;
  423. }
  424. /**
  425. * Close the connection to the server
  426. *
  427. */
  428. public function close()
  429. {
  430. if(is_resource($this->_curl)) {
  431. curl_close($this->_curl);
  432. }
  433. $this->_curl = null;
  434. $this->_connected_to = array(null, null);
  435. }
  436. /**
  437. * Get cUrl Handle
  438. *
  439. * @return resource
  440. */
  441. public function getHandle()
  442. {
  443. return $this->_curl;
  444. }
  445. /**
  446. * Set output stream for the response
  447. *
  448. * @param resource $stream
  449. * @return Zend_Http_Client_Adapter_Socket
  450. */
  451. public function setOutputStream($stream)
  452. {
  453. $this->out_stream = $stream;
  454. return $this;
  455. }
  456. /**
  457. * Header reader function for CURL
  458. *
  459. * @param resource $curl
  460. * @param string $header
  461. * @return int
  462. */
  463. public function readHeader($curl, $header)
  464. {
  465. $this->_response .= $header;
  466. return strlen($header);
  467. }
  468. }