/**
* @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 PHP streams.
класс HTTP транспорт для использования P H P потоков.
*
* @package Joomla.Platform
* @subpackage HTTP
* @since 11.3
*/
class JHttpTransportStream 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)
{
// Verify that fopen() is available. Проверьте, что fopen () доступен.
if (!function_exists('fopen') || !is_callable('fopen'))
{
throw new RuntimeException('Cannot use a stream transport when fopen() is not available.');
}
// Verify that URLs can be used with fopen(); Убедитесь, что URLs может использоваться с fopen ();
if (!ini_get('allow_url_fopen'))
{
throw new RuntimeException('Cannot use a stream transport when "allow_url_fopen" is disabled.');
}
$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)
{
// Create the stream context options array with the required method offset.
// Создать массив параметров контекста потока с заданием внешнего метода.
$options = array('method' => strtoupper($method));
// 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 stream context options.
if (is_scalar($data))
{
$options['content'] = $data;
}
// Otherwise we need to encode the value first.
// Иначе мы должны закодировать значение сначала.
else
{
$options['content'] = http_build_query($data);
}
if (!isset($headers['Content-type']))
{
$headers['Content-type'] = 'application/x-www-form-urlencoded';
}
$headers['Content-length'] = strlen($options['content']);
}
// Build the headers string for the request.
// Создть строку заголовков для запроса.
$headerString = null;
if (isset($headers))
{
foreach ($headers as $key => $value)
{
$headerString .= $key . ': ' . $value . "\r\n";
}
// Add the headers string into the stream context options array.
// Добавить строку заголовков в массив параметров потокового контекста.
$options['header'] = trim($headerString, "\r\n");
}
// If an explicit timeout is given user it.
// Если было заданно время ожидания.
if (isset($timeout))
{
$options['timeout'] = (int) $timeout;
}
// If an explicit user agent is given use it.
// Если был задан юзер-агент
if (isset($userAgent))
{
$options['user_agent'] = $userAgent;
}
// Ignore HTTP errors so that we can capture them.
//Проигноровать ошибки HTTP, чтобы мы могли получить их.
$options['ignore_errors'] = 1;
// Create the stream context for the request.
// Создать потоковый контекст для запроса.
$context = stream_context_create(array('http' => $options));
// Open the stream for reading.
// Открыть поток для чтения.
$stream = fopen((string) $uri, 'r', false, $context);
// Get the metadata for the stream, including response headers.
//Получить метаданные для потока, включая заголовки ответа.
$metadata = stream_get_meta_data($stream);
// Get the contents from the stream.
//Получить контент из потока.
$content = stream_get_contents($stream);
// Close the stream.
// Закрыть поток.
fclose($stream);
return $this->getResponse($metadata['wrapper_data'], $content);
}
/**
* Method to get a response object from a server response.
Метод для получения объекта ответа из ответа сервера.
*
* @param array $headers The response headers as an array.
Заголовки ответа как массив.
* @param string $body The response body as a string.
Тело ответа как строка.
*
* @return JHttpResponse
*
* @since 11.3
* @throws UnexpectedValueException
*/
protected function getResponse(array $headers, $body)
{
// Create the response object.
// Создать объект ответа.
$return = new JHttpResponse;
// Set the body for the response.
// Установить тело ответа.
$return->body = $body;
// 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;
}
}