HttpSocket.php 27 KB

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