HttpSocket.php 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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 a 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. }
  305. $this->_setAuth();
  306. $this->request['auth'] = $this->_auth;
  307. if (is_array($this->request['body'])) {
  308. $this->request['body'] = http_build_query($this->request['body'], '', '&');
  309. }
  310. if (!empty($this->request['body']) && !isset($this->request['header']['Content-Type'])) {
  311. $this->request['header']['Content-Type'] = 'application/x-www-form-urlencoded';
  312. }
  313. if (!empty($this->request['body']) && !isset($this->request['header']['Content-Length'])) {
  314. $this->request['header']['Content-Length'] = strlen($this->request['body']);
  315. }
  316. $connectionType = null;
  317. if (isset($this->request['header']['Connection'])) {
  318. $connectionType = $this->request['header']['Connection'];
  319. }
  320. $this->request['header'] = $this->_buildHeader($this->request['header']) . $cookies;
  321. if (empty($this->request['line'])) {
  322. $this->request['line'] = $this->_buildRequestLine($this->request);
  323. }
  324. if ($this->quirksMode === false && $this->request['line'] === false) {
  325. return false;
  326. }
  327. $this->_configContext($this->request['uri']['host']);
  328. $this->request['raw'] = '';
  329. if ($this->request['line'] !== false) {
  330. $this->request['raw'] = $this->request['line'];
  331. }
  332. if ($this->request['header'] !== false) {
  333. $this->request['raw'] .= $this->request['header'];
  334. }
  335. $this->request['raw'] .= "\r\n";
  336. $this->request['raw'] .= $this->request['body'];
  337. $this->write($this->request['raw']);
  338. $response = null;
  339. $inHeader = true;
  340. while ($data = $this->read()) {
  341. if ($this->_contentResource) {
  342. if ($inHeader) {
  343. $response .= $data;
  344. $pos = strpos($response, "\r\n\r\n");
  345. if ($pos !== false) {
  346. $pos += 4;
  347. $data = substr($response, $pos);
  348. fwrite($this->_contentResource, $data);
  349. $response = substr($response, 0, $pos);
  350. $inHeader = false;
  351. }
  352. } else {
  353. fwrite($this->_contentResource, $data);
  354. fflush($this->_contentResource);
  355. }
  356. } else {
  357. $response .= $data;
  358. }
  359. }
  360. if ($connectionType === 'close') {
  361. $this->disconnect();
  362. }
  363. list($plugin, $responseClass) = pluginSplit($this->responseClass, true);
  364. App::uses($responseClass, $plugin . 'Network/Http');
  365. if (!class_exists($responseClass)) {
  366. throw new SocketException(__d('cake_dev', 'Class %s not found.', $this->responseClass));
  367. }
  368. $this->response = new $responseClass($response);
  369. if (!empty($this->response->cookies)) {
  370. if (!isset($this->config['request']['cookies'][$Host])) {
  371. $this->config['request']['cookies'][$Host] = array();
  372. }
  373. $this->config['request']['cookies'][$Host] = array_merge($this->config['request']['cookies'][$Host], $this->response->cookies);
  374. }
  375. if ($this->request['redirect'] && $this->response->isRedirect()) {
  376. $request['uri'] = trim(urldecode($this->response->getHeader('Location')), '=');
  377. $request['redirect'] = is_int($this->request['redirect']) ? $this->request['redirect'] - 1 : $this->request['redirect'];
  378. $this->response = $this->request($request);
  379. }
  380. return $this->response;
  381. }
  382. /**
  383. * Issues a GET request to the specified URI, query, and request.
  384. *
  385. * Using a string uri and an array of query string parameters:
  386. *
  387. * `$response = $http->get('http://google.com/search', array('q' => 'cakephp', 'client' => 'safari'));`
  388. *
  389. * Would do a GET request to `http://google.com/search?q=cakephp&client=safari`
  390. *
  391. * You could express the same thing using a uri array and query string parameters:
  392. *
  393. * {{{
  394. * $response = $http->get(
  395. * array('host' => 'google.com', 'path' => '/search'),
  396. * array('q' => 'cakephp', 'client' => 'safari')
  397. * );
  398. * }}}
  399. *
  400. * @param string|array $uri URI to request. Either a string uri, or a uri array, see HttpSocket::_parseUri()
  401. * @param array $query Querystring parameters to append to URI
  402. * @param array $request An indexed array with indexes such as 'method' or uri
  403. * @return mixed Result of request, either false on failure or the response to the request.
  404. */
  405. public function get($uri = null, $query = array(), $request = array()) {
  406. if (!empty($query)) {
  407. $uri = $this->_parseUri($uri, $this->config['request']['uri']);
  408. if (isset($uri['query'])) {
  409. $uri['query'] = array_merge($uri['query'], $query);
  410. } else {
  411. $uri['query'] = $query;
  412. }
  413. $uri = $this->_buildUri($uri);
  414. }
  415. $request = Hash::merge(array('method' => 'GET', 'uri' => $uri), $request);
  416. return $this->request($request);
  417. }
  418. /**
  419. * Issues a POST request to the specified URI, query, and request.
  420. *
  421. * `post()` can be used to post simple data arrays to a url:
  422. *
  423. * {{{
  424. * $response = $http->post('http://example.com', array(
  425. * 'username' => 'batman',
  426. * 'password' => 'bruce_w4yne'
  427. * ));
  428. * }}}
  429. *
  430. * @param string|array $uri URI to request. See HttpSocket::_parseUri()
  431. * @param array $data Array of POST data keys and values.
  432. * @param array $request An indexed array with indexes such as 'method' or uri
  433. * @return mixed Result of request, either false on failure or the response to the request.
  434. */
  435. public function post($uri = null, $data = array(), $request = array()) {
  436. $request = Hash::merge(array('method' => 'POST', 'uri' => $uri, 'body' => $data), $request);
  437. return $this->request($request);
  438. }
  439. /**
  440. * Issues a PUT request to the specified URI, query, and request.
  441. *
  442. * @param string|array $uri URI to request, See HttpSocket::_parseUri()
  443. * @param array $data Array of PUT data keys and values.
  444. * @param array $request An indexed array with indexes such as 'method' or uri
  445. * @return mixed Result of request
  446. */
  447. public function put($uri = null, $data = array(), $request = array()) {
  448. $request = Hash::merge(array('method' => 'PUT', 'uri' => $uri, 'body' => $data), $request);
  449. return $this->request($request);
  450. }
  451. /**
  452. * Issues a DELETE request to the specified URI, query, and request.
  453. *
  454. * @param string|array $uri URI to request (see {@link _parseUri()})
  455. * @param array $data Query to append to URI
  456. * @param array $request An indexed array with indexes such as 'method' or uri
  457. * @return mixed Result of request
  458. */
  459. public function delete($uri = null, $data = array(), $request = array()) {
  460. $request = Hash::merge(array('method' => 'DELETE', 'uri' => $uri, 'body' => $data), $request);
  461. return $this->request($request);
  462. }
  463. /**
  464. * Normalizes urls into a $uriTemplate. If no template is provided
  465. * a default one will be used. Will generate the url using the
  466. * current config information.
  467. *
  468. * ### Usage:
  469. *
  470. * After configuring part of the request parameters, you can use url() to generate
  471. * urls.
  472. *
  473. * {{{
  474. * $http = new HttpSocket('http://www.cakephp.org');
  475. * $url = $http->url('/search?q=bar');
  476. * }}}
  477. *
  478. * Would return `http://www.cakephp.org/search?q=bar`
  479. *
  480. * url() can also be used with custom templates:
  481. *
  482. * `$url = $http->url('http://www.cakephp/search?q=socket', '/%path?%query');`
  483. *
  484. * Would return `/search?q=socket`.
  485. *
  486. * @param string|array Either a string or array of url options to create a url with.
  487. * @param string $uriTemplate A template string to use for url formatting.
  488. * @return mixed Either false on failure or a string containing the composed url.
  489. */
  490. public function url($url = null, $uriTemplate = null) {
  491. if (is_null($url)) {
  492. $url = '/';
  493. }
  494. if (is_string($url)) {
  495. $scheme = $this->config['request']['uri']['scheme'];
  496. if (is_array($scheme)) {
  497. $scheme = $scheme[0];
  498. }
  499. $port = $this->config['request']['uri']['port'];
  500. if (is_array($port)) {
  501. $port = $port[0];
  502. }
  503. if ($url{0} === '/') {
  504. $url = $this->config['request']['uri']['host'] . ':' . $port . $url;
  505. }
  506. if (!preg_match('/^.+:\/\/|\*|^\//', $url)) {
  507. $url = $scheme . '://' . $url;
  508. }
  509. } elseif (!is_array($url) && !empty($url)) {
  510. return false;
  511. }
  512. $base = array_merge($this->config['request']['uri'], array('scheme' => array('http', 'https'), 'port' => array(80, 443)));
  513. $url = $this->_parseUri($url, $base);
  514. if (empty($url)) {
  515. $url = $this->config['request']['uri'];
  516. }
  517. if (!empty($uriTemplate)) {
  518. return $this->_buildUri($url, $uriTemplate);
  519. }
  520. return $this->_buildUri($url);
  521. }
  522. /**
  523. * Set authentication in request
  524. *
  525. * @return void
  526. * @throws SocketException
  527. */
  528. protected function _setAuth() {
  529. if (empty($this->_auth)) {
  530. return;
  531. }
  532. $method = key($this->_auth);
  533. list($plugin, $authClass) = pluginSplit($method, true);
  534. $authClass = Inflector::camelize($authClass) . 'Authentication';
  535. App::uses($authClass, $plugin . 'Network/Http');
  536. if (!class_exists($authClass)) {
  537. throw new SocketException(__d('cake_dev', 'Unknown authentication method.'));
  538. }
  539. if (!method_exists($authClass, 'authentication')) {
  540. throw new SocketException(sprintf(__d('cake_dev', 'The %s do not support authentication.'), $authClass));
  541. }
  542. call_user_func_array("$authClass::authentication", array($this, &$this->_auth[$method]));
  543. }
  544. /**
  545. * Set the proxy configuration and authentication
  546. *
  547. * @return void
  548. * @throws SocketException
  549. */
  550. protected function _setProxy() {
  551. if (empty($this->_proxy) || !isset($this->_proxy['host'], $this->_proxy['port'])) {
  552. return;
  553. }
  554. $this->config['host'] = $this->_proxy['host'];
  555. $this->config['port'] = $this->_proxy['port'];
  556. if (empty($this->_proxy['method']) || !isset($this->_proxy['user'], $this->_proxy['pass'])) {
  557. return;
  558. }
  559. list($plugin, $authClass) = pluginSplit($this->_proxy['method'], true);
  560. $authClass = Inflector::camelize($authClass) . 'Authentication';
  561. App::uses($authClass, $plugin . 'Network/Http');
  562. if (!class_exists($authClass)) {
  563. throw new SocketException(__d('cake_dev', 'Unknown authentication method for proxy.'));
  564. }
  565. if (!method_exists($authClass, 'proxyAuthentication')) {
  566. throw new SocketException(sprintf(__d('cake_dev', 'The %s do not support proxy authentication.'), $authClass));
  567. }
  568. call_user_func_array("$authClass::proxyAuthentication", array($this, &$this->_proxy));
  569. }
  570. /**
  571. * Parses and sets the specified URI into current request configuration.
  572. *
  573. * @param string|array $uri URI, See HttpSocket::_parseUri()
  574. * @return boolean If uri has merged in config
  575. */
  576. protected function _configUri($uri = null) {
  577. if (empty($uri)) {
  578. return false;
  579. }
  580. if (is_array($uri)) {
  581. $uri = $this->_parseUri($uri);
  582. } else {
  583. $uri = $this->_parseUri($uri, true);
  584. }
  585. if (!isset($uri['host'])) {
  586. return false;
  587. }
  588. $config = array(
  589. 'request' => array(
  590. 'uri' => array_intersect_key($uri, $this->config['request']['uri'])
  591. )
  592. );
  593. $this->config = Hash::merge($this->config, $config);
  594. $this->config = Hash::merge($this->config, array_intersect_key($this->config['request']['uri'], $this->config));
  595. return true;
  596. }
  597. /**
  598. * Configure the socket's context. Adds in configuration
  599. * that can not be declared in the class definition.
  600. *
  601. * @param string $host The host you're connecting to.
  602. * @return void
  603. */
  604. protected function _configContext($host) {
  605. foreach ($this->config as $key => $value) {
  606. if (substr($key, 0, 4) !== 'ssl_') {
  607. continue;
  608. }
  609. $contextKey = substr($key, 4);
  610. if (empty($this->config['context']['ssl'][$contextKey])) {
  611. $this->config['context']['ssl'][$contextKey] = $value;
  612. }
  613. unset($this->config[$key]);
  614. }
  615. if (empty($this->_context['ssl']['cafile'])) {
  616. $this->config['context']['ssl']['cafile'] = CAKE . 'Config' . DS . 'cacert.pem';
  617. }
  618. if (!empty($this->config['context']['ssl']['verify_host'])) {
  619. $this->config['context']['ssl']['CN_match'] = $host;
  620. unset($this->config['context']['ssl']['verify_host']);
  621. }
  622. }
  623. /**
  624. * Takes a $uri array and turns it into a fully qualified URL string
  625. *
  626. * @param string|array $uri Either A $uri array, or a request string. Will use $this->config if left empty.
  627. * @param string $uriTemplate The Uri template/format to use.
  628. * @return mixed A fully qualified URL formatted according to $uriTemplate, or false on failure
  629. */
  630. protected function _buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') {
  631. if (is_string($uri)) {
  632. $uri = array('host' => $uri);
  633. }
  634. $uri = $this->_parseUri($uri, true);
  635. if (!is_array($uri) || empty($uri)) {
  636. return false;
  637. }
  638. $uri['path'] = preg_replace('/^\//', null, $uri['path']);
  639. $uri['query'] = http_build_query($uri['query'], '', '&');
  640. $uri['query'] = rtrim($uri['query'], '=');
  641. $stripIfEmpty = array(
  642. 'query' => '?%query',
  643. 'fragment' => '#%fragment',
  644. 'user' => '%user:%pass@',
  645. 'host' => '%host:%port/'
  646. );
  647. foreach ($stripIfEmpty as $key => $strip) {
  648. if (empty($uri[$key])) {
  649. $uriTemplate = str_replace($strip, null, $uriTemplate);
  650. }
  651. }
  652. $defaultPorts = array('http' => 80, 'https' => 443);
  653. if (array_key_exists($uri['scheme'], $defaultPorts) && $defaultPorts[$uri['scheme']] == $uri['port']) {
  654. $uriTemplate = str_replace(':%port', null, $uriTemplate);
  655. }
  656. foreach ($uri as $property => $value) {
  657. $uriTemplate = str_replace('%' . $property, $value, $uriTemplate);
  658. }
  659. if ($uriTemplate === '/*') {
  660. $uriTemplate = '*';
  661. }
  662. return $uriTemplate;
  663. }
  664. /**
  665. * Parses the given URI and breaks it down into pieces as an indexed array with elements
  666. * such as 'scheme', 'port', 'query'.
  667. *
  668. * @param string|array $uri URI to parse
  669. * @param boolean|array $base If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc.
  670. * @return array Parsed URI
  671. */
  672. protected function _parseUri($uri = null, $base = array()) {
  673. $uriBase = array(
  674. 'scheme' => array('http', 'https'),
  675. 'host' => null,
  676. 'port' => array(80, 443),
  677. 'user' => null,
  678. 'pass' => null,
  679. 'path' => '/',
  680. 'query' => null,
  681. 'fragment' => null
  682. );
  683. if (is_string($uri)) {
  684. $uri = parse_url($uri);
  685. }
  686. if (!is_array($uri) || empty($uri)) {
  687. return false;
  688. }
  689. if ($base === true) {
  690. $base = $uriBase;
  691. }
  692. if (isset($base['port'], $base['scheme']) && is_array($base['port']) && is_array($base['scheme'])) {
  693. if (isset($uri['scheme']) && !isset($uri['port'])) {
  694. $base['port'] = $base['port'][array_search($uri['scheme'], $base['scheme'])];
  695. } elseif (isset($uri['port']) && !isset($uri['scheme'])) {
  696. $base['scheme'] = $base['scheme'][array_search($uri['port'], $base['port'])];
  697. }
  698. }
  699. if (is_array($base) && !empty($base)) {
  700. $uri = array_merge($base, $uri);
  701. }
  702. if (isset($uri['scheme']) && is_array($uri['scheme'])) {
  703. $uri['scheme'] = array_shift($uri['scheme']);
  704. }
  705. if (isset($uri['port']) && is_array($uri['port'])) {
  706. $uri['port'] = array_shift($uri['port']);
  707. }
  708. if (array_key_exists('query', $uri)) {
  709. $uri['query'] = $this->_parseQuery($uri['query']);
  710. }
  711. if (!array_intersect_key($uriBase, $uri)) {
  712. return false;
  713. }
  714. return $uri;
  715. }
  716. /**
  717. * 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
  718. * supports nesting by using the php bracket syntax. So this means you can parse queries like:
  719. *
  720. * - ?key[subKey]=value
  721. * - ?key[]=value1&key[]=value2
  722. *
  723. * A leading '?' mark in $query is optional and does not effect the outcome of this function.
  724. * For the complete capabilities of this implementation take a look at HttpSocketTest::testparseQuery()
  725. *
  726. * @param string|array $query A query string to parse into an array or an array to return directly "as is"
  727. * @return array The $query parsed into a possibly multi-level array. If an empty $query is
  728. * given, an empty array is returned.
  729. */
  730. protected function _parseQuery($query) {
  731. if (is_array($query)) {
  732. return $query;
  733. }
  734. $parsedQuery = array();
  735. if (is_string($query) && !empty($query)) {
  736. $query = preg_replace('/^\?/', '', $query);
  737. $items = explode('&', $query);
  738. foreach ($items as $item) {
  739. if (strpos($item, '=') !== false) {
  740. list($key, $value) = explode('=', $item, 2);
  741. } else {
  742. $key = $item;
  743. $value = null;
  744. }
  745. $key = urldecode($key);
  746. $value = urldecode($value);
  747. if (preg_match_all('/\[([^\[\]]*)\]/iUs', $key, $matches)) {
  748. $subKeys = $matches[1];
  749. $rootKey = substr($key, 0, strpos($key, '['));
  750. if (!empty($rootKey)) {
  751. array_unshift($subKeys, $rootKey);
  752. }
  753. $queryNode =& $parsedQuery;
  754. foreach ($subKeys as $subKey) {
  755. if (!is_array($queryNode)) {
  756. $queryNode = array();
  757. }
  758. if ($subKey === '') {
  759. $queryNode[] = array();
  760. end($queryNode);
  761. $subKey = key($queryNode);
  762. }
  763. $queryNode =& $queryNode[$subKey];
  764. }
  765. $queryNode = $value;
  766. continue;
  767. }
  768. if (!isset($parsedQuery[$key])) {
  769. $parsedQuery[$key] = $value;
  770. } else {
  771. $parsedQuery[$key] = (array)$parsedQuery[$key];
  772. $parsedQuery[$key][] = $value;
  773. }
  774. }
  775. }
  776. return $parsedQuery;
  777. }
  778. /**
  779. * Builds a request line according to HTTP/1.1 specs. Activate quirks mode to work outside specs.
  780. *
  781. * @param array $request Needs to contain a 'uri' key. Should also contain a 'method' key, otherwise defaults to GET.
  782. * @param string $versionToken The version token to use, defaults to HTTP/1.1
  783. * @return string Request line
  784. * @throws SocketException
  785. */
  786. protected function _buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') {
  787. $asteriskMethods = array('OPTIONS');
  788. if (is_string($request)) {
  789. $isValid = preg_match("/(.+) (.+) (.+)\r\n/U", $request, $match);
  790. if (!$this->quirksMode && (!$isValid || ($match[2] === '*' && !in_array($match[3], $asteriskMethods)))) {
  791. throw new SocketException(__d('cake_dev', 'HttpSocket::_buildRequestLine - Passed an invalid request line string. Activate quirks mode to do this.'));
  792. }
  793. return $request;
  794. } elseif (!is_array($request)) {
  795. return false;
  796. } elseif (!array_key_exists('uri', $request)) {
  797. return false;
  798. }
  799. $request['uri'] = $this->_parseUri($request['uri']);
  800. $request = array_merge(array('method' => 'GET'), $request);
  801. if (!empty($this->_proxy['host'])) {
  802. $request['uri'] = $this->_buildUri($request['uri'], '%scheme://%host:%port/%path?%query');
  803. } else {
  804. $request['uri'] = $this->_buildUri($request['uri'], '/%path?%query');
  805. }
  806. if (!$this->quirksMode && $request['uri'] === '*' && !in_array($request['method'], $asteriskMethods)) {
  807. 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)));
  808. }
  809. return $request['method'] . ' ' . $request['uri'] . ' ' . $versionToken . "\r\n";
  810. }
  811. /**
  812. * Builds the header.
  813. *
  814. * @param array $header Header to build
  815. * @param string $mode
  816. * @return string Header built from array
  817. */
  818. protected function _buildHeader($header, $mode = 'standard') {
  819. if (is_string($header)) {
  820. return $header;
  821. } elseif (!is_array($header)) {
  822. return false;
  823. }
  824. $fieldsInHeader = array();
  825. foreach ($header as $key => $value) {
  826. $lowKey = strtolower($key);
  827. if (array_key_exists($lowKey, $fieldsInHeader)) {
  828. $header[$fieldsInHeader[$lowKey]] = $value;
  829. unset($header[$key]);
  830. } else {
  831. $fieldsInHeader[$lowKey] = $key;
  832. }
  833. }
  834. $returnHeader = '';
  835. foreach ($header as $field => $contents) {
  836. if (is_array($contents) && $mode === 'standard') {
  837. $contents = implode(',', $contents);
  838. }
  839. foreach ((array)$contents as $content) {
  840. $contents = preg_replace("/\r\n(?![\t ])/", "\r\n ", $content);
  841. $field = $this->_escapeToken($field);
  842. $returnHeader .= $field . ': ' . $contents . "\r\n";
  843. }
  844. }
  845. return $returnHeader;
  846. }
  847. /**
  848. * Builds cookie headers for a request.
  849. *
  850. * @param array $cookies Array of cookies to send with the request.
  851. * @return string Cookie header string to be sent with the request.
  852. */
  853. public function buildCookies($cookies) {
  854. $header = array();
  855. foreach ($cookies as $name => $cookie) {
  856. $header[] = $name . '=' . $this->_escapeToken($cookie['value'], array(';'));
  857. }
  858. return $this->_buildHeader(array('Cookie' => implode('; ', $header)), 'pragmatic');
  859. }
  860. /**
  861. * Escapes a given $token according to RFC 2616 (HTTP 1.1 specs)
  862. *
  863. * @param string $token Token to escape
  864. * @param array $chars
  865. * @return string Escaped token
  866. */
  867. protected function _escapeToken($token, $chars = null) {
  868. $regex = '/([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])/';
  869. $token = preg_replace($regex, '"\\1"', $token);
  870. return $token;
  871. }
  872. /**
  873. * Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
  874. *
  875. * @param boolean $hex true to get them as HEX values, false otherwise
  876. * @param array $chars
  877. * @return array Escape chars
  878. */
  879. protected function _tokenEscapeChars($hex = true, $chars = null) {
  880. if (!empty($chars)) {
  881. $escape = $chars;
  882. } else {
  883. $escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
  884. for ($i = 0; $i <= 31; $i++) {
  885. $escape[] = chr($i);
  886. }
  887. $escape[] = chr(127);
  888. }
  889. if (!$hex) {
  890. return $escape;
  891. }
  892. foreach ($escape as $key => $char) {
  893. $escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
  894. }
  895. return $escape;
  896. }
  897. /**
  898. * Resets the state of this HttpSocket instance to it's initial state (before Object::__construct got executed) or does
  899. * the same thing partially for the request and the response property only.
  900. *
  901. * @param boolean $full If set to false only HttpSocket::response and HttpSocket::request are reseted
  902. * @return boolean True on success
  903. */
  904. public function reset($full = true) {
  905. static $initalState = array();
  906. if (empty($initalState)) {
  907. $initalState = get_class_vars(__CLASS__);
  908. }
  909. if (!$full) {
  910. $this->request = $initalState['request'];
  911. $this->response = $initalState['response'];
  912. return true;
  913. }
  914. parent::reset($initalState);
  915. return true;
  916. }
  917. }