PageRenderTime 72ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

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

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