HttpSocket.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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. } 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 a 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 a 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. * @param array $cookies Array of cookies to send with the request.
  853. * @return string Cookie header string to be sent with the request.
  854. */
  855. public function buildCookies($cookies) {
  856. $header = array();
  857. foreach ($cookies as $name => $cookie) {
  858. $header[] = $name . '=' . $this->_escapeToken($cookie['value'], array(';'));
  859. }
  860. return $this->_buildHeader(array('Cookie' => implode('; ', $header)), 'pragmatic');
  861. }
  862. /**
  863. * Escapes a given $token according to RFC 2616 (HTTP 1.1 specs)
  864. *
  865. * @param string $token Token to escape
  866. * @param array $chars
  867. * @return string Escaped token
  868. */
  869. protected function _escapeToken($token, $chars = null) {
  870. $regex = '/([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])/';
  871. $token = preg_replace($regex, '"\\1"', $token);
  872. return $token;
  873. }
  874. /**
  875. * Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
  876. *
  877. * @param boolean $hex true to get them as HEX values, false otherwise
  878. * @param array $chars
  879. * @return array Escape chars
  880. */
  881. protected function _tokenEscapeChars($hex = true, $chars = null) {
  882. if (!empty($chars)) {
  883. $escape = $chars;
  884. } else {
  885. $escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
  886. for ($i = 0; $i <= 31; $i++) {
  887. $escape[] = chr($i);
  888. }
  889. $escape[] = chr(127);
  890. }
  891. if (!$hex) {
  892. return $escape;
  893. }
  894. foreach ($escape as $key => $char) {
  895. $escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
  896. }
  897. return $escape;
  898. }
  899. /**
  900. * Resets the state of this HttpSocket instance to it's initial state (before Object::__construct got executed) or does
  901. * the same thing partially for the request and the response property only.
  902. *
  903. * @param boolean $full If set to false only HttpSocket::response and HttpSocket::request are reseted
  904. * @return boolean True on success
  905. */
  906. public function reset($full = true) {
  907. static $initalState = array();
  908. if (empty($initalState)) {
  909. $initalState = get_class_vars(__CLASS__);
  910. }
  911. if (!$full) {
  912. $this->request = $initalState['request'];
  913. $this->response = $initalState['response'];
  914. return true;
  915. }
  916. parent::reset($initalState);
  917. return true;
  918. }
  919. }