10 defined(
'JPATH_PLATFORM') or die;
38 if (!function_exists(
'curl_init') || !is_callable(
'curl_init'))
40 throw new RuntimeException(
'Cannot use a cURL transport when curl_init() is not available.');
43 $this->options = $options;
61 public function request($method,
JUri $uri, $data = null, array $headers = null, $timeout = null, $userAgent = null)
67 $options[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
70 $options[CURLOPT_NOBODY] = ($method ===
'HEAD');
73 $options[CURLOPT_CAINFO] = $this->options->get(
'curl.certpath', __DIR__ .
'/cacert.pem');
79 if (is_scalar($data) || (isset($headers[
'Content-Type']) && strpos($headers[
'Content-Type'],
'multipart/form-data') === 0))
81 $options[CURLOPT_POSTFIELDS] = $data;
87 $options[CURLOPT_POSTFIELDS] = http_build_query($data);
90 if (!isset($headers[
'Content-Type']))
92 $headers[
'Content-Type'] =
'application/x-www-form-urlencoded; charset=utf-8';
96 if (is_scalar($options[CURLOPT_POSTFIELDS]))
98 $headers[
'Content-Length'] = strlen($options[CURLOPT_POSTFIELDS]);
103 $headerArray = array();
107 foreach ($headers as $key => $value)
109 $headerArray[] = $key .
': ' . $value;
113 $options[CURLOPT_HTTPHEADER] = $headerArray;
119 $options[CURLOPT_TIMEOUT] = (int) $timeout;
120 $options[CURLOPT_CONNECTTIMEOUT] = (int) $timeout;
124 if (isset($userAgent))
126 $options[CURLOPT_USERAGENT] = $userAgent;
130 $options[CURLOPT_URL] = (string) $uri;
133 $options[CURLOPT_HEADER] =
true;
136 $options[CURLOPT_RETURNTRANSFER] =
true;
140 $options[CURLOPT_HTTPHEADER][] =
'Expect:';
143 $options[CURLOPT_FOLLOWLOCATION] = (bool) $this->options->get(
'follow_location',
true);
146 curl_setopt_array($ch, $options);
149 $content = curl_exec($ch);
152 if (!is_string($content))
154 $message = curl_error($ch);
159 $message =
'No HTTP response received';
162 throw new RuntimeException($message);
166 $info = curl_getinfo($ch);
171 return $this->getResponse($content, $info);
186 protected function getResponse($content, $info)
192 $redirects = isset($info[
'redirect_count']) ? $info[
'redirect_count'] : 0;
199 $response = explode(
"\r\n\r\n", $content, 2 + $redirects);
202 $return->body = array_pop($response);
205 $headers = explode(
"\r\n", array_pop($response));
208 preg_match(
'/[0-9]{3}/', array_shift($headers), $matches);
210 $code = count($matches) ? $matches[0] : null;
212 if (is_numeric($code))
214 $return->code = (int) $code;
220 throw new UnexpectedValueException(
'No HTTP response code found.');
224 foreach ($headers as $header)
226 $pos = strpos($header,
':');
227 $return->headers[trim(substr($header, 0, $pos))] = trim(substr($header, ($pos + 1)));
240 public static function isSupported()
242 return function_exists(
'curl_version') && curl_version();