HttpSocket.php 27 KB

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