This commit is contained in:
2022-03-10 12:34:30 -05:00
parent 81f0c4c233
commit 346073b544
101 changed files with 12902 additions and 0 deletions
@@ -0,0 +1,316 @@
<?php
/*!
* Hybridauth
* https://hybridauth.github.io | https://github.com/hybridauth/hybridauth
* (c) 2017 Hybridauth authors | https://hybridauth.github.io/license.html
*/
namespace Hybridauth\HttpClient;
/**
* Hybridauth default Http client
*/
class Curl implements HttpClientInterface
{
/**
* Default curl options
*
* These defaults options can be overwritten when sending requests.
*
* See setCurlOptions()
*
* @var array
*/
protected $curlOptions = [
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLINFO_HEADER_OUT => true,
CURLOPT_ENCODING => 'identity',
// phpcs:ignore
CURLOPT_USERAGENT => 'Hybridauth, PHP Social Authentication Library (https://github.com/hybridauth/hybridauth)',
];
/**
* Method request() arguments
*
* This is used for debugging.
*
* @var array
*/
protected $requestArguments = [];
/**
* Default request headers
*
* @var array
*/
protected $requestHeader = [
'Accept' => '*/*',
'Cache-Control' => 'max-age=0',
'Connection' => 'keep-alive',
'Expect' => '',
'Pragma' => '',
];
/**
* Raw response returned by server
*
* @var string
*/
protected $responseBody = '';
/**
* Headers returned in the response
*
* @var array
*/
protected $responseHeader = [];
/**
* Response HTTP status code
*
* @var int
*/
protected $responseHttpCode = 0;
/**
* Last curl error number
*
* @var mixed
*/
protected $responseClientError = null;
/**
* Information about the last transfer
*
* @var mixed
*/
protected $responseClientInfo = [];
/**
* Hybridauth logger instance
*
* @var object
*/
protected $logger = null;
/**
* {@inheritdoc}
*/
public function request($uri, $method = 'GET', $parameters = [], $headers = [], $multipart = false)
{
$this->requestHeader = array_replace($this->requestHeader, (array)$headers);
$this->requestArguments = [
'uri' => $uri,
'method' => $method,
'parameters' => $parameters,
'headers' => $this->requestHeader,
];
$curl = curl_init();
switch ($method) {
case 'GET':
case 'DELETE':
unset($this->curlOptions[CURLOPT_POST]);
unset($this->curlOptions[CURLOPT_POSTFIELDS]);
$uri = $uri . (strpos($uri, '?') ? '&' : '?') . http_build_query($parameters);
if ($method === 'DELETE') {
$this->curlOptions[CURLOPT_CUSTOMREQUEST] = 'DELETE';
}
break;
case 'PUT':
case 'POST':
case 'PATCH':
$body_content = $multipart ? $parameters : http_build_query($parameters);
if (isset($this->requestHeader['Content-Type'])
&& $this->requestHeader['Content-Type'] == 'application/json'
) {
$body_content = json_encode($parameters);
}
if ($method === 'POST') {
$this->curlOptions[CURLOPT_POST] = true;
} else {
$this->curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
}
$this->curlOptions[CURLOPT_POSTFIELDS] = $body_content;
break;
}
$this->curlOptions[CURLOPT_URL] = $uri;
$this->curlOptions[CURLOPT_HTTPHEADER] = $this->prepareRequestHeaders();
$this->curlOptions[CURLOPT_HEADERFUNCTION] = [$this, 'fetchResponseHeader'];
foreach ($this->curlOptions as $opt => $value) {
curl_setopt($curl, $opt, $value);
}
$response = curl_exec($curl);
$this->responseBody = $response;
$this->responseHttpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$this->responseClientError = curl_error($curl);
$this->responseClientInfo = curl_getinfo($curl);
if ($this->logger) {
// phpcs:ignore
$this->logger->debug(sprintf('%s::request( %s, %s ), response:', get_class($this), $uri, $method), $this->getResponse());
if (false === $response) {
// phpcs:ignore
$this->logger->error(sprintf('%s::request( %s, %s ), error:', get_class($this), $uri, $method), [$this->responseClientError]);
}
}
curl_close($curl);
return $this->responseBody;
}
/**
* Get response details
*
* @return array Map structure of details
*/
public function getResponse()
{
$curlOptions = $this->curlOptions;
$curlOptions[CURLOPT_HEADERFUNCTION] = '*omitted';
return [
'request' => $this->getRequestArguments(),
'response' => [
'code' => $this->getResponseHttpCode(),
'headers' => $this->getResponseHeader(),
'body' => $this->getResponseBody(),
],
'client' => [
'error' => $this->getResponseClientError(),
'info' => $this->getResponseClientInfo(),
'opts' => $curlOptions,
],
];
}
/**
* Reset curl options
*
* @param array $curlOptions
*/
public function setCurlOptions($curlOptions)
{
foreach ($curlOptions as $opt => $value) {
$this->curlOptions[$opt] = $value;
}
}
/**
* Set logger instance
*
* @param object $logger
*/
public function setLogger($logger)
{
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function getResponseBody()
{
return $this->responseBody;
}
/**
* {@inheritdoc}
*/
public function getResponseHeader()
{
return $this->responseHeader;
}
/**
* {@inheritdoc}
*/
public function getResponseHttpCode()
{
return $this->responseHttpCode;
}
/**
* {@inheritdoc}
*/
public function getResponseClientError()
{
return $this->responseClientError;
}
/**
* @return array
*/
protected function getResponseClientInfo()
{
return $this->responseClientInfo;
}
/**
* Returns method request() arguments
*
* This is used for debugging.
*
* @return array
*/
protected function getRequestArguments()
{
return $this->requestArguments;
}
/**
* Fetch server response headers
*
* @param mixed $curl
* @param string $header
*
* @return int
*/
protected function fetchResponseHeader($curl, $header)
{
$pos = strpos($header, ':');
if (!empty($pos)) {
$key = str_replace('-', '_', strtolower(substr($header, 0, $pos)));
$value = trim(substr($header, $pos + 2));
$this->responseHeader[$key] = $value;
}
return strlen($header);
}
/**
* Convert request headers to the expect curl format
*
* @return array
*/
protected function prepareRequestHeaders()
{
$headers = [];
foreach ($this->requestHeader as $header => $value) {
$headers[] = trim($header) . ': ' . trim($value);
}
return $headers;
}
}
@@ -0,0 +1,276 @@
<?php
/*!
* Hybridauth
* https://hybridauth.github.io | https://github.com/hybridauth/hybridauth
* (c) 2017 Hybridauth authors | https://hybridauth.github.io/license.html
*/
namespace Hybridauth\HttpClient;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\TransferException;
/**
* Hybridauth Guzzle Http client
*
* Note: This is just a proof of concept. Feel free to improve it.
*
* Example:
*
* <code>
* $guzzle = new Hybridauth\HttpClient\Guzzle(new GuzzleHttp\Client(), [
* 'verify' => '/path/to/your/certificate.crt',
* 'headers' => ['User-Agent' => '..']
* // 'proxy' => ...
* ]);
*
* $adapter = new Hybridauth\Provider\Github($config, $guzzle);
*
* $adapter->authenticate();
* </code>
*/
class Guzzle implements HttpClientInterface
{
/**
* Method request() arguments
*
* This is used for debugging.
*
* @var array
*/
protected $requestArguments = [];
/**
* Default request headers
*
* @var array
*/
protected $requestHeader = [];
/**
* Raw response returned by server
*
* @var string
*/
protected $responseBody = '';
/**
* Headers returned in the response
*
* @var array
*/
protected $responseHeader = [];
/**
* Response HTTP status code
*
* @var int
*/
protected $responseHttpCode = 0;
/**
* Last curl error number
*
* @var mixed
*/
protected $responseClientError = null;
/**
* Information about the last transfer
*
* @var mixed
*/
protected $responseClientInfo = [];
/**
* Hybridauth logger instance
*
* @var object
*/
protected $logger = null;
/**
* GuzzleHttp client
*
* @var \GuzzleHttp\Client
*/
protected $client = null;
/**
* ..
* @param null $client
* @param array $config
*/
public function __construct($client = null, $config = [])
{
$this->client = $client ? $client : new Client($config);
}
/**
* {@inheritdoc}
*/
public function request($uri, $method = 'GET', $parameters = [], $headers = [], $multipart = false)
{
$this->requestHeader = array_replace($this->requestHeader, (array)$headers);
$this->requestArguments = [
'uri' => $uri,
'method' => $method,
'parameters' => $parameters,
'headers' => $this->requestHeader,
];
$response = null;
try {
switch ($method) {
case 'GET':
case 'DELETE':
$response = $this->client->request($method, $uri, [
'query' => $parameters,
'headers' => $this->requestHeader,
]);
break;
case 'PUT':
case 'PATCH':
case 'POST':
$body_type = $multipart ? 'multipart' : 'form_params';
if (isset($this->requestHeader['Content-Type'])
&& $this->requestHeader['Content-Type'] === 'application/json'
) {
$body_type = 'json';
}
$body_content = $parameters;
if ($multipart) {
$body_content = [];
foreach ($parameters as $key => $val) {
if ($val instanceof \CURLFile) {
$val = fopen($val->getFilename(), 'r');
}
$body_content[] = [
'name' => $key,
'contents' => $val,
];
}
}
$response = $this->client->request($method, $uri, [
$body_type => $body_content,
'headers' => $this->requestHeader,
]);
break;
}
} catch (\Exception $e) {
$response = $e->getResponse();
$this->responseClientError = $e->getMessage();
}
if (!$this->responseClientError) {
$this->responseBody = $response->getBody();
$this->responseHttpCode = $response->getStatusCode();
$this->responseHeader = $response->getHeaders();
}
if ($this->logger) {
// phpcs:ignore
$this->logger->debug(sprintf('%s::request( %s, %s ), response:', get_class($this), $uri, $method), $this->getResponse());
if ($this->responseClientError) {
// phpcs:ignore
$this->logger->error(sprintf('%s::request( %s, %s ), error:', get_class($this), $uri, $method), [$this->responseClientError]);
}
}
return $this->responseBody;
}
/**
* Get response details
*
* @return array Map structure of details
*/
public function getResponse()
{
return [
'request' => $this->getRequestArguments(),
'response' => [
'code' => $this->getResponseHttpCode(),
'headers' => $this->getResponseHeader(),
'body' => $this->getResponseBody(),
],
'client' => [
'error' => $this->getResponseClientError(),
'info' => $this->getResponseClientInfo(),
'opts' => null,
],
];
}
/**
* Set logger instance
*
* @param object $logger
*/
public function setLogger($logger)
{
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function getResponseBody()
{
return $this->responseBody;
}
/**
* {@inheritdoc}
*/
public function getResponseHeader()
{
return $this->responseHeader;
}
/**
* {@inheritdoc}
*/
public function getResponseHttpCode()
{
return $this->responseHttpCode;
}
/**
* {@inheritdoc}
*/
public function getResponseClientError()
{
return $this->responseClientError;
}
/**
* @return array
*/
protected function getResponseClientInfo()
{
return $this->responseClientInfo;
}
/**
* Returns method request() arguments
*
* This is used for debugging.
*
* @return array
*/
protected function getRequestArguments()
{
return $this->requestArguments;
}
}
@@ -0,0 +1,58 @@
<?php
/*!
* Hybridauth
* https://hybridauth.github.io | https://github.com/hybridauth/hybridauth
* (c) 2017 Hybridauth authors | https://hybridauth.github.io/license.html
*/
namespace Hybridauth\HttpClient;
/**
* Hybridauth Http clients interface
*/
interface HttpClientInterface
{
/**
* Send request to the remote server
*
* Returns the result (Raw response from the server) on success, FALSE on failure
*
* @param string $uri
* @param string $method
* @param array $parameters
* @param array $headers
* @param bool $multipart
*
* @return mixed
*/
public function request($uri, $method = 'GET', $parameters = [], $headers = [], $multipart = false);
/**
* Returns raw response from the server on success, FALSE on failure
*
* @return mixed
*/
public function getResponseBody();
/**
* Retriever the headers returned in the response
*
* @return array
*/
public function getResponseHeader();
/**
* Returns latest request HTTP status code
*
* @return int
*/
public function getResponseHttpCode();
/**
* Returns latest error encountered by the client
* This can be either a code or error message
*
* @return mixed
*/
public function getResponseClientError();
}
@@ -0,0 +1,100 @@
<?php
/*!
* Hybridauth
* https://hybridauth.github.io | https://github.com/hybridauth/hybridauth
* (c) 2017 Hybridauth authors | https://hybridauth.github.io/license.html
*/
namespace Hybridauth\HttpClient;
use Hybridauth\Data;
/**
* HttpClient\Util home to a number of utility functions.
*/
class Util
{
/**
* Redirect handler.
*
* @var callable|null
*/
protected static $redirectHandler;
/**
* Exit handler.
*
* @var callable|null
*/
protected static $exitHandler;
/**
* Redirect to a given URL.
*
* In case your application need to perform certain required actions before Hybridauth redirect users
* to IDPs websites, the default behaviour can be altered in one of two ways:
* If callable $redirectHandler is defined, it will be called instead.
* If callable $exitHandler is defined, it will be called instead of exit().
*
* @param string $url
*
* @return mixed
*/
public static function redirect($url)
{
if (static::$redirectHandler) {
return call_user_func(static::$redirectHandler, $url);
}
header(sprintf('Location: %s', $url));
if (static::$exitHandler) {
return call_user_func(static::$exitHandler);
}
exit(1);
}
/**
* Redirect handler to which the regular redirect() will yield the action of redirecting users.
*
* @param callable $callback
*/
public static function setRedirectHandler($callback)
{
self::$redirectHandler = $callback;
}
/**
* Exit handler will be called instead of regular exit() when calling Util::redirect() method.
*
* @param callable $callback
*/
public static function setExitHandler($callback)
{
self::$exitHandler = $callback;
}
/**
* Returns the Current URL.
*
* @param bool $requestUri TRUE to use $_SERVER['REQUEST_URI'], FALSE for $_SERVER['PHP_SELF']
*
* @return string
*/
public static function getCurrentUrl($requestUri = false)
{
$collection = new Data\Collection($_SERVER);
$protocol = 'http://';
if (($collection->get('HTTPS') && $collection->get('HTTPS') !== 'off') ||
$collection->get('HTTP_X_FORWARDED_PROTO') === 'https') {
$protocol = 'https://';
}
return $protocol .
$collection->get('HTTP_HOST') .
$collection->get($requestUri ? 'REQUEST_URI' : 'PHP_SELF');
}
}