PageRenderTime 44ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Network/Http/HttpSocket.php

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