HttpSocket.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. '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' => 'http',
  92. 'host' => 'localhost',
  93. 'port' => 80
  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 mixed $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 = Set::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 mixed $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 mixed $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 mixed $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 mixed $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 = Set::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($this->responseClass, $plugin . 'Network/Http');
  359. if (!class_exists($responseClass)) {
  360. throw new SocketException(__d('cake_dev', 'Class %s not found.', $this->responseClass));
  361. }
  362. $responseClass = $this->responseClass;
  363. $this->response = new $responseClass($response);
  364. if (!empty($this->response->cookies)) {
  365. if (!isset($this->config['request']['cookies'][$Host])) {
  366. $this->config['request']['cookies'][$Host] = array();
  367. }
  368. $this->config['request']['cookies'][$Host] = array_merge($this->config['request']['cookies'][$Host], $this->response->cookies);
  369. }
  370. if($this->request['redirect'] && $this->response->isRedirect()) {
  371. $request['uri'] = $this->response->getHeader('Location');
  372. $request['redirect'] = is_int($this->request['redirect']) ? $this->request['redirect'] - 1 : $this->request['redirect'];
  373. $this->response = $this->request($request);
  374. }
  375. return $this->response;
  376. }
  377. /**
  378. * Issues a GET request to the specified URI, query, and request.
  379. *
  380. * Using a string uri and an array of query string parameters:
  381. *
  382. * `$response = $http->get('http://google.com/search', array('q' => 'cakephp', 'client' => 'safari'));`
  383. *
  384. * Would do a GET request to `http://google.com/search?q=cakephp&client=safari`
  385. *
  386. * You could express the same thing using a uri array and query string parameters:
  387. *
  388. * {{{
  389. * $response = $http->get(
  390. * array('host' => 'google.com', 'path' => '/search'),
  391. * array('q' => 'cakephp', 'client' => 'safari')
  392. * );
  393. * }}}
  394. *
  395. * @param mixed $uri URI to request. Either a string uri, or a uri array, see HttpSocket::_parseUri()
  396. * @param array $query Querystring parameters to append to URI
  397. * @param array $request An indexed array with indexes such as 'method' or uri
  398. * @return mixed Result of request, either false on failure or the response to the request.
  399. */
  400. public function get($uri = null, $query = array(), $request = array()) {
  401. if (!empty($query)) {
  402. $uri = $this->_parseUri($uri, $this->config['request']['uri']);
  403. if (isset($uri['query'])) {
  404. $uri['query'] = array_merge($uri['query'], $query);
  405. } else {
  406. $uri['query'] = $query;
  407. }
  408. $uri = $this->_buildUri($uri);
  409. }
  410. $request = Set::merge(array('method' => 'GET', 'uri' => $uri), $request);
  411. return $this->request($request);
  412. }
  413. /**
  414. * Issues a POST request to the specified URI, query, and request.
  415. *
  416. * `post()` can be used to post simple data arrays to a url:
  417. *
  418. * {{{
  419. * $response = $http->post('http://example.com', array(
  420. * 'username' => 'batman',
  421. * 'password' => 'bruce_w4yne'
  422. * ));
  423. * }}}
  424. *
  425. * @param mixed $uri URI to request. See HttpSocket::_parseUri()
  426. * @param array $data Array of POST data keys and values.
  427. * @param array $request An indexed array with indexes such as 'method' or uri
  428. * @return mixed Result of request, either false on failure or the response to the request.
  429. */
  430. public function post($uri = null, $data = array(), $request = array()) {
  431. $request = Set::merge(array('method' => 'POST', 'uri' => $uri, 'body' => $data), $request);
  432. return $this->request($request);
  433. }
  434. /**
  435. * Issues a PUT request to the specified URI, query, and request.
  436. *
  437. * @param mixed $uri URI to request, See HttpSocket::_parseUri()
  438. * @param array $data Array of PUT data keys and values.
  439. * @param array $request An indexed array with indexes such as 'method' or uri
  440. * @return mixed Result of request
  441. */
  442. public function put($uri = null, $data = array(), $request = array()) {
  443. $request = Set::merge(array('method' => 'PUT', 'uri' => $uri, 'body' => $data), $request);
  444. return $this->request($request);
  445. }
  446. /**
  447. * Issues a DELETE request to the specified URI, query, and request.
  448. *
  449. * @param mixed $uri URI to request (see {@link _parseUri()})
  450. * @param array $data Query to append to URI
  451. * @param array $request An indexed array with indexes such as 'method' or uri
  452. * @return mixed Result of request
  453. */
  454. public function delete($uri = null, $data = array(), $request = array()) {
  455. $request = Set::merge(array('method' => 'DELETE', 'uri' => $uri, 'body' => $data), $request);
  456. return $this->request($request);
  457. }
  458. /**
  459. * Normalizes urls into a $uriTemplate. If no template is provided
  460. * a default one will be used. Will generate the url using the
  461. * current config information.
  462. *
  463. * ### Usage:
  464. *
  465. * After configuring part of the request parameters, you can use url() to generate
  466. * urls.
  467. *
  468. * {{{
  469. * $http->configUri('http://www.cakephp.org');
  470. * $url = $http->url('/search?q=bar');
  471. * }}}
  472. *
  473. * Would return `http://www.cakephp.org/search?q=bar`
  474. *
  475. * url() can also be used with custom templates:
  476. *
  477. * `$url = $http->url('http://www.cakephp/search?q=socket', '/%path?%query');`
  478. *
  479. * Would return `/search?q=socket`.
  480. *
  481. * @param mixed $url Either a string or array of url options to create a url with.
  482. * @param string $uriTemplate A template string to use for url formatting.
  483. * @return mixed Either false on failure or a string containing the composed url.
  484. */
  485. public function url($url = null, $uriTemplate = null) {
  486. if (is_null($url)) {
  487. $url = '/';
  488. }
  489. if (is_string($url)) {
  490. if ($url{0} == '/') {
  491. $url = $this->config['request']['uri']['host'] . ':' . $this->config['request']['uri']['port'] . $url;
  492. }
  493. if (!preg_match('/^.+:\/\/|\*|^\//', $url)) {
  494. $url = $this->config['request']['uri']['scheme'] . '://' . $url;
  495. }
  496. } elseif (!is_array($url) && !empty($url)) {
  497. return false;
  498. }
  499. $base = array_merge($this->config['request']['uri'], array('scheme' => array('http', 'https'), 'port' => array(80, 443)));
  500. $url = $this->_parseUri($url, $base);
  501. if (empty($url)) {
  502. $url = $this->config['request']['uri'];
  503. }
  504. if (!empty($uriTemplate)) {
  505. return $this->_buildUri($url, $uriTemplate);
  506. }
  507. return $this->_buildUri($url);
  508. }
  509. /**
  510. * Set authentication in request
  511. *
  512. * @return void
  513. * @throws SocketException
  514. */
  515. protected function _setAuth() {
  516. if (empty($this->_auth)) {
  517. return;
  518. }
  519. $method = key($this->_auth);
  520. list($plugin, $authClass) = pluginSplit($method, true);
  521. $authClass = Inflector::camelize($authClass) . 'Authentication';
  522. App::uses($authClass, $plugin . 'Network/Http');
  523. if (!class_exists($authClass)) {
  524. throw new SocketException(__d('cake_dev', 'Unknown authentication method.'));
  525. }
  526. if (!method_exists($authClass, 'authentication')) {
  527. throw new SocketException(sprintf(__d('cake_dev', 'The %s do not support authentication.'), $authClass));
  528. }
  529. call_user_func_array("$authClass::authentication", array($this, &$this->_auth[$method]));
  530. }
  531. /**
  532. * Set the proxy configuration and authentication
  533. *
  534. * @return void
  535. * @throws SocketException
  536. */
  537. protected function _setProxy() {
  538. if (empty($this->_proxy) || !isset($this->_proxy['host'], $this->_proxy['port'])) {
  539. return;
  540. }
  541. $this->config['host'] = $this->_proxy['host'];
  542. $this->config['port'] = $this->_proxy['port'];
  543. if (empty($this->_proxy['method']) || !isset($this->_proxy['user'], $this->_proxy['pass'])) {
  544. return;
  545. }
  546. list($plugin, $authClass) = pluginSplit($this->_proxy['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 for proxy.'));
  551. }
  552. if (!method_exists($authClass, 'proxyAuthentication')) {
  553. throw new SocketException(sprintf(__d('cake_dev', 'The %s do not support proxy authentication.'), $authClass));
  554. }
  555. call_user_func_array("$authClass::proxyAuthentication", array($this, &$this->_proxy));
  556. }
  557. /**
  558. * Parses and sets the specified URI into current request configuration.
  559. *
  560. * @param mixed $uri URI, See HttpSocket::_parseUri()
  561. * @return boolean If uri has merged in config
  562. */
  563. protected function _configUri($uri = null) {
  564. if (empty($uri)) {
  565. return false;
  566. }
  567. if (is_array($uri)) {
  568. $uri = $this->_parseUri($uri);
  569. } else {
  570. $uri = $this->_parseUri($uri, true);
  571. }
  572. if (!isset($uri['host'])) {
  573. return false;
  574. }
  575. $config = array(
  576. 'request' => array(
  577. 'uri' => array_intersect_key($uri, $this->config['request']['uri'])
  578. )
  579. );
  580. $this->config = Set::merge($this->config, $config);
  581. $this->config = Set::merge($this->config, array_intersect_key($this->config['request']['uri'], $this->config));
  582. return true;
  583. }
  584. /**
  585. * Takes a $uri array and turns it into a fully qualified URL string
  586. *
  587. * @param mixed $uri Either A $uri array, or a request string. Will use $this->config if left empty.
  588. * @param string $uriTemplate The Uri template/format to use.
  589. * @return mixed A fully qualified URL formatted according to $uriTemplate, or false on failure
  590. */
  591. protected function _buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') {
  592. if (is_string($uri)) {
  593. $uri = array('host' => $uri);
  594. }
  595. $uri = $this->_parseUri($uri, true);
  596. if (!is_array($uri) || empty($uri)) {
  597. return false;
  598. }
  599. $uri['path'] = preg_replace('/^\//', null, $uri['path']);
  600. $uri['query'] = http_build_query($uri['query']);
  601. $uri['query'] = rtrim($uri['query'], '=');
  602. $stripIfEmpty = array(
  603. 'query' => '?%query',
  604. 'fragment' => '#%fragment',
  605. 'user' => '%user:%pass@',
  606. 'host' => '%host:%port/'
  607. );
  608. foreach ($stripIfEmpty as $key => $strip) {
  609. if (empty($uri[$key])) {
  610. $uriTemplate = str_replace($strip, null, $uriTemplate);
  611. }
  612. }
  613. $defaultPorts = array('http' => 80, 'https' => 443);
  614. if (array_key_exists($uri['scheme'], $defaultPorts) && $defaultPorts[$uri['scheme']] == $uri['port']) {
  615. $uriTemplate = str_replace(':%port', null, $uriTemplate);
  616. }
  617. foreach ($uri as $property => $value) {
  618. $uriTemplate = str_replace('%' . $property, $value, $uriTemplate);
  619. }
  620. if ($uriTemplate === '/*') {
  621. $uriTemplate = '*';
  622. }
  623. return $uriTemplate;
  624. }
  625. /**
  626. * Parses the given URI and breaks it down into pieces as an indexed array with elements
  627. * such as 'scheme', 'port', 'query'.
  628. *
  629. * @param string $uri URI to parse
  630. * @param mixed $base If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc.
  631. * @return array Parsed URI
  632. */
  633. protected function _parseUri($uri = null, $base = array()) {
  634. $uriBase = array(
  635. 'scheme' => array('http', 'https'),
  636. 'host' => null,
  637. 'port' => array(80, 443),
  638. 'user' => null,
  639. 'pass' => null,
  640. 'path' => '/',
  641. 'query' => null,
  642. 'fragment' => null
  643. );
  644. if (is_string($uri)) {
  645. $uri = parse_url($uri);
  646. }
  647. if (!is_array($uri) || empty($uri)) {
  648. return false;
  649. }
  650. if ($base === true) {
  651. $base = $uriBase;
  652. }
  653. if (isset($base['port'], $base['scheme']) && is_array($base['port']) && is_array($base['scheme'])) {
  654. if (isset($uri['scheme']) && !isset($uri['port'])) {
  655. $base['port'] = $base['port'][array_search($uri['scheme'], $base['scheme'])];
  656. } elseif (isset($uri['port']) && !isset($uri['scheme'])) {
  657. $base['scheme'] = $base['scheme'][array_search($uri['port'], $base['port'])];
  658. }
  659. }
  660. if (is_array($base) && !empty($base)) {
  661. $uri = array_merge($base, $uri);
  662. }
  663. if (isset($uri['scheme']) && is_array($uri['scheme'])) {
  664. $uri['scheme'] = array_shift($uri['scheme']);
  665. }
  666. if (isset($uri['port']) && is_array($uri['port'])) {
  667. $uri['port'] = array_shift($uri['port']);
  668. }
  669. if (array_key_exists('query', $uri)) {
  670. $uri['query'] = $this->_parseQuery($uri['query']);
  671. }
  672. if (!array_intersect_key($uriBase, $uri)) {
  673. return false;
  674. }
  675. return $uri;
  676. }
  677. /**
  678. * 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
  679. * supports nesting by using the php bracket syntax. So this means you can parse queries like:
  680. *
  681. * - ?key[subKey]=value
  682. * - ?key[]=value1&key[]=value2
  683. *
  684. * A leading '?' mark in $query is optional and does not effect the outcome of this function.
  685. * For the complete capabilities of this implementation take a look at HttpSocketTest::testparseQuery()
  686. *
  687. * @param mixed $query A query string to parse into an array or an array to return directly "as is"
  688. * @return array The $query parsed into a possibly multi-level array. If an empty $query is
  689. * given, an empty array is returned.
  690. */
  691. protected function _parseQuery($query) {
  692. if (is_array($query)) {
  693. return $query;
  694. }
  695. parse_str(ltrim($query, '?'), $parsedQuery);
  696. return $parsedQuery;
  697. }
  698. /**
  699. * Builds a request line according to HTTP/1.1 specs. Activate quirks mode to work outside specs.
  700. *
  701. * @param array $request Needs to contain a 'uri' key. Should also contain a 'method' key, otherwise defaults to GET.
  702. * @param string $versionToken The version token to use, defaults to HTTP/1.1
  703. * @return string Request line
  704. * @throws SocketException
  705. */
  706. protected function _buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') {
  707. $asteriskMethods = array('OPTIONS');
  708. if (is_string($request)) {
  709. $isValid = preg_match("/(.+) (.+) (.+)\r\n/U", $request, $match);
  710. if (!$this->quirksMode && (!$isValid || ($match[2] == '*' && !in_array($match[3], $asteriskMethods)))) {
  711. throw new SocketException(__d('cake_dev', 'HttpSocket::_buildRequestLine - Passed an invalid request line string. Activate quirks mode to do this.'));
  712. }
  713. return $request;
  714. } elseif (!is_array($request)) {
  715. return false;
  716. } elseif (!array_key_exists('uri', $request)) {
  717. return false;
  718. }
  719. $request['uri'] = $this->_parseUri($request['uri']);
  720. $request = array_merge(array('method' => 'GET'), $request);
  721. if (!empty($this->_proxy['host'])) {
  722. $request['uri'] = $this->_buildUri($request['uri'], '%scheme://%host:%port/%path?%query');
  723. } else {
  724. $request['uri'] = $this->_buildUri($request['uri'], '/%path?%query');
  725. }
  726. if (!$this->quirksMode && $request['uri'] === '*' && !in_array($request['method'], $asteriskMethods)) {
  727. 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)));
  728. }
  729. return $request['method'] . ' ' . $request['uri'] . ' ' . $versionToken . "\r\n";
  730. }
  731. /**
  732. * Builds the header.
  733. *
  734. * @param array $header Header to build
  735. * @param string $mode
  736. * @return string Header built from array
  737. */
  738. protected function _buildHeader($header, $mode = 'standard') {
  739. if (is_string($header)) {
  740. return $header;
  741. } elseif (!is_array($header)) {
  742. return false;
  743. }
  744. $fieldsInHeader = array();
  745. foreach ($header as $key => $value) {
  746. $lowKey = strtolower($key);
  747. if (array_key_exists($lowKey, $fieldsInHeader)) {
  748. $header[$fieldsInHeader[$lowKey]] = $value;
  749. unset($header[$key]);
  750. } else {
  751. $fieldsInHeader[$lowKey] = $key;
  752. }
  753. }
  754. $returnHeader = '';
  755. foreach ($header as $field => $contents) {
  756. if (is_array($contents) && $mode == 'standard') {
  757. $contents = implode(',', $contents);
  758. }
  759. foreach ((array)$contents as $content) {
  760. $contents = preg_replace("/\r\n(?![\t ])/", "\r\n ", $content);
  761. $field = $this->_escapeToken($field);
  762. $returnHeader .= $field . ': ' . $contents . "\r\n";
  763. }
  764. }
  765. return $returnHeader;
  766. }
  767. /**
  768. * Builds cookie headers for a request.
  769. *
  770. * @param array $cookies Array of cookies to send with the request.
  771. * @return string Cookie header string to be sent with the request.
  772. * @todo Refactor token escape mechanism to be configurable
  773. */
  774. public function buildCookies($cookies) {
  775. $header = array();
  776. foreach ($cookies as $name => $cookie) {
  777. $header[] = $name . '=' . $this->_escapeToken($cookie['value'], array(';'));
  778. }
  779. return $this->_buildHeader(array('Cookie' => implode('; ', $header)), 'pragmatic');
  780. }
  781. /**
  782. * Escapes a given $token according to RFC 2616 (HTTP 1.1 specs)
  783. *
  784. * @param string $token Token to escape
  785. * @param array $chars
  786. * @return string Escaped token
  787. * @todo Test $chars parameter
  788. */
  789. protected function _escapeToken($token, $chars = null) {
  790. $regex = '/([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])/';
  791. $token = preg_replace($regex, '"\\1"', $token);
  792. return $token;
  793. }
  794. /**
  795. * Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
  796. *
  797. * @param boolean $hex true to get them as HEX values, false otherwise
  798. * @param array $chars
  799. * @return array Escape chars
  800. * @todo Test $chars parameter
  801. */
  802. protected function _tokenEscapeChars($hex = true, $chars = null) {
  803. if (!empty($chars)) {
  804. $escape = $chars;
  805. } else {
  806. $escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
  807. for ($i = 0; $i <= 31; $i++) {
  808. $escape[] = chr($i);
  809. }
  810. $escape[] = chr(127);
  811. }
  812. if ($hex == false) {
  813. return $escape;
  814. }
  815. foreach ($escape as $key => $char) {
  816. $escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
  817. }
  818. return $escape;
  819. }
  820. /**
  821. * Resets the state of this HttpSocket instance to it's initial state (before Object::__construct got executed) or does
  822. * the same thing partially for the request and the response property only.
  823. *
  824. * @param boolean $full If set to false only HttpSocket::response and HttpSocket::request are reseted
  825. * @return boolean True on success
  826. */
  827. public function reset($full = true) {
  828. static $initalState = array();
  829. if (empty($initalState)) {
  830. $initalState = get_class_vars(__CLASS__);
  831. }
  832. if (!$full) {
  833. $this->request = $initalState['request'];
  834. $this->response = $initalState['response'];
  835. return true;
  836. }
  837. parent::reset($initalState);
  838. return true;
  839. }
  840. }