<?php
namespace Guzzle\Http\Curl;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Exception\RuntimeException;
use Guzzle\Common\Collection;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Parser\ParserRegistry;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Url;
class CurlHandle {
const BODY_AS_STRING = 'body_as_string';
const PROGRESS = 'progress';
const DEBUG = 'debug';
protected $options;
protected $handle;
protected $errorNo = CURLE_OK;
public static function factory(RequestInterface $request) {
$mediator = new RequestMediator($request);
$requestCurlOptions = $request
->getCurlOptions();
$tempContentLength = null;
$method = $request
->getMethod();
$bodyAsString = $requestCurlOptions
->get(self::BODY_AS_STRING);
$curlOptions = array(
CURLOPT_URL => $request
->getUrl(),
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => false,
CURLOPT_HEADER => false,
CURLOPT_USERAGENT => (string) $request
->getHeader('User-Agent'),
CURLOPT_PORT => $request
->getPort(),
CURLOPT_HTTPHEADER => array(),
CURLOPT_HEADERFUNCTION => array(
$mediator,
'receiveResponseHeader',
),
CURLOPT_HTTP_VERSION => $request
->getProtocolVersion() === '1.0' ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1,
CURLOPT_SSL_VERIFYPEER => 1,
CURLOPT_SSL_VERIFYHOST => 2,
);
if ($acceptEncodingHeader = $request
->getHeader('Accept-Encoding')) {
$curlOptions[CURLOPT_ENCODING] = (string) $acceptEncodingHeader;
$request
->removeHeader('Accept-Encoding');
}
if ($requestCurlOptions
->get('progress')) {
$curlOptions[CURLOPT_PROGRESSFUNCTION] = array(
$mediator,
'progress',
);
$curlOptions[CURLOPT_NOPROGRESS] = false;
}
if ($requestCurlOptions
->get('debug')) {
$curlOptions[CURLOPT_STDERR] = fopen('php://temp', 'r+');
if (false === $curlOptions[CURLOPT_STDERR]) {
throw new RuntimeException('Unable to create a stream for CURLOPT_STDERR');
}
$curlOptions[CURLOPT_VERBOSE] = true;
}
if ($method != 'HEAD') {
$curlOptions[CURLOPT_WRITEFUNCTION] = array(
$mediator,
'writeResponseBody',
);
}
switch ($method) {
case 'GET':
$curlOptions[CURLOPT_HTTPGET] = true;
break;
case 'HEAD':
$curlOptions[CURLOPT_NOBODY] = true;
break;
case 'POST':
$curlOptions[CURLOPT_POST] = true;
if (count($request
->getPostFiles())) {
$fields = $request
->getPostFields()
->useUrlEncoding(false)
->urlEncode();
foreach ($request
->getPostFiles() as $key => $data) {
$prefixKeys = count($data) > 1;
foreach ($data as $index => $file) {
$fieldKey = $prefixKeys ? "{$key}[{$index}]" : $key;
$fields[$fieldKey] = $file
->getCurlString();
}
}
$curlOptions[CURLOPT_POSTFIELDS] = $fields;
$request
->removeHeader('Content-Length');
}
elseif (count($request
->getPostFields())) {
$curlOptions[CURLOPT_POSTFIELDS] = (string) $request
->getPostFields()
->useUrlEncoding(true);
$request
->removeHeader('Content-Length');
}
elseif (!$request
->getBody()) {
unset($curlOptions[CURLOPT_POST]);
$curlOptions[CURLOPT_CUSTOMREQUEST] = 'POST';
}
break;
case 'PUT':
case 'PATCH':
case 'DELETE':
default:
$curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
if ($bodyAsString) {
if (!$request
->hasHeader('Content-Type')) {
$curlOptions[CURLOPT_HTTPHEADER][] = 'Content-Type:';
}
}
else {
$curlOptions[CURLOPT_UPLOAD] = true;
if ($tempContentLength = $request
->getHeader('Content-Length')) {
$tempContentLength = (int) (string) $tempContentLength;
$curlOptions[CURLOPT_INFILESIZE] = $tempContentLength;
}
}
}
if ($request instanceof EntityEnclosingRequestInterface) {
if ($request
->getBody()) {
if ($bodyAsString) {
$curlOptions[CURLOPT_POSTFIELDS] = (string) $request
->getBody();
if ($tempContentLength = $request
->getHeader('Content-Length')) {
$tempContentLength = (int) (string) $tempContentLength;
}
}
else {
$curlOptions[CURLOPT_READFUNCTION] = array(
$mediator,
'readRequestBody',
);
$request
->getBody()
->seek(0);
}
}
if (!$request
->hasHeader('Expect')) {
$curlOptions[CURLOPT_HTTPHEADER][] = 'Expect:';
}
}
if (null !== $tempContentLength) {
$request
->removeHeader('Content-Length');
}
foreach ($requestCurlOptions as $key => $value) {
if (is_numeric($key)) {
$curlOptions[$key] = $value;
}
}
if (!isset($curlOptions[CURLOPT_ENCODING])) {
$curlOptions[CURLOPT_HTTPHEADER][] = 'Accept:';
}
if ($blacklist = $requestCurlOptions
->get('blacklist')) {
foreach ($blacklist as $value) {
if (strpos($value, 'header.') !== 0) {
unset($curlOptions[$value]);
}
else {
$key = substr($value, 7);
$request
->removeHeader($key);
$curlOptions[CURLOPT_HTTPHEADER][] = $key . ':';
}
}
}
foreach ($request
->getHeaderLines() as $line) {
$curlOptions[CURLOPT_HTTPHEADER][] = $line;
}
$handle = curl_init();
curl_setopt_array($handle, $curlOptions);
if ($tempContentLength) {
$request
->setHeader('Content-Length', $tempContentLength);
}
$handle = new static($handle, $curlOptions);
$mediator
->setCurlHandle($handle);
return $handle;
}
public function __construct($handle, $options) {
if (!is_resource($handle)) {
throw new InvalidArgumentException('Invalid handle provided');
}
if (is_array($options)) {
$this->options = new Collection($options);
}
elseif ($options instanceof Collection) {
$this->options = $options;
}
else {
throw new InvalidArgumentException('Expected array or Collection');
}
$this->handle = $handle;
}
public function __destruct() {
$this
->close();
}
public function close() {
if (is_resource($this->handle)) {
curl_close($this->handle);
}
$this->handle = null;
}
public function isAvailable() {
return is_resource($this->handle);
}
public function getError() {
return $this
->isAvailable() ? curl_error($this->handle) : '';
}
public function getErrorNo() {
if ($this->errorNo) {
return $this->errorNo;
}
return $this
->isAvailable() ? curl_errno($this->handle) : CURLE_OK;
}
public function setErrorNo($error) {
$this->errorNo = $error;
return $this;
}
public function getInfo($option = null) {
if (!is_resource($this->handle)) {
return null;
}
if (null !== $option) {
return curl_getinfo($this->handle, $option) ?: null;
}
return curl_getinfo($this->handle) ?: array();
}
public function getStderr($asResource = false) {
$stderr = $this
->getOptions()
->get(CURLOPT_STDERR);
if (!$stderr) {
return null;
}
if ($asResource) {
return $stderr;
}
fseek($stderr, 0);
$e = stream_get_contents($stderr);
fseek($stderr, 0, SEEK_END);
return $e;
}
public function getUrl() {
return Url::factory($this->options
->get(CURLOPT_URL));
}
public function getHandle() {
return $this
->isAvailable() ? $this->handle : null;
}
public function getOptions() {
return $this->options;
}
public function updateRequestFromTransfer(RequestInterface $request) {
if (!$request
->getResponse()) {
return;
}
$request
->getResponse()
->setInfo($this
->getInfo());
if (!($log = $this
->getStderr(true))) {
return;
}
$headers = '';
fseek($log, 0);
while (($line = fgets($log)) !== false) {
if ($line && $line[0] == '>') {
$headers = substr(trim($line), 2) . "\r\n";
while (($line = fgets($log)) !== false) {
if ($line[0] == '*' || $line[0] == '<') {
break;
}
else {
$headers .= trim($line) . "\r\n";
}
}
}
}
if ($headers) {
$parsed = ParserRegistry::getInstance()
->getParser('message')
->parseRequest($headers);
if (!empty($parsed['headers'])) {
$request
->setHeaders(array());
foreach ($parsed['headers'] as $name => $value) {
$request
->setHeader($name, $value);
}
}
if (!empty($parsed['version'])) {
$request
->setProtocolVersion($parsed['version']);
}
}
}
public static function parseCurlConfig($config) {
$curlOptions = array();
foreach ($config as $key => $value) {
if (!is_numeric($key) && defined($key)) {
$key = constant($key);
}
$curlOptions[$key] = is_string($value) && defined($value) ? constant($value) : $value;
}
return $curlOptions;
}
}