PageRenderTime 50ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/libs/http_socket.php

https://github.com/hardsshah/bookmarks
PHP | 978 lines | 616 code | 84 blank | 278 comment | 132 complexity | 7d0fdd41915cf96c727b4b747301a4f0 MD5 | raw file
  1. <?php
  2. /* SVN FILE: $Id$ */
  3. /**
  4. * HTTP Socket connection class.
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
  9. * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
  10. *
  11. * Licensed under The MIT License
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @filesource
  15. * @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
  16. * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
  17. * @package cake
  18. * @subpackage cake.cake.libs
  19. * @since CakePHP(tm) v 1.2.0
  20. * @version $Revision$
  21. * @modifiedby $LastChangedBy$
  22. * @lastmodified $Date$
  23. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  24. */
  25. App::import('Core', array('Socket', 'Set', 'Router'));
  26. /**
  27. * Cake network socket connection class.
  28. *
  29. * Core base class for HTTP network communication.
  30. *
  31. * @package cake
  32. * @subpackage cake.cake.libs
  33. */
  34. class HttpSocket extends CakeSocket {
  35. /**
  36. * Object description
  37. *
  38. * @var string
  39. * @access public
  40. */
  41. var $description = 'HTTP-based DataSource Interface';
  42. /**
  43. * When one activates the $quirksMode by setting it to true, all checks meant to enforce RFC 2616 (HTTP/1.1 specs)
  44. * will be disabled and additional measures to deal with non-standard responses will be enabled.
  45. *
  46. * @var boolean
  47. * @access public
  48. */
  49. var $quirksMode = false;
  50. /**
  51. * The default values to use for a request
  52. *
  53. * @var array
  54. * @access public
  55. */
  56. var $request = array(
  57. 'method' => 'GET',
  58. 'uri' => array(
  59. 'scheme' => 'http',
  60. 'host' => null,
  61. 'port' => 80,
  62. 'user' => null,
  63. 'pass' => null,
  64. 'path' => null,
  65. 'query' => null,
  66. 'fragment' => null
  67. ),
  68. 'auth' => array(
  69. 'method' => 'Basic',
  70. 'user' => null,
  71. 'pass' => null
  72. ),
  73. 'version' => '1.1',
  74. 'body' => '',
  75. 'line' => null,
  76. 'header' => array(
  77. 'Connection' => 'close',
  78. 'User-Agent' => 'CakePHP'
  79. ),
  80. 'raw' => null,
  81. 'cookies' => array()
  82. );
  83. /**
  84. * The default structure for storing the response
  85. *
  86. * @var array
  87. * @access public
  88. */
  89. var $response = array(
  90. 'raw' => array(
  91. 'status-line' => null,
  92. 'header' => null,
  93. 'body' => null,
  94. 'response' => null
  95. ),
  96. 'status' => array(
  97. 'http-version' => null,
  98. 'code' => null,
  99. 'reason-phrase' => null
  100. ),
  101. 'header' => array(),
  102. 'body' => '',
  103. 'cookies' => array()
  104. );
  105. /**
  106. * Default configuration settings for the HttpSocket
  107. *
  108. * @var array
  109. * @access public
  110. */
  111. var $config = array(
  112. 'persistent' => false,
  113. 'host' => 'localhost',
  114. 'protocol' => 'tcp',
  115. 'port' => 80,
  116. 'timeout' => 30,
  117. 'request' => array(
  118. 'uri' => array(
  119. 'scheme' => 'http',
  120. 'host' => 'localhost',
  121. 'port' => 80
  122. ),
  123. 'auth' => array(
  124. 'method' => 'Basic',
  125. 'user' => null,
  126. 'pass' => null
  127. ),
  128. 'cookies' => array()
  129. )
  130. );
  131. /**
  132. * String that represents a line break.
  133. *
  134. * @var string
  135. * @access public
  136. */
  137. var $lineBreak = "\r\n";
  138. /**
  139. * Build an HTTP Socket using the specified configuration.
  140. *
  141. * @param array $config Configuration
  142. */
  143. function __construct($config = array()) {
  144. if (is_string($config)) {
  145. $this->configUri($config);
  146. } elseif (is_array($config)) {
  147. if (isset($config['request']['uri']) && is_string($config['request']['uri'])) {
  148. $this->configUri($config['request']['uri']);
  149. unset($config['request']['uri']);
  150. }
  151. $this->config = Set::merge($this->config, $config);
  152. }
  153. parent::__construct($this->config);
  154. }
  155. /**
  156. * Issue the specified request.
  157. *
  158. * @param mixed $request Either an URI string, or an array defining host/uri
  159. * @return mixed false on error, request body on success
  160. * @access public
  161. */
  162. function request($request = array()) {
  163. $this->reset(false);
  164. if (is_string($request)) {
  165. $request = array('uri' => $request);
  166. } elseif (!is_array($request)) {
  167. return false;
  168. }
  169. if (!isset($request['uri'])) {
  170. $request['uri'] = null;
  171. }
  172. $uri = $this->parseUri($request['uri']);
  173. if (!isset($uri['host'])) {
  174. $host = $this->config['host'];
  175. }
  176. if (isset($request['host'])) {
  177. $host = $request['host'];
  178. unset($request['host']);
  179. }
  180. $request['uri'] = $this->url($request['uri']);
  181. $request['uri'] = $this->parseUri($request['uri'], true);
  182. $this->request = Set::merge($this->request, $this->config['request'], $request);
  183. $this->configUri($this->request['uri']);
  184. if (isset($host)) {
  185. $this->config['host'] = $host;
  186. }
  187. $cookies = null;
  188. if (is_array($this->request['header'])) {
  189. $this->request['header'] = $this->parseHeader($this->request['header']);
  190. if (!empty($this->request['cookies'])) {
  191. $cookies = $this->buildCookies($this->request['cookies']);
  192. }
  193. $this->request['header'] = array_merge(array('Host' => $this->request['uri']['host']), $this->request['header']);
  194. }
  195. if (isset($this->request['auth']['user']) && isset($this->request['auth']['pass'])) {
  196. $this->request['header']['Authorization'] = $this->request['auth']['method'] ." ". base64_encode($this->request['auth']['user'] .":".$this->request['auth']['pass']);
  197. }
  198. if (isset($this->request['uri']['user']) && isset($this->request['uri']['pass'])) {
  199. $this->request['header']['Authorization'] = $this->request['auth']['method'] ." ". base64_encode($this->request['uri']['user'] .":".$this->request['uri']['pass']);
  200. }
  201. if (is_array($this->request['body'])) {
  202. $this->request['body'] = $this->httpSerialize($this->request['body']);
  203. }
  204. if (!empty($this->request['body']) && !isset($this->request['header']['Content-Type'])) {
  205. $this->request['header']['Content-Type'] = 'application/x-www-form-urlencoded';
  206. }
  207. if (!empty($this->request['body']) && !isset($this->request['header']['Content-Length'])) {
  208. $this->request['header']['Content-Length'] = strlen($this->request['body']);
  209. }
  210. $connectionType = @$this->request['header']['Connection'];
  211. $this->request['header'] = $this->buildHeader($this->request['header']).$cookies;
  212. if (empty($this->request['line'])) {
  213. $this->request['line'] = $this->buildRequestLine($this->request);
  214. }
  215. if ($this->quirksMode === false && $this->request['line'] === false) {
  216. return $this->response = false;
  217. }
  218. if ($this->request['line'] !== false) {
  219. $this->request['raw'] = $this->request['line'];
  220. }
  221. if ($this->request['header'] !== false) {
  222. $this->request['raw'] .= $this->request['header'];
  223. }
  224. $this->request['raw'] .= "\r\n";
  225. $this->request['raw'] .= $this->request['body'];
  226. $this->write($this->request['raw']);
  227. $response = null;
  228. while ($data = $this->read()) {
  229. $response .= $data;
  230. }
  231. if ($connectionType == 'close') {
  232. $this->disconnect();
  233. }
  234. $this->response = $this->parseResponse($response);
  235. if (!empty($this->response['cookies'])) {
  236. $this->config['request']['cookies'] = array_merge($this->config['request']['cookies'], $this->response['cookies']);
  237. }
  238. return $this->response['body'];
  239. }
  240. /**
  241. * Issues a GET request to the specified URI, query, and request.
  242. *
  243. * @param mixed $uri URI to request (see {@link parseUri()})
  244. * @param array $query Query to append to URI
  245. * @param array $request An indexed array with indexes such as 'method' or uri
  246. * @return mixed Result of request
  247. * @access public
  248. */
  249. function get($uri = null, $query = array(), $request = array()) {
  250. if (!empty($query)) {
  251. $uri =$this->parseUri($uri);
  252. if (isset($uri['query'])) {
  253. $uri['query'] = array_merge($uri['query'], $query);
  254. } else {
  255. $uri['query'] = $query;
  256. }
  257. $uri = $this->buildUri($uri);
  258. }
  259. $request = Set::merge(array('method' => 'GET', 'uri' => $uri), $request);
  260. return $this->request($request);
  261. }
  262. /**
  263. * Issues a POST request to the specified URI, query, and request.
  264. *
  265. * @param mixed $uri URI to request (see {@link parseUri()})
  266. * @param array $query Query to append to URI
  267. * @param array $request An indexed array with indexes such as 'method' or uri
  268. * @return mixed Result of request
  269. * @access public
  270. */
  271. function post($uri = null, $data = array(), $request = array()) {
  272. $request = Set::merge(array('method' => 'POST', 'uri' => $uri, 'body' => $data), $request);
  273. return $this->request($request);
  274. }
  275. /**
  276. * Issues a PUT request to the specified URI, query, and request.
  277. *
  278. * @param mixed $uri URI to request (see {@link parseUri()})
  279. * @param array $query Query to append to URI
  280. * @param array $request An indexed array with indexes such as 'method' or uri
  281. * @return mixed Result of request
  282. * @access public
  283. */
  284. function put($uri = null, $data = array(), $request = array()) {
  285. $request = Set::merge(array('method' => 'PUT', 'uri' => $uri, 'body' => $data), $request);
  286. return $this->request($request);
  287. }
  288. /**
  289. * Issues a DELETE request to the specified URI, query, and request.
  290. *
  291. * @param mixed $uri URI to request (see {@link parseUri()})
  292. * @param array $query Query to append to URI
  293. * @param array $request An indexed array with indexes such as 'method' or uri
  294. * @return mixed Result of request
  295. * @access public
  296. */
  297. function delete($uri = null, $data = array(), $request = array()) {
  298. $request = Set::merge(array('method' => 'DELETE', 'uri' => $uri, 'body' => $data), $request);
  299. return $this->request($request);
  300. }
  301. /**
  302. * undocumented function
  303. *
  304. * @param unknown $url
  305. * @param unknown $uriTemplate
  306. * @return void
  307. * @access public
  308. */
  309. function url($url = null, $uriTemplate = null) {
  310. if (is_null($url)) {
  311. $url = '/';
  312. }
  313. if (is_string($url)) {
  314. if ($url{0} == '/') {
  315. $url = $this->config['request']['uri']['host'].':'.$this->config['request']['uri']['port'] . $url;
  316. }
  317. if (!preg_match('/^.+:\/\/|\*|^\//', $url)) {
  318. $url = $this->config['request']['uri']['scheme'].'://'.$url;
  319. }
  320. } elseif (!is_array($url) && !empty($url)) {
  321. return false;
  322. }
  323. $base = array_merge($this->config['request']['uri'], array('scheme' => array('http', 'https'), 'port' => array(80, 443)));
  324. $url = $this->parseUri($url, $base);
  325. if (empty($url)) {
  326. $url = $this->config['request']['uri'];
  327. }
  328. if (!empty($uriTemplate)) {
  329. return $this->buildUri($url, $uriTemplate);
  330. }
  331. return $this->buildUri($url);
  332. }
  333. /**
  334. * Parses the given message and breaks it down in parts.
  335. *
  336. * @param string $message Message to parse
  337. * @return array Parsed message (with indexed elements such as raw, status, header, body)
  338. * @access protected
  339. */
  340. function parseResponse($message) {
  341. if (is_array($message)) {
  342. return $message;
  343. } elseif (!is_string($message)) {
  344. return false;
  345. }
  346. static $responseTemplate;
  347. if (empty($responseTemplate)) {
  348. $classVars = get_class_vars(__CLASS__);
  349. $responseTemplate = $classVars['response'];
  350. }
  351. $response = $responseTemplate;
  352. if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) {
  353. return false;
  354. }
  355. list($null, $response['raw']['status-line'], $response['raw']['header']) = $match;
  356. $response['raw']['response'] = $message;
  357. $response['raw']['body'] = substr($message, strlen($match[0]));
  358. if (preg_match("/(.+) ([0-9]{3}) (.+)\r\n/DU", $response['raw']['status-line'], $match)) {
  359. $response['status']['http-version'] = $match[1];
  360. $response['status']['code'] = (int)$match[2];
  361. $response['status']['reason-phrase'] = $match[3];
  362. }
  363. $response['header'] = $this->parseHeader($response['raw']['header']);
  364. $decoded = $this->decodeBody($response['raw']['body'], @$response['header']['Transfer-Encoding']);
  365. $response['body'] = $decoded['body'];
  366. if (!empty($decoded['header'])) {
  367. $response['header'] = $this->parseHeader($this->buildHeader($response['header']).$this->buildHeader($decoded['header']));
  368. }
  369. if (!empty($response['header'])) {
  370. $response['cookies'] = $this->parseCookies($response['header']);
  371. }
  372. foreach ($response['raw'] as $field => $val) {
  373. if ($val === '') {
  374. $response['raw'][$field] = null;
  375. }
  376. }
  377. return $response;
  378. }
  379. /**
  380. * Generic function to decode a $body with a given $encoding. Returns either an array with the keys
  381. * 'body' and 'header' or false on failure.
  382. *
  383. * @param string $body A string continaing the body to decode
  384. * @param mixed $encoding Can be false in case no encoding is being used, or a string representing the encoding
  385. * @return mixed Array or false
  386. * @access protected
  387. */
  388. function decodeBody($body, $encoding = 'chunked') {
  389. if (!is_string($body)) {
  390. return false;
  391. }
  392. if (empty($encoding)) {
  393. return array('body' => $body, 'header' => false);
  394. }
  395. $decodeMethod = 'decode'.Inflector::camelize(str_replace('-', '_', $encoding)).'Body';
  396. if (!is_callable(array(&$this, $decodeMethod))) {
  397. if (!$this->quirksMode) {
  398. trigger_error(sprintf(__('HttpSocket::decodeBody - Unknown encoding: %s. Activate quirks mode to surpress error.', true), h($encoding)), E_USER_WARNING);
  399. }
  400. return array('body' => $body, 'header' => false);
  401. }
  402. return $this->{$decodeMethod}($body);
  403. }
  404. /**
  405. * Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as
  406. * a result.
  407. *
  408. * @param string $body A string continaing the chunked body to decode
  409. * @return mixed Array or false
  410. * @access protected
  411. */
  412. function decodeChunkedBody($body) {
  413. if (!is_string($body)) {
  414. return false;
  415. }
  416. $decodedBody = null;
  417. $chunkLength = null;
  418. while ($chunkLength !== 0) {
  419. if (!preg_match("/^([0-9a-f]+) *(?:;(.+)=(.+))?\r\n/iU", $body, $match)) {
  420. if (!$this->quirksMode) {
  421. trigger_error(__('HttpSocket::decodeChunkedBody - Could not parse malformed chunk. Activate quirks mode to do this.', true), E_USER_WARNING);
  422. return false;
  423. }
  424. break;
  425. }
  426. $chunkSize = 0;
  427. $hexLength = 0;
  428. $chunkExtensionName = '';
  429. $chunkExtensionValue = '';
  430. if (isset($match[0])) {
  431. $chunkSize = $match[0];
  432. }
  433. if (isset($match[1])) {
  434. $hexLength = $match[1];
  435. }
  436. if (isset($match[2])) {
  437. $chunkExtensionName = $match[2];
  438. }
  439. if (isset($match[3])) {
  440. $chunkExtensionValue = $match[3];
  441. }
  442. $body = substr($body, strlen($chunkSize));
  443. $chunkLength = hexdec($hexLength);
  444. $chunk = substr($body, 0, $chunkLength);
  445. if (!empty($chunkExtensionName)) {
  446. /**
  447. * @todo See if there are popular chunk extensions we should implement
  448. */
  449. }
  450. $decodedBody .= $chunk;
  451. if ($chunkLength !== 0) {
  452. $body = substr($body, $chunkLength+strlen("\r\n"));
  453. }
  454. }
  455. $entityHeader = false;
  456. if (!empty($body)) {
  457. $entityHeader = $this->parseHeader($body);
  458. }
  459. return array('body' => $decodedBody, 'header' => $entityHeader);
  460. }
  461. /**
  462. * Parses and sets the specified URI into current request configuration.
  463. *
  464. * @param mixed $uri URI (see {@link parseUri()})
  465. * @return array Current configuration settings
  466. * @access protected
  467. */
  468. function configUri($uri = null) {
  469. if (empty($uri)) {
  470. return false;
  471. }
  472. if (is_array($uri)) {
  473. $uri = $this->parseUri($uri);
  474. } else {
  475. $uri = $this->parseUri($uri, true);
  476. }
  477. if (!isset($uri['host'])) {
  478. return false;
  479. }
  480. $config = array(
  481. 'request' => array(
  482. 'uri' => array_intersect_key($uri, $this->config['request']['uri']),
  483. 'auth' => array_intersect_key($uri, $this->config['request']['auth'])
  484. )
  485. );
  486. $this->config = Set::merge($this->config, $config);
  487. $this->config = Set::merge($this->config, array_intersect_key($this->config['request']['uri'], $this->config));
  488. return $this->config;
  489. }
  490. /**
  491. * Takes a $uri array and turns it into a fully qualified URL string
  492. *
  493. * @param array $uri A $uri array, or uses $this->config if left empty
  494. * @param string $uriTemplate The Uri template/format to use
  495. * @return string A fully qualified URL formated according to $uriTemplate
  496. * @access protected
  497. */
  498. function buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') {
  499. if (is_string($uri)) {
  500. $uri = array('host' => $uri);
  501. }
  502. $uri = $this->parseUri($uri, true);
  503. if (!is_array($uri) || empty($uri)) {
  504. return false;
  505. }
  506. $uri['path'] = preg_replace('/^\//', null, $uri['path']);
  507. $uri['query'] = $this->httpSerialize($uri['query']);
  508. $stripIfEmpty = array(
  509. 'query' => '?%query',
  510. 'fragment' => '#%fragment',
  511. 'user' => '%user:%pass@'
  512. );
  513. foreach ($stripIfEmpty as $key => $strip) {
  514. if (empty($uri[$key])) {
  515. $uriTemplate = str_replace($strip, null, $uriTemplate);
  516. }
  517. }
  518. $defaultPorts = array('http' => 80, 'https' => 443);
  519. if (array_key_exists($uri['scheme'], $defaultPorts) && $defaultPorts[$uri['scheme']] == $uri['port']) {
  520. $uriTemplate = str_replace(':%port', null, $uriTemplate);
  521. }
  522. foreach ($uri as $property => $value) {
  523. $uriTemplate = str_replace('%'.$property, $value, $uriTemplate);
  524. }
  525. if ($uriTemplate === '/*') {
  526. $uriTemplate = '*';
  527. }
  528. return $uriTemplate;
  529. }
  530. /**
  531. * Parses the given URI and breaks it down into pieces as an indexed array with elements
  532. * such as 'scheme', 'port', 'query'.
  533. *
  534. * @param string $uri URI to parse
  535. * @param mixed $base If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc.
  536. * @return array Parsed URI
  537. * @access protected
  538. */
  539. function parseUri($uri = null, $base = array()) {
  540. $uriBase = array(
  541. 'scheme' => array('http', 'https'),
  542. 'host' => null,
  543. 'port' => array(80, 443),
  544. 'user' => null,
  545. 'pass' => null,
  546. 'path' => '/',
  547. 'query' => null,
  548. 'fragment' => null
  549. );
  550. if (is_string($uri)) {
  551. $uri = parse_url($uri);
  552. }
  553. if (!is_array($uri) || empty($uri)) {
  554. return false;
  555. }
  556. if ($base === true) {
  557. $base = $uriBase;
  558. }
  559. if (isset($base['port'], $base['scheme']) && is_array($base['port']) && is_array($base['scheme'])) {
  560. if (isset($uri['scheme']) && !isset($uri['port'])) {
  561. $base['port'] = $base['port'][array_search($uri['scheme'], $base['scheme'])];
  562. } elseif (isset($uri['port']) && !isset($uri['scheme'])) {
  563. $base['scheme'] = $base['scheme'][array_search($uri['port'], $base['port'])];
  564. }
  565. }
  566. if (is_array($base) && !empty($base)) {
  567. $uri = array_merge($base, $uri);
  568. }
  569. if (isset($uri['scheme']) && is_array($uri['scheme'])) {
  570. $uri['scheme'] = array_shift($uri['scheme']);
  571. }
  572. if (isset($uri['port']) && is_array($uri['port'])) {
  573. $uri['port'] = array_shift($uri['port']);
  574. }
  575. if (array_key_exists('query', $uri)) {
  576. $uri['query'] = $this->parseQuery($uri['query']);
  577. }
  578. if (!array_intersect_key($uriBase, $uri)) {
  579. return false;
  580. }
  581. return $uri;
  582. }
  583. /**
  584. * 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
  585. * supports nesting by using the php bracket syntax. So this menas you can parse queries like:
  586. *
  587. * - ?key[subKey]=value
  588. * - ?key[]=value1&key[]=value2
  589. *
  590. * A leading '?' mark in $query is optional and does not effect the outcome of this function. For the complete capabilities of this implementation
  591. * take a look at HttpSocketTest::testParseQuery()
  592. *
  593. * @param mixed $query A query string to parse into an array or an array to return directly "as is"
  594. * @return array The $query parsed into a possibly multi-level array. If an empty $query is given, an empty array is returned.
  595. * @access protected
  596. */
  597. function parseQuery($query) {
  598. if (is_array($query)) {
  599. return $query;
  600. }
  601. $parsedQuery = array();
  602. if (is_string($query) && !empty($query)) {
  603. $query = preg_replace('/^\?/', '', $query);
  604. $items = explode('&', $query);
  605. foreach ($items as $item) {
  606. if (strpos($item, '=') !== false) {
  607. list($key, $value) = explode('=', $item);
  608. } else {
  609. $key = $item;
  610. $value = null;
  611. }
  612. $key = urldecode($key);
  613. $value = urldecode($value);
  614. if (preg_match_all('/\[([^\[\]]*)\]/iUs', $key, $matches)) {
  615. $subKeys = $matches[1];
  616. $rootKey = substr($key, 0, strpos($key, '['));
  617. if (!empty($rootKey)) {
  618. array_unshift($subKeys, $rootKey);
  619. }
  620. $queryNode =& $parsedQuery;
  621. foreach ($subKeys as $subKey) {
  622. if (!is_array($queryNode)) {
  623. $queryNode = array();
  624. }
  625. if ($subKey === '') {
  626. $queryNode[] = array();
  627. end($queryNode);
  628. $subKey = key($queryNode);
  629. }
  630. $queryNode =& $queryNode[$subKey];
  631. }
  632. $queryNode = $value;
  633. } else {
  634. $parsedQuery[$key] = $value;
  635. }
  636. }
  637. }
  638. return $parsedQuery;
  639. }
  640. /**
  641. * Builds a request line according to HTTP/1.1 specs. Activate quirks mode to work outside specs.
  642. *
  643. * @param array $request Needs to contain a 'uri' key. Should also contain a 'method' key, otherwise defaults to GET.
  644. * @param string $versionToken The version token to use, defaults to HTTP/1.1
  645. * @return string Request line
  646. * @access protected
  647. */
  648. function buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') {
  649. $asteriskMethods = array('OPTIONS');
  650. if (is_string($request)) {
  651. $isValid = preg_match("/(.+) (.+) (.+)\r\n/U", $request, $match);
  652. if (!$this->quirksMode && (!$isValid || ($match[2] == '*' && !in_array($match[3], $asteriskMethods)))) {
  653. trigger_error(__('HttpSocket::buildRequestLine - Passed an invalid request line string. Activate quirks mode to do this.', true), E_USER_WARNING);
  654. return false;
  655. }
  656. return $request;
  657. } elseif (!is_array($request)) {
  658. return false;
  659. } elseif (!array_key_exists('uri', $request)) {
  660. return false;
  661. }
  662. $request['uri'] = $this->parseUri($request['uri']);
  663. $request = array_merge(array('method' => 'GET'), $request);
  664. $request['uri'] = $this->buildUri($request['uri'], '/%path?%query');
  665. if (!$this->quirksMode && $request['uri'] === '*' && !in_array($request['method'], $asteriskMethods)) {
  666. trigger_error(sprintf(__('HttpSocket::buildRequestLine - The "*" asterisk character is only allowed for the following methods: %s. Activate quirks mode to work outside of HTTP/1.1 specs.', true), join(',', $asteriskMethods)), E_USER_WARNING);
  667. return false;
  668. }
  669. return $request['method'].' '.$request['uri'].' '.$versionToken.$this->lineBreak;
  670. }
  671. /**
  672. * Serializes an array for transport.
  673. *
  674. * @param array $data Data to serialize
  675. * @return string Serialized variable
  676. * @access protected
  677. */
  678. function httpSerialize($data = array()) {
  679. if (is_string($data)) {
  680. return $data;
  681. }
  682. if (empty($data) || !is_array($data)) {
  683. return false;
  684. }
  685. return substr(Router::queryString($data), 1);
  686. }
  687. /**
  688. * Builds the header.
  689. *
  690. * @param array $header Header to build
  691. * @return string Header built from array
  692. * @access protected
  693. */
  694. function buildHeader($header, $mode = 'standard') {
  695. if (is_string($header)) {
  696. return $header;
  697. } elseif (!is_array($header)) {
  698. return false;
  699. }
  700. $returnHeader = '';
  701. foreach ($header as $field => $contents) {
  702. if (is_array($contents) && $mode == 'standard') {
  703. $contents = join(',', $contents);
  704. }
  705. foreach ((array)$contents as $content) {
  706. $contents = preg_replace("/\r\n(?![\t ])/", "\r\n ", $content);
  707. $field = $this->escapeToken($field);
  708. $returnHeader .= $field.': '.$contents.$this->lineBreak;
  709. }
  710. }
  711. return $returnHeader;
  712. }
  713. /**
  714. * Parses an array based header.
  715. *
  716. * @param array $header Header as an indexed array (field => value)
  717. * @return array Parsed header
  718. * @access protected
  719. */
  720. function parseHeader($header) {
  721. if (is_array($header)) {
  722. foreach ($header as $field => $value) {
  723. unset($header[$field]);
  724. $field = strtolower($field);
  725. preg_match_all('/(?:^|(?<=-))[a-z]/U', $field, $offsets, PREG_OFFSET_CAPTURE);
  726. foreach ($offsets[0] as $offset) {
  727. $field = substr_replace($field, strtoupper($offset[0]), $offset[1], 1);
  728. }
  729. $header[$field] = $value;
  730. }
  731. return $header;
  732. } elseif (!is_string($header)) {
  733. return false;
  734. }
  735. preg_match_all("/(.+):(.+)(?:(?<![\t ])".$this->lineBreak."|\$)/Uis", $header, $matches, PREG_SET_ORDER);
  736. $header = array();
  737. foreach ($matches as $match) {
  738. list(, $field, $value) = $match;
  739. $value = trim($value);
  740. $value = preg_replace("/[\t ]\r\n/", "\r\n", $value);
  741. $field = $this->unescapeToken($field);
  742. $field = strtolower($field);
  743. preg_match_all('/(?:^|(?<=-))[a-z]/U', $field, $offsets, PREG_OFFSET_CAPTURE);
  744. foreach ($offsets[0] as $offset) {
  745. $field = substr_replace($field, strtoupper($offset[0]), $offset[1], 1);
  746. }
  747. if (!isset($header[$field])) {
  748. $header[$field] = $value;
  749. } else {
  750. $header[$field] = array_merge((array)$header[$field], (array)$value);
  751. }
  752. }
  753. return $header;
  754. }
  755. /**
  756. * undocumented function
  757. *
  758. * @param unknown $header
  759. * @return void
  760. * @access public
  761. * @todo Make this 100% RFC 2965 confirm
  762. */
  763. function parseCookies($header) {
  764. if (!isset($header['Set-Cookie'])) {
  765. return false;
  766. }
  767. $cookies = array();
  768. foreach ((array)$header['Set-Cookie'] as $cookie) {
  769. $parts = preg_split('/(?<![^;]");[ \t]*/', $cookie);
  770. list($name, $value) = explode('=', array_shift($parts));
  771. $cookies[$name] = compact('value');
  772. foreach ($parts as $part) {
  773. if (strpos($part, '=') !== false) {
  774. list($key, $value) = explode('=', $part);
  775. } else {
  776. $key = $part;
  777. $value = true;
  778. }
  779. $key = strtolower($key);
  780. if (!isset($cookies[$name][$key])) {
  781. $cookies[$name][$key] = $value;
  782. }
  783. }
  784. }
  785. return $cookies;
  786. }
  787. /**
  788. * undocumented function
  789. *
  790. * @param unknown $cookies
  791. * @return void
  792. * @access public
  793. * @todo Refactor token escape mechanism to be configurable
  794. */
  795. function buildCookies($cookies) {
  796. $header = array();
  797. foreach ($cookies as $name => $cookie) {
  798. $header[] = $name.'='.$this->escapeToken($cookie['value'], array(';'));
  799. }
  800. $header = $this->buildHeader(array('Cookie' => $header), 'pragmatic');
  801. return $header;
  802. }
  803. /**
  804. * undocumented function
  805. *
  806. * @return void
  807. * @access public
  808. */
  809. function saveCookies() {
  810. }
  811. /**
  812. * undocumented function
  813. *
  814. * @return void
  815. * @access public
  816. */
  817. function loadCookies() {
  818. }
  819. /**
  820. * Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs)
  821. *
  822. * @param string $token Token to unescape
  823. * @return string Unescaped token
  824. * @access protected
  825. * @todo Test $chars parameter
  826. */
  827. function unescapeToken($token, $chars = null) {
  828. $regex = '/"(['.join('', $this->__tokenEscapeChars(true, $chars)).'])"/';
  829. $token = preg_replace($regex, '\\1', $token);
  830. return $token;
  831. }
  832. /**
  833. * Escapes a given $token according to RFC 2616 (HTTP 1.1 specs)
  834. *
  835. * @param string $token Token to escape
  836. * @return string Escaped token
  837. * @access protected
  838. * @todo Test $chars parameter
  839. */
  840. function escapeToken($token, $chars = null) {
  841. $regex = '/(['.join('', $this->__tokenEscapeChars(true, $chars)).'])/';
  842. $token = preg_replace($regex, '"\\1"', $token);
  843. return $token;
  844. }
  845. /**
  846. * Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
  847. *
  848. * @param boolean $hex true to get them as HEX values, false otherwise
  849. * @return array Escape chars
  850. * @access private
  851. * @todo Test $chars parameter
  852. */
  853. function __tokenEscapeChars($hex = true, $chars = null) {
  854. if (!empty($chars)) {
  855. $escape = $chars;
  856. } else {
  857. $escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
  858. for ($i = 0; $i <= 31; $i++) {
  859. $escape[] = chr($i);
  860. }
  861. $escape[] = chr(127);
  862. }
  863. if ($hex == false) {
  864. return $escape;
  865. }
  866. $regexChars = '';
  867. foreach ($escape as $key => $char) {
  868. $escape[$key] = '\\x'.str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
  869. }
  870. return $escape;
  871. }
  872. /**
  873. * Resets the state of this HttpSocket instance to it's initial state (before Object::__construct got executed) or does
  874. * the same thing partially for the request and the response property only.
  875. *
  876. * @param boolean $full If set to false only HttpSocket::response and HttpSocket::request are reseted
  877. * @return boolean True on success
  878. * @access public
  879. */
  880. function reset($full = true) {
  881. static $initalState = array();
  882. if (empty($initalState)) {
  883. $initalState = get_class_vars(__CLASS__);
  884. }
  885. if ($full == false) {
  886. $this->request = $initalState['request'];
  887. $this->response = $initalState['response'];
  888. return true;
  889. }
  890. parent::reset($initalState);
  891. return true;
  892. }
  893. }
  894. ?>