/**
* @package Joomla.Platform
* @subpackage HTTP
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die();
/**
* HTTP transport class for using cURL.
класс HTTP транспорт для использования c cURL.
*
* @package Joomla.Platform
* @subpackage HTTP
* @since 11.3
*/
class JHttpTransportCurl implements JHttpTransport
{
/**
* @var JRegistry The client options.
* @since 11.3
*/
protected $options;
/**
* Constructor. Конструктор.
*
* @param JRegistry &$options Client options object.
Объект Параметры клиента.
*
* @since 11.3
* @throws RuntimeException
*/
public function __construct(JRegistry &$options)
{
if (!function_exists('curl_init') || !is_callable('curl_init'))
{
throw new RuntimeException('Cannot use a cURL transport when curl_init() is not available.');
}
$this->options = $options;
}
/**
* Send a request to the server and return a JHttpResponse object with the response.
Отправить запрос на сервер и возвращает объект JHttpResponse с ответом.
*
* @param string $method The HTTP method for sending the request.
HTTP метод для отправки запроса.
* @param JUri $uri The URI to the resource to request.
URI ресурса для запроса.
* @param mixed $data Either an associative array or a string to be sent with the request.
Ассоциативный массив или строка, отправляемая с запросом.
* @param array $headers An array of request headers to send with the request.
Массив заголовков запроса для отправки с запросом.
* @param integer $timeout Read timeout in seconds.
Тайм-аут читения в секундах.
* @param string $userAgent The optional user agent string to send with the request.
Строка юзер-агента необязательное для отправки с запросом.
*
* @return JHttpResponse
*
* @since 11.3
*/
public function request($method, JUri $uri, $data = null, array $headers = null, $timeout = null, $userAgent = null)
{
// Setup the cURL handle.
// Установить cURL дескриптор.
$ch = curl_init();
// Set the request method.
// Установить метод запроса.
$options[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
// Initialize the certificate store
//Инициализировать хранилище сертификата
$options[CURLOPT_CAINFO] = dirname(__FILE__) . '/cacert.pem';
// If data exists let's encode it and make sure our Content-type header is set.
// Если данные существуют, закодируем их и удостоверимся, что заголовок Типа контента устанавливается.
if (isset($data))
{
// If the data is a scalar value simply add it to the cURL post fields.
//Если данные - скалярное значение, просто добавим их к cURL полям сообщения.
if (is_scalar($data))
{
$options[CURLOPT_POSTFIELDS] = $data;
}
// Otherwise we need to encode the value first.
// Иначе мы должны сначала закодировать значение.
else
{
$options[CURLOPT_POSTFIELDS] = http_build_query($data);
}
if (!isset($headers['Content-type']))
{
$headers['Content-type'] = 'application/x-www-form-urlencoded';
}
$headers['Content-length'] = strlen($options[CURLOPT_POSTFIELDS]);
}
// Build the headers string for the request.
// Создать строку заголовков для запроса.
$headerArray = array();
if (isset($headers))
{
foreach ($headers as $key => $value)
{
$headerArray[] = $key . ': ' . $value;
}
// Add the headers string into the stream context options array.
// Добавить строку заголовков в массив опций потокового контекста.
$options[CURLOPT_HTTPHEADER] = $headerArray;
}
// If an explicit timeout is given user it.
// Если явно заданно времея ожидания используем его.
if (isset($timeout))
{
$options[CURLOPT_TIMEOUT] = (int) $timeout;
$options[CURLOPT_CONNECTTIMEOUT] = (int) $timeout;
}
// If an explicit user agent is given use it.
// Если явно заданн юзер-агент используем его.
if (isset($userAgent))
{
$headers[CURLOPT_USERAGENT] = $userAgent;
}
// Set the request URL.
// Установить запрос URL.
$options[CURLOPT_URL] = (string) $uri;
// We want our headers. :-)
// Мы хотим наши заголовки. :-)
$options[CURLOPT_HEADER] = true;
// Return it... echoing it would be tacky.
// Возврат... эхом он будет липким.
$options[CURLOPT_RETURNTRANSFER] = true;
// Set the cURL options.
// Установить cURL параметры.
curl_setopt_array($ch, $options);
// Execute the request and close the connection.
//Выполнить запрос и закройте соединение.
$content = curl_exec($ch);
curl_close($ch);
return $this->getResponse($content);
}
/**
* Method to get a response object from a server response.
Метод для получения объекта ответа из ответа сервера.
*
* @param string $content The complete server response, including headers.
Полный ответ сервера, включая заголовки.
*
* @return JHttpResponse
*
* @since 11.3
* @throws UnexpectedValueException
*/
protected function getResponse($content)
{
// Create the response object.
// Создать объект ответа.
$return = new JHttpResponse;
// Split the response into headers and body.
// Разделить ответ на заголовки и тело.
$response = explode("\r\n\r\n", $content, 2);
// Get the response headers as an array.
// Получить заголовки ответа как массив.
$headers = explode("\r\n", $response[0]);
// Set the body for the response.
// Установить тело для ответа.
$return->body = $response[1];
// Get the response code from the first offset of the response headers.
// Получить код ответа взяв первый заголовок ответа.
preg_match('/[0-9]{3}/', array_shift($headers), $matches);
$code = $matches[0];
if (is_numeric($code))
{
$return->code = (int) $code;
}
// No valid response code was detected.
// Допустимый код ответа не был обнаружен.
else
{
throw new UnexpectedValueException('No HTTP response code found.');
}
// Add the response headers to the response object.
// Добавить заголовки ответа к объекту ответа.
foreach ($headers as $header)
{
$pos = strpos($header, ':');
$return->headers[trim(substr($header, 0, $pos))] = trim(substr($header, ($pos + 1)));
}
return $return;
}
}