HttpSocket.php 28 KB

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