HttpSocket.php 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  1. <?php
  2. /**
  3. * HTTP Socket connection class.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.Network.Http
  17. * @since CakePHP(tm) v 1.2.0
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. App::uses('CakeSocket', 'Network');
  21. App::uses('Router', 'Routing');
  22. App::uses('Hash', 'Utility');
  23. /**
  24. * Cake network socket connection class.
  25. *
  26. * Core base class for HTTP network communication. HttpSocket can be used as an
  27. * Object Oriented replacement for cURL in many places.
  28. *
  29. * @package Cake.Network.Http
  30. */
  31. class HttpSocket extends CakeSocket {
  32. /**
  33. * When one activates the $quirksMode by setting it to true, all checks meant to
  34. * enforce RFC 2616 (HTTP/1.1 specs).
  35. * will be disabled and additional measures to deal with non-standard responses will be enabled.
  36. *
  37. * @var boolean
  38. */
  39. public $quirksMode = false;
  40. /**
  41. * Contain information about the last request (read only)
  42. *
  43. * @var array
  44. */
  45. public $request = array(
  46. 'method' => 'GET',
  47. 'uri' => array(
  48. 'scheme' => 'http',
  49. 'host' => null,
  50. 'port' => 80,
  51. 'user' => null,
  52. 'pass' => null,
  53. 'path' => null,
  54. 'query' => null,
  55. 'fragment' => null
  56. ),
  57. 'version' => '1.1',
  58. 'body' => '',
  59. 'line' => null,
  60. 'header' => array(
  61. 'Connection' => 'close',
  62. 'User-Agent' => 'CakePHP'
  63. ),
  64. 'raw' => null,
  65. 'redirect' => false,
  66. 'cookies' => array(),
  67. );
  68. /**
  69. * Contain information about the last response (read only)
  70. *
  71. * @var array
  72. */
  73. public $response = null;
  74. /**
  75. * Response classname
  76. *
  77. * @var string
  78. */
  79. public $responseClass = 'HttpSocketResponse';
  80. /**
  81. * Configuration settings for the HttpSocket and the requests
  82. *
  83. * @var array
  84. */
  85. public $config = array(
  86. 'persistent' => false,
  87. 'host' => 'localhost',
  88. 'protocol' => 'tcp',
  89. 'port' => 80,
  90. 'timeout' => 30,
  91. 'ssl_verify_peer' => true,
  92. 'ssl_verify_depth' => 5,
  93. 'ssl_verify_host' => true,
  94. 'request' => array(
  95. 'uri' => array(
  96. 'scheme' => array('http', 'https'),
  97. 'host' => 'localhost',
  98. 'port' => array(80, 443)
  99. ),
  100. 'redirect' => false,
  101. 'cookies' => array(),
  102. )
  103. );
  104. /**
  105. * Authentication settings
  106. *
  107. * @var array
  108. */
  109. protected $_auth = array();
  110. /**
  111. * Proxy settings
  112. *
  113. * @var array
  114. */
  115. protected $_proxy = array();
  116. /**
  117. * Resource to receive the content of request
  118. *
  119. * @var mixed
  120. */
  121. protected $_contentResource = null;
  122. /**
  123. * Build an HTTP Socket using the specified configuration.
  124. *
  125. * You can use an URL string to set the URL and use default configurations for
  126. * all other options:
  127. *
  128. * `$http = new HttpSocket('http://cakephp.org/');`
  129. *
  130. * Or use an array to configure multiple options:
  131. *
  132. * {{{
  133. * $http = new HttpSocket(array(
  134. * 'host' => 'cakephp.org',
  135. * 'timeout' => 20
  136. * ));
  137. * }}}
  138. *
  139. * See HttpSocket::$config for options that can be used.
  140. *
  141. * @param string|array $config Configuration information, either a string URL or an array of options.
  142. */
  143. public function __construct($config = array()) {
  144. if (is_string($config)) {
  145. $this->_configUri($config);
  146. } elseif (is_array($config)) {
  147. if (isset($config['request']['uri']) && is_string($config['request']['uri'])) {
  148. $this->_configUri($config['request']['uri']);
  149. unset($config['request']['uri']);
  150. }
  151. $this->config = Hash::merge($this->config, $config);
  152. }
  153. parent::__construct($this->config);
  154. }
  155. /**
  156. * Set authentication settings.
  157. *
  158. * Accepts two forms of parameters. If all you need is a username + password, as with
  159. * Basic authentication you can do the following:
  160. *
  161. * {{{
  162. * $http->configAuth('Basic', 'mark', 'secret');
  163. * }}}
  164. *
  165. * If you are using an authentication strategy that requires more inputs, like Digest authentication
  166. * you can call `configAuth()` with an array of user information.
  167. *
  168. * {{{
  169. * $http->configAuth('Digest', array(
  170. * 'user' => 'mark',
  171. * 'pass' => 'secret',
  172. * 'realm' => 'my-realm',
  173. * 'nonce' => 1235
  174. * ));
  175. * }}}
  176. *
  177. * To remove any set authentication strategy, call `configAuth()` with no parameters:
  178. *
  179. * `$http->configAuth();`
  180. *
  181. * @param string $method Authentication method (ie. Basic, Digest). If empty, disable authentication
  182. * @param string|array $user Username for authentication. Can be an array with settings to authentication class
  183. * @param string $pass Password for authentication
  184. * @return void
  185. */
  186. public function configAuth($method, $user = null, $pass = null) {
  187. if (empty($method)) {
  188. $this->_auth = array();
  189. return;
  190. }
  191. if (is_array($user)) {
  192. $this->_auth = array($method => $user);
  193. return;
  194. }
  195. $this->_auth = array($method => compact('user', 'pass'));
  196. }
  197. /**
  198. * Set proxy settings
  199. *
  200. * @param string|array $host Proxy host. Can be an array with settings to authentication class
  201. * @param integer $port Port. Default 3128.
  202. * @param string $method Proxy method (ie, Basic, Digest). If empty, disable proxy authentication
  203. * @param string $user Username if your proxy need authentication
  204. * @param string $pass Password to proxy authentication
  205. * @return void
  206. */
  207. public function configProxy($host, $port = 3128, $method = null, $user = null, $pass = null) {
  208. if (empty($host)) {
  209. $this->_proxy = array();
  210. return;
  211. }
  212. if (is_array($host)) {
  213. $this->_proxy = $host + array('host' => null);
  214. return;
  215. }
  216. $this->_proxy = compact('host', 'port', 'method', 'user', 'pass');
  217. }
  218. /**
  219. * Set the resource to receive the request content. This resource must support fwrite.
  220. *
  221. * @param resource|boolean $resource Resource or false to disable the resource use
  222. * @return void
  223. * @throws SocketException
  224. */
  225. public function setContentResource($resource) {
  226. if ($resource === false) {
  227. $this->_contentResource = null;
  228. return;
  229. }
  230. if (!is_resource($resource)) {
  231. throw new SocketException(__d('cake_dev', 'Invalid resource.'));
  232. }
  233. $this->_contentResource = $resource;
  234. }
  235. /**
  236. * Issue the specified request. HttpSocket::get() and HttpSocket::post() wrap this
  237. * method and provide a more granular interface.
  238. *
  239. * @param string|array $request Either an URI string, or an array defining host/uri
  240. * @return mixed false on error, HttpSocketResponse on success
  241. * @throws SocketException
  242. */
  243. public function request($request = array()) {
  244. $this->reset(false);
  245. if (is_string($request)) {
  246. $request = array('uri' => $request);
  247. } elseif (!is_array($request)) {
  248. return false;
  249. }
  250. if (!isset($request['uri'])) {
  251. $request['uri'] = null;
  252. }
  253. $uri = $this->_parseUri($request['uri']);
  254. if (!isset($uri['host'])) {
  255. $host = $this->config['host'];
  256. }
  257. if (isset($request['host'])) {
  258. $host = $request['host'];
  259. unset($request['host']);
  260. }
  261. $request['uri'] = $this->url($request['uri']);
  262. $request['uri'] = $this->_parseUri($request['uri'], true);
  263. $this->request = Hash::merge($this->request, array_diff_key($this->config['request'], array('cookies' => true)), $request);
  264. $this->_configUri($this->request['uri']);
  265. $Host = $this->request['uri']['host'];
  266. if (!empty($this->config['request']['cookies'][$Host])) {
  267. if (!isset($this->request['cookies'])) {
  268. $this->request['cookies'] = array();
  269. }
  270. if (!isset($request['cookies'])) {
  271. $request['cookies'] = array();
  272. }
  273. $this->request['cookies'] = array_merge($this->request['cookies'], $this->config['request']['cookies'][$Host], $request['cookies']);
  274. }
  275. if (isset($host)) {
  276. $this->config['host'] = $host;
  277. }
  278. $this->_setProxy();
  279. $this->request['proxy'] = $this->_proxy;
  280. $cookies = null;
  281. if (is_array($this->request['header'])) {
  282. if (!empty($this->request['cookies'])) {
  283. $cookies = $this->buildCookies($this->request['cookies']);
  284. }
  285. $scheme = '';
  286. $port = 0;
  287. if (isset($this->request['uri']['scheme'])) {
  288. $scheme = $this->request['uri']['scheme'];
  289. }
  290. if (isset($this->request['uri']['port'])) {
  291. $port = $this->request['uri']['port'];
  292. }
  293. if (
  294. ($scheme === 'http' && $port != 80) ||
  295. ($scheme === 'https' && $port != 443) ||
  296. ($port != 80 && $port != 443)
  297. ) {
  298. $Host .= ':' . $port;
  299. }
  300. $this->request['header'] = array_merge(compact('Host'), $this->request['header']);
  301. }
  302. if (isset($this->request['uri']['user'], $this->request['uri']['pass'])) {
  303. $this->configAuth('Basic', $this->request['uri']['user'], $this->request['uri']['pass']);
  304. } elseif (isset($this->request['auth'], $this->request['auth']['method'], $this->request['auth']['user'], $this->request['auth']['pass'])) {
  305. $this->configAuth($this->request['auth']['method'], $this->request['auth']['user'], $this->request['auth']['pass']);
  306. }
  307. $this->_setAuth();
  308. $this->request['auth'] = $this->_auth;
  309. if (is_array($this->request['body'])) {
  310. $this->request['body'] = http_build_query($this->request['body'], '', '&');
  311. }
  312. if (!empty($this->request['body']) && !isset($this->request['header']['Content-Type'])) {
  313. $this->request['header']['Content-Type'] = 'application/x-www-form-urlencoded';
  314. }
  315. if (!empty($this->request['body']) && !isset($this->request['header']['Content-Length'])) {
  316. $this->request['header']['Content-Length'] = strlen($this->request['body']);
  317. }
  318. $connectionType = null;
  319. if (isset($this->request['header']['Connection'])) {
  320. $connectionType = $this->request['header']['Connection'];
  321. }
  322. $this->request['header'] = $this->_buildHeader($this->request['header']) . $cookies;
  323. if (empty($this->request['line'])) {
  324. $this->request['line'] = $this->_buildRequestLine($this->request);
  325. }
  326. if ($this->quirksMode === false && $this->request['line'] === false) {
  327. return false;
  328. }
  329. $this->_configContext($this->request['uri']['host']);
  330. $this->request['raw'] = '';
  331. if ($this->request['line'] !== false) {
  332. $this->request['raw'] = $this->request['line'];
  333. }
  334. if ($this->request['header'] !== false) {
  335. $this->request['raw'] .= $this->request['header'];
  336. }
  337. $this->request['raw'] .= "\r\n";
  338. $this->request['raw'] .= $this->request['body'];
  339. $this->write($this->request['raw']);
  340. $response = null;
  341. $inHeader = true;
  342. while ($data = $this->read()) {
  343. if ($this->_contentResource) {
  344. if ($inHeader) {
  345. $response .= $data;
  346. $pos = strpos($response, "\r\n\r\n");
  347. if ($pos !== false) {
  348. $pos += 4;
  349. $data = substr($response, $pos);
  350. fwrite($this->_contentResource, $data);
  351. $response = substr($response, 0, $pos);
  352. $inHeader = false;
  353. }
  354. } else {
  355. fwrite($this->_contentResource, $data);
  356. fflush($this->_contentResource);
  357. }
  358. } else {
  359. $response .= $data;
  360. }
  361. }
  362. if ($connectionType === 'close') {
  363. $this->disconnect();
  364. }
  365. list($plugin, $responseClass) = pluginSplit($this->responseClass, true);
  366. App::uses($responseClass, $plugin . 'Network/Http');
  367. if (!class_exists($responseClass)) {
  368. throw new SocketException(__d('cake_dev', 'Class %s not found.', $this->responseClass));
  369. }
  370. $this->response = new $responseClass($response);
  371. if (!empty($this->response->cookies)) {
  372. if (!isset($this->config['request']['cookies'][$Host])) {
  373. $this->config['request']['cookies'][$Host] = array();
  374. }
  375. $this->config['request']['cookies'][$Host] = array_merge($this->config['request']['cookies'][$Host], $this->response->cookies);
  376. }
  377. if ($this->request['redirect'] && $this->response->isRedirect()) {
  378. $request['uri'] = trim(urldecode($this->response->getHeader('Location')), '=');
  379. $request['redirect'] = is_int($this->request['redirect']) ? $this->request['redirect'] - 1 : $this->request['redirect'];
  380. $this->response = $this->request($request);
  381. }
  382. return $this->response;
  383. }
  384. /**
  385. * Issues a GET request to the specified URI, query, and request.
  386. *
  387. * Using a string uri and an array of query string parameters:
  388. *
  389. * `$response = $http->get('http://google.com/search', array('q' => 'cakephp', 'client' => 'safari'));`
  390. *
  391. * Would do a GET request to `http://google.com/search?q=cakephp&client=safari`
  392. *
  393. * You could express the same thing using a uri array and query string parameters:
  394. *
  395. * {{{
  396. * $response = $http->get(
  397. * array('host' => 'google.com', 'path' => '/search'),
  398. * array('q' => 'cakephp', 'client' => 'safari')
  399. * );
  400. * }}}
  401. *
  402. * @param string|array $uri URI to request. Either a string uri, or a uri array, see HttpSocket::_parseUri()
  403. * @param array $query Querystring parameters to append to URI
  404. * @param array $request An indexed array with indexes such as 'method' or uri
  405. * @return mixed Result of request, either false on failure or the response to the request.
  406. */
  407. public function get($uri = null, $query = array(), $request = array()) {
  408. if (!empty($query)) {
  409. $uri = $this->_parseUri($uri, $this->config['request']['uri']);
  410. if (isset($uri['query'])) {
  411. $uri['query'] = array_merge($uri['query'], $query);
  412. } else {
  413. $uri['query'] = $query;
  414. }
  415. $uri = $this->_buildUri($uri);
  416. }
  417. $request = Hash::merge(array('method' => 'GET', 'uri' => $uri), $request);
  418. return $this->request($request);
  419. }
  420. /**
  421. * Issues a POST request to the specified URI, query, and request.
  422. *
  423. * `post()` can be used to post simple data arrays to an URL:
  424. *
  425. * {{{
  426. * $response = $http->post('http://example.com', array(
  427. * 'username' => 'batman',
  428. * 'password' => 'bruce_w4yne'
  429. * ));
  430. * }}}
  431. *
  432. * @param string|array $uri URI to request. See HttpSocket::_parseUri()
  433. * @param array $data Array of POST data keys and values.
  434. * @param array $request An indexed array with indexes such as 'method' or uri
  435. * @return mixed Result of request, either false on failure or the response to the request.
  436. */
  437. public function post($uri = null, $data = array(), $request = array()) {
  438. $request = Hash::merge(array('method' => 'POST', 'uri' => $uri, 'body' => $data), $request);
  439. return $this->request($request);
  440. }
  441. /**
  442. * Issues a PUT request to the specified URI, query, and request.
  443. *
  444. * @param string|array $uri URI to request, See HttpSocket::_parseUri()
  445. * @param array $data Array of PUT data keys and values.
  446. * @param array $request An indexed array with indexes such as 'method' or uri
  447. * @return mixed Result of request
  448. */
  449. public function put($uri = null, $data = array(), $request = array()) {
  450. $request = Hash::merge(array('method' => 'PUT', 'uri' => $uri, 'body' => $data), $request);
  451. return $this->request($request);
  452. }
  453. /**
  454. * Issues a DELETE request to the specified URI, query, and request.
  455. *
  456. * @param string|array $uri URI to request (see {@link _parseUri()})
  457. * @param array $data Query to append to URI
  458. * @param array $request An indexed array with indexes such as 'method' or uri
  459. * @return mixed Result of request
  460. */
  461. public function delete($uri = null, $data = array(), $request = array()) {
  462. $request = Hash::merge(array('method' => 'DELETE', 'uri' => $uri, 'body' => $data), $request);
  463. return $this->request($request);
  464. }
  465. /**
  466. * Normalizes URLs into a $uriTemplate. If no template is provided
  467. * a default one will be used. Will generate the URL using the
  468. * current config information.
  469. *
  470. * ### Usage:
  471. *
  472. * After configuring part of the request parameters, you can use url() to generate
  473. * URLs.
  474. *
  475. * {{{
  476. * $http = new HttpSocket('http://www.cakephp.org');
  477. * $url = $http->url('/search?q=bar');
  478. * }}}
  479. *
  480. * Would return `http://www.cakephp.org/search?q=bar`
  481. *
  482. * url() can also be used with custom templates:
  483. *
  484. * `$url = $http->url('http://www.cakephp/search?q=socket', '/%path?%query');`
  485. *
  486. * Would return `/search?q=socket`.
  487. *
  488. * @param string|array Either a string or array of URL options to create an URL with.
  489. * @param string $uriTemplate A template string to use for URL formatting.
  490. * @return mixed Either false on failure or a string containing the composed URL.
  491. */
  492. public function url($url = null, $uriTemplate = null) {
  493. if (is_null($url)) {
  494. $url = '/';
  495. }
  496. if (is_string($url)) {
  497. $scheme = $this->config['request']['uri']['scheme'];
  498. if (is_array($scheme)) {
  499. $scheme = $scheme[0];
  500. }
  501. $port = $this->config['request']['uri']['port'];
  502. if (is_array($port)) {
  503. $port = $port[0];
  504. }
  505. if ($url{0} === '/') {
  506. $url = $this->config['request']['uri']['host'] . ':' . $port . $url;
  507. }
  508. if (!preg_match('/^.+:\/\/|\*|^\//', $url)) {
  509. $url = $scheme . '://' . $url;
  510. }
  511. } elseif (!is_array($url) && !empty($url)) {
  512. return false;
  513. }
  514. $base = array_merge($this->config['request']['uri'], array('scheme' => array('http', 'https'), 'port' => array(80, 443)));
  515. $url = $this->_parseUri($url, $base);
  516. if (empty($url)) {
  517. $url = $this->config['request']['uri'];
  518. }
  519. if (!empty($uriTemplate)) {
  520. return $this->_buildUri($url, $uriTemplate);
  521. }
  522. return $this->_buildUri($url);
  523. }
  524. /**
  525. * Set authentication in request
  526. *
  527. * @return void
  528. * @throws SocketException
  529. */
  530. protected function _setAuth() {
  531. if (empty($this->_auth)) {
  532. return;
  533. }
  534. $method = key($this->_auth);
  535. list($plugin, $authClass) = pluginSplit($method, true);
  536. $authClass = Inflector::camelize($authClass) . 'Authentication';
  537. App::uses($authClass, $plugin . 'Network/Http');
  538. if (!class_exists($authClass)) {
  539. throw new SocketException(__d('cake_dev', 'Unknown authentication method.'));
  540. }
  541. if (!method_exists($authClass, 'authentication')) {
  542. throw new SocketException(sprintf(__d('cake_dev', 'The %s do not support authentication.'), $authClass));
  543. }
  544. call_user_func_array("$authClass::authentication", array($this, &$this->_auth[$method]));
  545. }
  546. /**
  547. * Set the proxy configuration and authentication
  548. *
  549. * @return void
  550. * @throws SocketException
  551. */
  552. protected function _setProxy() {
  553. if (empty($this->_proxy) || !isset($this->_proxy['host'], $this->_proxy['port'])) {
  554. return;
  555. }
  556. $this->config['host'] = $this->_proxy['host'];
  557. $this->config['port'] = $this->_proxy['port'];
  558. if (empty($this->_proxy['method']) || !isset($this->_proxy['user'], $this->_proxy['pass'])) {
  559. return;
  560. }
  561. list($plugin, $authClass) = pluginSplit($this->_proxy['method'], true);
  562. $authClass = Inflector::camelize($authClass) . 'Authentication';
  563. App::uses($authClass, $plugin . 'Network/Http');
  564. if (!class_exists($authClass)) {
  565. throw new SocketException(__d('cake_dev', 'Unknown authentication method for proxy.'));
  566. }
  567. if (!method_exists($authClass, 'proxyAuthentication')) {
  568. throw new SocketException(sprintf(__d('cake_dev', 'The %s do not support proxy authentication.'), $authClass));
  569. }
  570. call_user_func_array("$authClass::proxyAuthentication", array($this, &$this->_proxy));
  571. }
  572. /**
  573. * Parses and sets the specified URI into current request configuration.
  574. *
  575. * @param string|array $uri URI, See HttpSocket::_parseUri()
  576. * @return boolean If uri has merged in config
  577. */
  578. protected function _configUri($uri = null) {
  579. if (empty($uri)) {
  580. return false;
  581. }
  582. if (is_array($uri)) {
  583. $uri = $this->_parseUri($uri);
  584. } else {
  585. $uri = $this->_parseUri($uri, true);
  586. }
  587. if (!isset($uri['host'])) {
  588. return false;
  589. }
  590. $config = array(
  591. 'request' => array(
  592. 'uri' => array_intersect_key($uri, $this->config['request']['uri'])
  593. )
  594. );
  595. $this->config = Hash::merge($this->config, $config);
  596. $this->config = Hash::merge($this->config, array_intersect_key($this->config['request']['uri'], $this->config));
  597. return true;
  598. }
  599. /**
  600. * Configure the socket's context. Adds in configuration
  601. * that can not be declared in the class definition.
  602. *
  603. * @param string $host The host you're connecting to.
  604. * @return void
  605. */
  606. protected function _configContext($host) {
  607. foreach ($this->config as $key => $value) {
  608. if (substr($key, 0, 4) !== 'ssl_') {
  609. continue;
  610. }
  611. $contextKey = substr($key, 4);
  612. if (empty($this->config['context']['ssl'][$contextKey])) {
  613. $this->config['context']['ssl'][$contextKey] = $value;
  614. }
  615. unset($this->config[$key]);
  616. }
  617. if (empty($this->_context['ssl']['cafile'])) {
  618. $this->config['context']['ssl']['cafile'] = CAKE . 'Config' . DS . 'cacert.pem';
  619. }
  620. if (!empty($this->config['context']['ssl']['verify_host'])) {
  621. $this->config['context']['ssl']['CN_match'] = $host;
  622. unset($this->config['context']['ssl']['verify_host']);
  623. }
  624. }
  625. /**
  626. * Takes a $uri array and turns it into a fully qualified URL string
  627. *
  628. * @param string|array $uri Either A $uri array, or a request string. Will use $this->config if left empty.
  629. * @param string $uriTemplate The Uri template/format to use.
  630. * @return mixed A fully qualified URL formatted according to $uriTemplate, or false on failure
  631. */
  632. protected function _buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') {
  633. if (is_string($uri)) {
  634. $uri = array('host' => $uri);
  635. }
  636. $uri = $this->_parseUri($uri, true);
  637. if (!is_array($uri) || empty($uri)) {
  638. return false;
  639. }
  640. $uri['path'] = preg_replace('/^\//', null, $uri['path']);
  641. $uri['query'] = http_build_query($uri['query'], '', '&');
  642. $uri['query'] = rtrim($uri['query'], '=');
  643. $stripIfEmpty = array(
  644. 'query' => '?%query',
  645. 'fragment' => '#%fragment',
  646. 'user' => '%user:%pass@',
  647. 'host' => '%host:%port/'
  648. );
  649. foreach ($stripIfEmpty as $key => $strip) {
  650. if (empty($uri[$key])) {
  651. $uriTemplate = str_replace($strip, null, $uriTemplate);
  652. }
  653. }
  654. $defaultPorts = array('http' => 80, 'https' => 443);
  655. if (array_key_exists($uri['scheme'], $defaultPorts) && $defaultPorts[$uri['scheme']] == $uri['port']) {
  656. $uriTemplate = str_replace(':%port', null, $uriTemplate);
  657. }
  658. foreach ($uri as $property => $value) {
  659. $uriTemplate = str_replace('%' . $property, $value, $uriTemplate);
  660. }
  661. if ($uriTemplate === '/*') {
  662. $uriTemplate = '*';
  663. }
  664. return $uriTemplate;
  665. }
  666. /**
  667. * Parses the given URI and breaks it down into pieces as an indexed array with elements
  668. * such as 'scheme', 'port', 'query'.
  669. *
  670. * @param string|array $uri URI to parse
  671. * @param boolean|array $base If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc.
  672. * @return array Parsed URI
  673. */
  674. protected function _parseUri($uri = null, $base = array()) {
  675. $uriBase = array(
  676. 'scheme' => array('http', 'https'),
  677. 'host' => null,
  678. 'port' => array(80, 443),
  679. 'user' => null,
  680. 'pass' => null,
  681. 'path' => '/',
  682. 'query' => null,
  683. 'fragment' => null
  684. );
  685. if (is_string($uri)) {
  686. $uri = parse_url($uri);
  687. }
  688. if (!is_array($uri) || empty($uri)) {
  689. return false;
  690. }
  691. if ($base === true) {
  692. $base = $uriBase;
  693. }
  694. if (isset($base['port'], $base['scheme']) && is_array($base['port']) && is_array($base['scheme'])) {
  695. if (isset($uri['scheme']) && !isset($uri['port'])) {
  696. $base['port'] = $base['port'][array_search($uri['scheme'], $base['scheme'])];
  697. } elseif (isset($uri['port']) && !isset($uri['scheme'])) {
  698. $base['scheme'] = $base['scheme'][array_search($uri['port'], $base['port'])];
  699. }
  700. }
  701. if (is_array($base) && !empty($base)) {
  702. $uri = array_merge($base, $uri);
  703. }
  704. if (isset($uri['scheme']) && is_array($uri['scheme'])) {
  705. $uri['scheme'] = array_shift($uri['scheme']);
  706. }
  707. if (isset($uri['port']) && is_array($uri['port'])) {
  708. $uri['port'] = array_shift($uri['port']);
  709. }
  710. if (array_key_exists('query', $uri)) {
  711. $uri['query'] = $this->_parseQuery($uri['query']);
  712. }
  713. if (!array_intersect_key($uriBase, $uri)) {
  714. return false;
  715. }
  716. return $uri;
  717. }
  718. /**
  719. * This function can be thought of as a reverse to PHP5's http_build_query(). It takes a given query string and turns it into an array and
  720. * supports nesting by using the php bracket syntax. So this means you can parse queries like:
  721. *
  722. * - ?key[subKey]=value
  723. * - ?key[]=value1&key[]=value2
  724. *
  725. * A leading '?' mark in $query is optional and does not effect the outcome of this function.
  726. * For the complete capabilities of this implementation take a look at HttpSocketTest::testparseQuery()
  727. *
  728. * @param string|array $query A query string to parse into an array or an array to return directly "as is"
  729. * @return array The $query parsed into a possibly multi-level array. If an empty $query is
  730. * given, an empty array is returned.
  731. */
  732. protected function _parseQuery($query) {
  733. if (is_array($query)) {
  734. return $query;
  735. }
  736. $parsedQuery = array();
  737. if (is_string($query) && !empty($query)) {
  738. $query = preg_replace('/^\?/', '', $query);
  739. $items = explode('&', $query);
  740. foreach ($items as $item) {
  741. if (strpos($item, '=') !== false) {
  742. list($key, $value) = explode('=', $item, 2);
  743. } else {
  744. $key = $item;
  745. $value = null;
  746. }
  747. $key = urldecode($key);
  748. $value = urldecode($value);
  749. if (preg_match_all('/\[([^\[\]]*)\]/iUs', $key, $matches)) {
  750. $subKeys = $matches[1];
  751. $rootKey = substr($key, 0, strpos($key, '['));
  752. if (!empty($rootKey)) {
  753. array_unshift($subKeys, $rootKey);
  754. }
  755. $queryNode =& $parsedQuery;
  756. foreach ($subKeys as $subKey) {
  757. if (!is_array($queryNode)) {
  758. $queryNode = array();
  759. }
  760. if ($subKey === '') {
  761. $queryNode[] = array();
  762. end($queryNode);
  763. $subKey = key($queryNode);
  764. }
  765. $queryNode =& $queryNode[$subKey];
  766. }
  767. $queryNode = $value;
  768. continue;
  769. }
  770. if (!isset($parsedQuery[$key])) {
  771. $parsedQuery[$key] = $value;
  772. } else {
  773. $parsedQuery[$key] = (array)$parsedQuery[$key];
  774. $parsedQuery[$key][] = $value;
  775. }
  776. }
  777. }
  778. return $parsedQuery;
  779. }
  780. /**
  781. * Builds a request line according to HTTP/1.1 specs. Activate quirks mode to work outside specs.
  782. *
  783. * @param array $request Needs to contain a 'uri' key. Should also contain a 'method' key, otherwise defaults to GET.
  784. * @param string $versionToken The version token to use, defaults to HTTP/1.1
  785. * @return string Request line
  786. * @throws SocketException
  787. */
  788. protected function _buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') {
  789. $asteriskMethods = array('OPTIONS');
  790. if (is_string($request)) {
  791. $isValid = preg_match("/(.+) (.+) (.+)\r\n/U", $request, $match);
  792. if (!$this->quirksMode && (!$isValid || ($match[2] === '*' && !in_array($match[3], $asteriskMethods)))) {
  793. throw new SocketException(__d('cake_dev', 'HttpSocket::_buildRequestLine - Passed an invalid request line string. Activate quirks mode to do this.'));
  794. }
  795. return $request;
  796. } elseif (!is_array($request)) {
  797. return false;
  798. } elseif (!array_key_exists('uri', $request)) {
  799. return false;
  800. }
  801. $request['uri'] = $this->_parseUri($request['uri']);
  802. $request = array_merge(array('method' => 'GET'), $request);
  803. if (!empty($this->_proxy['host'])) {
  804. $request['uri'] = $this->_buildUri($request['uri'], '%scheme://%host:%port/%path?%query');
  805. } else {
  806. $request['uri'] = $this->_buildUri($request['uri'], '/%path?%query');
  807. }
  808. if (!$this->quirksMode && $request['uri'] === '*' && !in_array($request['method'], $asteriskMethods)) {
  809. throw new SocketException(__d('cake_dev', 'HttpSocket::_buildRequestLine - The "*" asterisk character is only allowed for the following methods: %s. Activate quirks mode to work outside of HTTP/1.1 specs.', implode(',', $asteriskMethods)));
  810. }
  811. return $request['method'] . ' ' . $request['uri'] . ' ' . $versionToken . "\r\n";
  812. }
  813. /**
  814. * Builds the header.
  815. *
  816. * @param array $header Header to build
  817. * @param string $mode
  818. * @return string Header built from array
  819. */
  820. protected function _buildHeader($header, $mode = 'standard') {
  821. if (is_string($header)) {
  822. return $header;
  823. } elseif (!is_array($header)) {
  824. return false;
  825. }
  826. $fieldsInHeader = array();
  827. foreach ($header as $key => $value) {
  828. $lowKey = strtolower($key);
  829. if (array_key_exists($lowKey, $fieldsInHeader)) {
  830. $header[$fieldsInHeader[$lowKey]] = $value;
  831. unset($header[$key]);
  832. } else {
  833. $fieldsInHeader[$lowKey] = $key;
  834. }
  835. }
  836. $returnHeader = '';
  837. foreach ($header as $field => $contents) {
  838. if (is_array($contents) && $mode === 'standard') {
  839. $contents = implode(',', $contents);
  840. }
  841. foreach ((array)$contents as $content) {
  842. $contents = preg_replace("/\r\n(?![\t ])/", "\r\n ", $content);
  843. $field = $this->_escapeToken($field);
  844. $returnHeader .= $field . ': ' . $contents . "\r\n";
  845. }
  846. }
  847. return $returnHeader;
  848. }
  849. /**
  850. * Builds cookie headers for a request.
  851. *
  852. * Cookies can either be in the format returned in responses, or
  853. * a simple key => value pair.
  854. *
  855. * @param array $cookies Array of cookies to send with the request.
  856. * @return string Cookie header string to be sent with the request.
  857. */
  858. public function buildCookies($cookies) {
  859. $header = array();
  860. foreach ($cookies as $name => $cookie) {
  861. if (is_array($cookie)) {
  862. $value = $this->_escapeToken($cookie['value'], array(';'));
  863. } else {
  864. $value = $this->_escapeToken($cookie, array(';'));
  865. }
  866. $header[] = $name . '=' . $value;
  867. }
  868. return $this->_buildHeader(array('Cookie' => implode('; ', $header)), 'pragmatic');
  869. }
  870. /**
  871. * Escapes a given $token according to RFC 2616 (HTTP 1.1 specs)
  872. *
  873. * @param string $token Token to escape
  874. * @param array $chars
  875. * @return string Escaped token
  876. */
  877. protected function _escapeToken($token, $chars = null) {
  878. $regex = '/([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])/';
  879. $token = preg_replace($regex, '"\\1"', $token);
  880. return $token;
  881. }
  882. /**
  883. * Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
  884. *
  885. * @param boolean $hex true to get them as HEX values, false otherwise
  886. * @param array $chars
  887. * @return array Escape chars
  888. */
  889. protected function _tokenEscapeChars($hex = true, $chars = null) {
  890. if (!empty($chars)) {
  891. $escape = $chars;
  892. } else {
  893. $escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
  894. for ($i = 0; $i <= 31; $i++) {
  895. $escape[] = chr($i);
  896. }
  897. $escape[] = chr(127);
  898. }
  899. if (!$hex) {
  900. return $escape;
  901. }
  902. foreach ($escape as $key => $char) {
  903. $escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
  904. }
  905. return $escape;
  906. }
  907. /**
  908. * Resets the state of this HttpSocket instance to it's initial state (before Object::__construct got executed) or does
  909. * the same thing partially for the request and the response property only.
  910. *
  911. * @param boolean $full If set to false only HttpSocket::response and HttpSocket::request are reseted
  912. * @return boolean True on success
  913. */
  914. public function reset($full = true) {
  915. static $initalState = array();
  916. if (empty($initalState)) {
  917. $initalState = get_class_vars(__CLASS__);
  918. }
  919. if (!$full) {
  920. $this->request = $initalState['request'];
  921. $this->response = $initalState['response'];
  922. return true;
  923. }
  924. parent::reset($initalState);
  925. return true;
  926. }
  927. }