HttpSocket.php 30 KB

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