10 defined(
'JPATH_PLATFORM') or die;
38 if (!self::isSupported())
40 throw new RuntimeException(
'Cannot use a stream transport when fopen() is not available.');
44 if (!ini_get(
'allow_url_fopen'))
46 throw new RuntimeException(
'Cannot use a stream transport when "allow_url_fopen" is disabled.');
49 $this->options = $options;
67 public function request($method,
JUri $uri, $data = null, array $headers = null, $timeout = null, $userAgent = null)
70 $options = array(
'method' => strtoupper($method));
78 $options[
'content'] = $data;
83 $options[
'content'] = http_build_query($data);
86 if (!isset($headers[
'Content-Type']))
88 $headers[
'Content-Type'] =
'application/x-www-form-urlencoded; charset=utf-8';
92 $headers[
'Content-Length'] = strlen($options[
'content']);
100 foreach ($headers as $key => $value)
102 $headerString .= $key .
': ' . $value .
"\r\n";
106 $options[
'header'] = trim($headerString,
"\r\n");
112 $options[
'timeout'] = (int) $timeout;
116 if (isset($userAgent))
118 $options[
'user_agent'] = $userAgent;
122 $options[
'ignore_errors'] = 1;
125 $options[
'follow_location'] = (int) $this->options->get(
'follow_location', 1);
128 $context = stream_context_create(array(
'http' => $options));
132 $track_errors = ini_get(
'track_errors');
133 ini_set(
'track_errors',
true);
136 $stream = @fopen((
string) $uri,
'r',
false, $context);
143 $php_errormsg = sprintf(
'Could not connect to resource: %s', $uri, $err, $errno);
147 ini_set(
'track_errors', $track_errors);
149 throw new RuntimeException($php_errormsg);
153 ini_set(
'track_errors', $track_errors);
156 $metadata = stream_get_meta_data($stream);
159 $content = stream_get_contents($stream);
164 if (isset($metadata[
'wrapper_data'][
'headers']))
166 $headers = $metadata[
'wrapper_data'][
'headers'];
168 elseif (isset($metadata[
'wrapper_data']))
170 $headers = $metadata[
'wrapper_data'];
177 return $this->getResponse($headers, $content);
192 protected function getResponse(array $headers, $body)
198 $return->body = $body;
201 preg_match(
'/[0-9]{3}/', array_shift($headers), $matches);
204 if (is_numeric($code))
206 $return->code = (int) $code;
212 throw new UnexpectedValueException(
'No HTTP response code found.');
216 foreach ($headers as $header)
218 $pos = strpos($header,
':');
219 $return->headers[trim(substr($header, 0, $pos))] = trim(substr($header, ($pos + 1)));
232 public static function isSupported()
234 return function_exists(
'fopen') && is_callable(
'fopen');