HttpSocket.php 31 KB

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