PageRenderTime 52ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/libraries/src/Http/Transport/StreamTransport.php

https://bitbucket.org/taaas/dizi.lh
PHP | 285 lines | 149 code | 46 blank | 90 comment | 18 complexity | 8c55ee32e10e4e979af950be82525fc8 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, GPL-3.0, 0BSD, MIT
  1. <?php
  2. /**
  3. * Joomla! Content Management System
  4. *
  5. * @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
  6. * @license GNU General Public License version 2 or later; see LICENSE.txt
  7. */
  8. namespace Joomla\CMS\Http\Transport;
  9. defined('JPATH_PLATFORM') or die;
  10. use Joomla\CMS\Http\Response;
  11. use Joomla\CMS\Http\TransportInterface;
  12. use Joomla\CMS\Uri\Uri;
  13. use Joomla\Registry\Registry;
  14. /**
  15. * HTTP transport class for using PHP streams.
  16. *
  17. * @since 11.3
  18. */
  19. class StreamTransport implements TransportInterface
  20. {
  21. /**
  22. * @var Registry The client options.
  23. * @since 11.3
  24. */
  25. protected $options;
  26. /**
  27. * Constructor.
  28. *
  29. * @param Registry $options Client options object.
  30. *
  31. * @since 11.3
  32. * @throws \RuntimeException
  33. */
  34. public function __construct(Registry $options)
  35. {
  36. // Verify that URLs can be used with fopen();
  37. if (!ini_get('allow_url_fopen'))
  38. {
  39. throw new \RuntimeException('Cannot use a stream transport when "allow_url_fopen" is disabled.');
  40. }
  41. // Verify that fopen() is available.
  42. if (!self::isSupported())
  43. {
  44. throw new \RuntimeException('Cannot use a stream transport when fopen() is not available or "allow_url_fopen" is disabled.');
  45. }
  46. $this->options = $options;
  47. }
  48. /**
  49. * Send a request to the server and return a HttpResponse object with the response.
  50. *
  51. * @param string $method The HTTP method for sending the request.
  52. * @param Uri $uri The URI to the resource to request.
  53. * @param mixed $data Either an associative array or a string to be sent with the request.
  54. * @param array $headers An array of request headers to send with the request.
  55. * @param integer $timeout Read timeout in seconds.
  56. * @param string $userAgent The optional user agent string to send with the request.
  57. *
  58. * @return Response
  59. *
  60. * @since 11.3
  61. * @throws \RuntimeException
  62. */
  63. public function request($method, Uri $uri, $data = null, array $headers = null, $timeout = null, $userAgent = null)
  64. {
  65. // Create the stream context options array with the required method offset.
  66. $options = array('method' => strtoupper($method));
  67. // If data exists let's encode it and make sure our Content-Type header is set.
  68. if (isset($data))
  69. {
  70. // If the data is a scalar value simply add it to the stream context options.
  71. if (is_scalar($data))
  72. {
  73. $options['content'] = $data;
  74. }
  75. // Otherwise we need to encode the value first.
  76. else
  77. {
  78. $options['content'] = http_build_query($data);
  79. }
  80. if (!isset($headers['Content-Type']))
  81. {
  82. $headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
  83. }
  84. // Add the relevant headers.
  85. $headers['Content-Length'] = strlen($options['content']);
  86. }
  87. // If an explicit timeout is given user it.
  88. if (isset($timeout))
  89. {
  90. $options['timeout'] = (int) $timeout;
  91. }
  92. // If an explicit user agent is given use it.
  93. if (isset($userAgent))
  94. {
  95. $options['user_agent'] = $userAgent;
  96. }
  97. // Ignore HTTP errors so that we can capture them.
  98. $options['ignore_errors'] = 1;
  99. // Follow redirects.
  100. $options['follow_location'] = (int) $this->options->get('follow_location', 1);
  101. // Set any custom transport options
  102. foreach ($this->options->get('transport.stream', array()) as $key => $value)
  103. {
  104. $options[$key] = $value;
  105. }
  106. // Add the proxy configuration, if any.
  107. $config = \JFactory::getConfig();
  108. if ($config->get('proxy_enable'))
  109. {
  110. $options['proxy'] = $config->get('proxy_host') . ':' . $config->get('proxy_port');
  111. $options['request_fulluri'] = true;
  112. // Put any required authorization into the headers array to be handled later
  113. // TODO: do we need to support any auth type other than Basic?
  114. if ($user = $config->get('proxy_user'))
  115. {
  116. $auth = base64_encode($config->get('proxy_user') . ':' . $config->get('proxy_pass'));
  117. $headers['Proxy-Authorization'] = 'Basic ' . $auth;
  118. }
  119. }
  120. // Build the headers string for the request.
  121. $headerEntries = array();
  122. if (isset($headers))
  123. {
  124. foreach ($headers as $key => $value)
  125. {
  126. $headerEntries[] = $key . ': ' . $value;
  127. }
  128. // Add the headers string into the stream context options array.
  129. $options['header'] = implode("\r\n", $headerEntries);
  130. }
  131. // Get the current context options.
  132. $contextOptions = stream_context_get_options(stream_context_get_default());
  133. // Add our options to the current ones, if any.
  134. $contextOptions['http'] = isset($contextOptions['http']) ? array_merge($contextOptions['http'], $options) : $options;
  135. // Create the stream context for the request.
  136. $context = stream_context_create(
  137. array(
  138. 'http' => $options,
  139. 'ssl' => array(
  140. 'verify_peer' => true,
  141. 'cafile' => $this->options->get('stream.certpath', __DIR__ . '/cacert.pem'),
  142. 'verify_depth' => 5,
  143. ),
  144. )
  145. );
  146. // Authentification, if needed
  147. if ($this->options->get('userauth') && $this->options->get('passwordauth'))
  148. {
  149. $uri->setUser($this->options->get('userauth'));
  150. $uri->setPass($this->options->get('passwordauth'));
  151. }
  152. // Capture PHP errors
  153. $php_errormsg = '';
  154. $track_errors = ini_get('track_errors');
  155. ini_set('track_errors', true);
  156. // Open the stream for reading.
  157. $stream = @fopen((string) $uri, 'r', false, $context);
  158. if (!$stream)
  159. {
  160. if (!$php_errormsg)
  161. {
  162. // Error but nothing from php? Create our own
  163. $php_errormsg = sprintf('Could not connect to resource: %s', $uri, $err, $errno);
  164. }
  165. // Restore error tracking to give control to the exception handler
  166. ini_set('track_errors', $track_errors);
  167. throw new \RuntimeException($php_errormsg);
  168. }
  169. // Restore error tracking to what it was before.
  170. ini_set('track_errors', $track_errors);
  171. // Get the metadata for the stream, including response headers.
  172. $metadata = stream_get_meta_data($stream);
  173. // Get the contents from the stream.
  174. $content = stream_get_contents($stream);
  175. // Close the stream.
  176. fclose($stream);
  177. if (isset($metadata['wrapper_data']['headers']))
  178. {
  179. $headers = $metadata['wrapper_data']['headers'];
  180. }
  181. elseif (isset($metadata['wrapper_data']))
  182. {
  183. $headers = $metadata['wrapper_data'];
  184. }
  185. else
  186. {
  187. $headers = array();
  188. }
  189. return $this->getResponse($headers, $content);
  190. }
  191. /**
  192. * Method to get a response object from a server response.
  193. *
  194. * @param array $headers The response headers as an array.
  195. * @param string $body The response body as a string.
  196. *
  197. * @return Response
  198. *
  199. * @since 11.3
  200. * @throws \UnexpectedValueException
  201. */
  202. protected function getResponse(array $headers, $body)
  203. {
  204. // Create the response object.
  205. $return = new Response;
  206. // Set the body for the response.
  207. $return->body = $body;
  208. // Get the response code from the first offset of the response headers.
  209. preg_match('/[0-9]{3}/', array_shift($headers), $matches);
  210. $code = $matches[0];
  211. if (is_numeric($code))
  212. {
  213. $return->code = (int) $code;
  214. }
  215. // No valid response code was detected.
  216. else
  217. {
  218. throw new \UnexpectedValueException('No HTTP response code found.');
  219. }
  220. // Add the response headers to the response object.
  221. foreach ($headers as $header)
  222. {
  223. $pos = strpos($header, ':');
  224. $return->headers[trim(substr($header, 0, $pos))] = trim(substr($header, ($pos + 1)));
  225. }
  226. return $return;
  227. }
  228. /**
  229. * Method to check if http transport stream available for use
  230. *
  231. * @return bool true if available else false
  232. *
  233. * @since 12.1
  234. */
  235. public static function isSupported()
  236. {
  237. return function_exists('fopen') && is_callable('fopen') && ini_get('allow_url_fopen');
  238. }
  239. }