PageRenderTime 56ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Network/Http/HttpSocket.php

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