HttpSocket.php 28 KB

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