Ajout du FR

Ajout du FR + correction du "functions.php"
This commit is contained in:
Gauvain Boiché
2020-03-30 14:52:34 +02:00
commit 5e4c5f9418
4541 changed files with 608941 additions and 0 deletions

View File

@@ -0,0 +1,81 @@
<?php
namespace OAuth\Common;
/**
* PSR-0 Autoloader
*
* @author ieter Hordijk <info@pieterhordijk.com>
*/
class AutoLoader
{
/**
* @var string The namespace prefix for this instance.
*/
protected $namespace = '';
/**
* @var string The filesystem prefix to use for this instance
*/
protected $path = '';
/**
* Build the instance of the autoloader
*
* @param string $namespace The prefixed namespace this instance will load
* @param string $path The filesystem path to the root of the namespace
*/
public function __construct($namespace, $path)
{
$this->namespace = ltrim($namespace, '\\');
$this->path = rtrim($path, '/\\') . DIRECTORY_SEPARATOR;
}
/**
* Try to load a class
*
* @param string $class The class name to load
*
* @return boolean If the loading was successful
*/
public function load($class)
{
$class = ltrim($class, '\\');
if (strpos($class, $this->namespace) === 0) {
$nsparts = explode('\\', $class);
$class = array_pop($nsparts);
$nsparts[] = '';
$path = $this->path . implode(DIRECTORY_SEPARATOR, $nsparts);
$path .= str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
if (file_exists($path)) {
require $path;
return true;
}
}
return false;
}
/**
* Register the autoloader to PHP
*
* @return boolean The status of the registration
*/
public function register()
{
return spl_autoload_register(array($this, 'load'));
}
/**
* Unregister the autoloader to PHP
*
* @return boolean The status of the unregistration
*/
public function unregister()
{
return spl_autoload_unregister(array($this, 'load'));
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace OAuth\Common\Consumer;
/**
* Value object for the credentials of an OAuth service.
*/
class Credentials implements CredentialsInterface
{
/**
* @var string
*/
protected $consumerId;
/**
* @var string
*/
protected $consumerSecret;
/**
* @var string
*/
protected $callbackUrl;
/**
* @param string $consumerId
* @param string $consumerSecret
* @param string $callbackUrl
*/
public function __construct($consumerId, $consumerSecret, $callbackUrl)
{
$this->consumerId = $consumerId;
$this->consumerSecret = $consumerSecret;
$this->callbackUrl = $callbackUrl;
}
/**
* @return string
*/
public function getCallbackUrl()
{
return $this->callbackUrl;
}
/**
* @return string
*/
public function getConsumerId()
{
return $this->consumerId;
}
/**
* @return string
*/
public function getConsumerSecret()
{
return $this->consumerSecret;
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace OAuth\Common\Consumer;
/**
* Credentials Interface, credentials should implement this.
*/
interface CredentialsInterface
{
/**
* @return string
*/
public function getCallbackUrl();
/**
* @return string
*/
public function getConsumerId();
/**
* @return string
*/
public function getConsumerSecret();
}

View File

@@ -0,0 +1,10 @@
<?php
namespace OAuth\Common\Exception;
/**
* Generic library-level exception.
*/
class Exception extends \Exception
{
}

View File

@@ -0,0 +1,73 @@
<?php
namespace OAuth\Common\Http\Client;
/**
* Abstract HTTP client
*/
abstract class AbstractClient implements ClientInterface
{
/**
* @var string The user agent string passed to services
*/
protected $userAgent;
/**
* @var int The maximum number of redirects
*/
protected $maxRedirects = 5;
/**
* @var int The maximum timeout
*/
protected $timeout = 15;
/**
* Creates instance
*
* @param string $userAgent The UA string the client will use
*/
public function __construct($userAgent = 'PHPoAuthLib')
{
$this->userAgent = $userAgent;
}
/**
* @param int $redirects Maximum redirects for client
*
* @return ClientInterface
*/
public function setMaxRedirects($redirects)
{
$this->maxRedirects = $redirects;
return $this;
}
/**
* @param int $timeout Request timeout time for client in seconds
*
* @return ClientInterface
*/
public function setTimeout($timeout)
{
$this->timeout = $timeout;
return $this;
}
/**
* @param array $headers
*/
public function normalizeHeaders(&$headers)
{
// Normalize headers
array_walk(
$headers,
function (&$val, &$key) {
$key = ucfirst(strtolower($key));
$val = ucfirst(strtolower($key)) . ': ' . $val;
}
);
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace OAuth\Common\Http\Client;
use OAuth\Common\Http\Uri\UriInterface;
use OAuth\Common\Http\Exception\TokenResponseException;
/**
* Any HTTP clients to be used with the library should implement this interface.
*/
interface ClientInterface
{
/**
* Any implementing HTTP providers should send a request to the provided endpoint with the parameters.
* They should return, in string form, the response body and throw an exception on error.
*
* @param UriInterface $endpoint
* @param mixed $requestBody
* @param array $extraHeaders
* @param string $method
*
* @return string
*
* @throws TokenResponseException
*/
public function retrieveResponse(
UriInterface $endpoint,
$requestBody,
array $extraHeaders = array(),
$method = 'POST'
);
}

View File

@@ -0,0 +1,142 @@
<?php
namespace OAuth\Common\Http\Client;
use OAuth\Common\Http\Exception\TokenResponseException;
use OAuth\Common\Http\Uri\UriInterface;
/**
* Client implementation for cURL
*/
class CurlClient extends AbstractClient
{
/**
* If true, explicitly sets cURL to use SSL version 3. Use this if cURL
* compiles with GnuTLS SSL.
*
* @var bool
*/
private $forceSSL3 = false;
/**
* Additional parameters (as `key => value` pairs) to be passed to `curl_setopt`
*
* @var array
*/
private $parameters = array();
/**
* Additional `curl_setopt` parameters
*
* @param array $parameters
*/
public function setCurlParameters(array $parameters)
{
$this->parameters = $parameters;
}
/**
* @param bool $force
*
* @return CurlClient
*/
public function setForceSSL3($force)
{
$this->forceSSL3 = $force;
return $this;
}
/**
* Any implementing HTTP providers should send a request to the provided endpoint with the parameters.
* They should return, in string form, the response body and throw an exception on error.
*
* @param UriInterface $endpoint
* @param mixed $requestBody
* @param array $extraHeaders
* @param string $method
*
* @return string
*
* @throws TokenResponseException
* @throws \InvalidArgumentException
*/
public function retrieveResponse(
UriInterface $endpoint,
$requestBody,
array $extraHeaders = array(),
$method = 'POST'
) {
// Normalize method name
$method = strtoupper($method);
$this->normalizeHeaders($extraHeaders);
if ($method === 'GET' && !empty($requestBody)) {
throw new \InvalidArgumentException('No body expected for "GET" request.');
}
if (!isset($extraHeaders['Content-Type']) && $method === 'POST' && is_array($requestBody)) {
$extraHeaders['Content-Type'] = 'Content-Type: application/x-www-form-urlencoded';
}
$extraHeaders['Host'] = 'Host: '.$endpoint->getHost();
$extraHeaders['Connection'] = 'Connection: close';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint->getAbsoluteUri());
if ($method === 'POST' || $method === 'PUT') {
if ($requestBody && is_array($requestBody)) {
$requestBody = http_build_query($requestBody, '', '&');
}
if ($method === 'PUT') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
} else {
curl_setopt($ch, CURLOPT_POST, true);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
} else {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
}
if ($this->maxRedirects > 0) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, $this->maxRedirects);
}
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $extraHeaders);
curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
foreach ($this->parameters as $key => $value) {
curl_setopt($ch, $key, $value);
}
if ($this->forceSSL3) {
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
}
$response = curl_exec($ch);
$responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (false === $response) {
$errNo = curl_errno($ch);
$errStr = curl_error($ch);
curl_close($ch);
if (empty($errStr)) {
throw new TokenResponseException('Failed to request resource.', $responseCode);
}
throw new TokenResponseException('cURL Error # '.$errNo.': '.$errStr, $responseCode);
}
curl_close($ch);
return $response;
}
}

View File

@@ -0,0 +1,95 @@
<?php
namespace OAuth\Common\Http\Client;
use OAuth\Common\Http\Exception\TokenResponseException;
use OAuth\Common\Http\Uri\UriInterface;
/**
* Client implementation for streams/file_get_contents
*/
class StreamClient extends AbstractClient
{
/**
* Any implementing HTTP providers should send a request to the provided endpoint with the parameters.
* They should return, in string form, the response body and throw an exception on error.
*
* @param UriInterface $endpoint
* @param mixed $requestBody
* @param array $extraHeaders
* @param string $method
*
* @return string
*
* @throws TokenResponseException
* @throws \InvalidArgumentException
*/
public function retrieveResponse(
UriInterface $endpoint,
$requestBody,
array $extraHeaders = array(),
$method = 'POST'
) {
// Normalize method name
$method = strtoupper($method);
$this->normalizeHeaders($extraHeaders);
if ($method === 'GET' && !empty($requestBody)) {
throw new \InvalidArgumentException('No body expected for "GET" request.');
}
if (!isset($extraHeaders['Content-Type']) && $method === 'POST' && is_array($requestBody)) {
$extraHeaders['Content-Type'] = 'Content-Type: application/x-www-form-urlencoded';
}
$host = 'Host: '.$endpoint->getHost();
// Append port to Host if it has been specified
if ($endpoint->hasExplicitPortSpecified()) {
$host .= ':'.$endpoint->getPort();
}
$extraHeaders['Host'] = $host;
$extraHeaders['Connection'] = 'Connection: close';
if (is_array($requestBody)) {
$requestBody = http_build_query($requestBody, '', '&');
}
$extraHeaders['Content-length'] = 'Content-length: '.strlen($requestBody);
$context = $this->generateStreamContext($requestBody, $extraHeaders, $method);
$level = error_reporting(0);
$response = file_get_contents($endpoint->getAbsoluteUri(), false, $context);
error_reporting($level);
if (false === $response) {
$lastError = error_get_last();
if (is_null($lastError)) {
throw new TokenResponseException(
'Failed to request resource. HTTP Code: ' .
((isset($http_response_header[0]))?$http_response_header[0]:'No response')
);
}
throw new TokenResponseException($lastError['message']);
}
return $response;
}
private function generateStreamContext($body, $headers, $method)
{
return stream_context_create(
array(
'http' => array(
'method' => $method,
'header' => implode("\r\n", array_values($headers)),
'content' => $body,
'protocol_version' => '1.1',
'user_agent' => $this->userAgent,
'max_redirects' => $this->maxRedirects,
'timeout' => $this->timeout
),
)
);
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace OAuth\Common\Http\Exception;
use OAuth\Common\Exception\Exception;
/**
* Exception relating to token response from service.
*/
class TokenResponseException extends Exception
{
}

View File

@@ -0,0 +1,408 @@
<?php
namespace OAuth\Common\Http\Uri;
use InvalidArgumentException;
/**
* Standards-compliant URI class.
*/
class Uri implements UriInterface
{
/**
* @var string
*/
private $scheme = 'http';
/**
* @var string
*/
private $userInfo = '';
/**
* @var string
*/
private $rawUserInfo = '';
/**
* @var string
*/
private $host;
/**
* @var int
*/
private $port = 80;
/**
* @var string
*/
private $path = '/';
/**
* @var string
*/
private $query = '';
/**
* @var string
*/
private $fragment = '';
/**
* @var bool
*/
private $explicitPortSpecified = false;
/**
* @var bool
*/
private $explicitTrailingHostSlash = false;
/**
* @param string $uri
*/
public function __construct($uri = null)
{
if (null !== $uri) {
$this->parseUri($uri);
}
}
/**
* @param string $uri
*
* @throws \InvalidArgumentException
*/
protected function parseUri($uri)
{
if (false === ($uriParts = parse_url($uri))) {
// congratulations if you've managed to get parse_url to fail,
// it seems to always return some semblance of a parsed url no matter what
throw new InvalidArgumentException("Invalid URI: $uri");
}
if (!isset($uriParts['scheme'])) {
throw new InvalidArgumentException('Invalid URI: http|https scheme required');
}
$this->scheme = $uriParts['scheme'];
$this->host = $uriParts['host'];
if (isset($uriParts['port'])) {
$this->port = $uriParts['port'];
$this->explicitPortSpecified = true;
} else {
$this->port = strcmp('https', $uriParts['scheme']) ? 80 : 443;
$this->explicitPortSpecified = false;
}
if (isset($uriParts['path'])) {
$this->path = $uriParts['path'];
if ('/' === $uriParts['path']) {
$this->explicitTrailingHostSlash = true;
}
} else {
$this->path = '/';
}
$this->query = isset($uriParts['query']) ? $uriParts['query'] : '';
$this->fragment = isset($uriParts['fragment']) ? $uriParts['fragment'] : '';
$userInfo = '';
if (!empty($uriParts['user'])) {
$userInfo .= $uriParts['user'];
}
if ($userInfo && !empty($uriParts['pass'])) {
$userInfo .= ':' . $uriParts['pass'];
}
$this->setUserInfo($userInfo);
}
/**
* @param string $rawUserInfo
*
* @return string
*/
protected function protectUserInfo($rawUserInfo)
{
$colonPos = strpos($rawUserInfo, ':');
// rfc3986-3.2.1 | http://tools.ietf.org/html/rfc3986#section-3.2
// "Applications should not render as clear text any data
// after the first colon (":") character found within a userinfo
// subcomponent unless the data after the colon is the empty string
// (indicating no password)"
if ($colonPos !== false && strlen($rawUserInfo)-1 > $colonPos) {
return substr($rawUserInfo, 0, $colonPos) . ':********';
} else {
return $rawUserInfo;
}
}
/**
* @return string
*/
public function getScheme()
{
return $this->scheme;
}
/**
* @return string
*/
public function getUserInfo()
{
return $this->userInfo;
}
/**
* @return string
*/
public function getRawUserInfo()
{
return $this->rawUserInfo;
}
/**
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* @return int
*/
public function getPort()
{
return $this->port;
}
/**
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* @return string
*/
public function getQuery()
{
return $this->query;
}
/**
* @return string
*/
public function getFragment()
{
return $this->fragment;
}
/**
* Uses protected user info by default as per rfc3986-3.2.1
* Uri::getRawAuthority() is available if plain-text password information is desirable.
*
* @return string
*/
public function getAuthority()
{
$authority = $this->userInfo ? $this->userInfo.'@' : '';
$authority .= $this->host;
if ($this->explicitPortSpecified) {
$authority .= ":{$this->port}";
}
return $authority;
}
/**
* @return string
*/
public function getRawAuthority()
{
$authority = $this->rawUserInfo ? $this->rawUserInfo.'@' : '';
$authority .= $this->host;
if ($this->explicitPortSpecified) {
$authority .= ":{$this->port}";
}
return $authority;
}
/**
* @return string
*/
public function getAbsoluteUri()
{
$uri = $this->scheme . '://' . $this->getRawAuthority();
if ('/' === $this->path) {
$uri .= $this->explicitTrailingHostSlash ? '/' : '';
} else {
$uri .= $this->path;
}
if (!empty($this->query)) {
$uri .= "?{$this->query}";
}
if (!empty($this->fragment)) {
$uri .= "#{$this->fragment}";
}
return $uri;
}
/**
* @return string
*/
public function getRelativeUri()
{
$uri = '';
if ('/' === $this->path) {
$uri .= $this->explicitTrailingHostSlash ? '/' : '';
} else {
$uri .= $this->path;
}
return $uri;
}
/**
* Uses protected user info by default as per rfc3986-3.2.1
* Uri::getAbsoluteUri() is available if plain-text password information is desirable.
*
* @return string
*/
public function __toString()
{
$uri = $this->scheme . '://' . $this->getAuthority();
if ('/' === $this->path) {
$uri .= $this->explicitTrailingHostSlash ? '/' : '';
} else {
$uri .= $this->path;
}
if (!empty($this->query)) {
$uri .= "?{$this->query}";
}
if (!empty($this->fragment)) {
$uri .= "#{$this->fragment}";
}
return $uri;
}
/**
* @param $path
*/
public function setPath($path)
{
if (empty($path)) {
$this->path = '/';
$this->explicitTrailingHostSlash = false;
} else {
$this->path = $path;
if ('/' === $this->path) {
$this->explicitTrailingHostSlash = true;
}
}
}
/**
* @param string $query
*/
public function setQuery($query)
{
$this->query = $query;
}
/**
* @param string $var
* @param string $val
*/
public function addToQuery($var, $val)
{
if (strlen($this->query) > 0) {
$this->query .= '&';
}
$this->query .= http_build_query(array($var => $val), '', '&');
}
/**
* @param string $fragment
*/
public function setFragment($fragment)
{
$this->fragment = $fragment;
}
/**
* @param string $scheme
*/
public function setScheme($scheme)
{
$this->scheme = $scheme;
}
/**
* @param string $userInfo
*/
public function setUserInfo($userInfo)
{
$this->userInfo = $userInfo ? $this->protectUserInfo($userInfo) : '';
$this->rawUserInfo = $userInfo;
}
/**
* @param int $port
*/
public function setPort($port)
{
$this->port = intval($port);
if (('https' === $this->scheme && $this->port === 443) || ('http' === $this->scheme && $this->port === 80)) {
$this->explicitPortSpecified = false;
} else {
$this->explicitPortSpecified = true;
}
}
/**
* @param string $host
*/
public function setHost($host)
{
$this->host = $host;
}
/**
* @return bool
*/
public function hasExplicitTrailingHostSlash()
{
return $this->explicitTrailingHostSlash;
}
/**
* @return bool
*/
public function hasExplicitPortSpecified()
{
return $this->explicitPortSpecified;
}
}

View File

@@ -0,0 +1,168 @@
<?php
namespace OAuth\Common\Http\Uri;
use RuntimeException;
/**
* Factory class for uniform resource indicators
*/
class UriFactory implements UriFactoryInterface
{
/**
* Factory method to build a URI from a super-global $_SERVER array.
*
* @param array $_server
*
* @return UriInterface
*/
public function createFromSuperGlobalArray(array $_server)
{
if ($uri = $this->attemptProxyStyleParse($_server)) {
return $uri;
}
$scheme = $this->detectScheme($_server);
$host = $this->detectHost($_server);
$port = $this->detectPort($_server);
$path = $this->detectPath($_server);
$query = $this->detectQuery($_server);
return $this->createFromParts($scheme, '', $host, $port, $path, $query);
}
/**
* @param string $absoluteUri
*
* @return UriInterface
*/
public function createFromAbsolute($absoluteUri)
{
return new Uri($absoluteUri);
}
/**
* Factory method to build a URI from parts
*
* @param string $scheme
* @param string $userInfo
* @param string $host
* @param string $port
* @param string $path
* @param string $query
* @param string $fragment
*
* @return UriInterface
*/
public function createFromParts($scheme, $userInfo, $host, $port, $path = '', $query = '', $fragment = '')
{
$uri = new Uri();
$uri->setScheme($scheme);
$uri->setUserInfo($userInfo);
$uri->setHost($host);
$uri->setPort($port);
$uri->setPath($path);
$uri->setQuery($query);
$uri->setFragment($fragment);
return $uri;
}
/**
* @param array $_server
*
* @return UriInterface|null
*/
private function attemptProxyStyleParse($_server)
{
// If the raw HTTP request message arrives with a proxy-style absolute URI in the
// initial request line, the absolute URI is stored in $_SERVER['REQUEST_URI'] and
// we only need to parse that.
if (isset($_server['REQUEST_URI']) && parse_url($_server['REQUEST_URI'], PHP_URL_SCHEME)) {
return new Uri($_server['REQUEST_URI']);
}
return null;
}
/**
* @param array $_server
*
* @return string
*
* @throws RuntimeException
*/
private function detectPath($_server)
{
if (isset($_server['REQUEST_URI'])) {
$uri = $_server['REQUEST_URI'];
} elseif (isset($_server['REDIRECT_URL'])) {
$uri = $_server['REDIRECT_URL'];
} else {
throw new RuntimeException('Could not detect URI path from superglobal');
}
$queryStr = strpos($uri, '?');
if ($queryStr !== false) {
$uri = substr($uri, 0, $queryStr);
}
return $uri;
}
/**
* @param array $_server
*
* @return string
*/
private function detectHost(array $_server)
{
$host = isset($_server['HTTP_HOST']) ? $_server['HTTP_HOST'] : '';
if (strstr($host, ':')) {
$host = parse_url($host, PHP_URL_HOST);
}
return $host;
}
/**
* @param array $_server
*
* @return string
*/
private function detectPort(array $_server)
{
return isset($_server['SERVER_PORT']) ? $_server['SERVER_PORT'] : 80;
}
/**
* @param array $_server
*
* @return string
*/
private function detectQuery(array $_server)
{
return isset($_server['QUERY_STRING']) ? $_server['QUERY_STRING'] : '';
}
/**
* Determine URI scheme component from superglobal array
*
* When using ISAPI with IIS, the value will be "off" if the request was
* not made through the HTTPS protocol. As a result, we filter the
* value to a bool.
*
* @param array $_server A super-global $_SERVER array
*
* @return string Returns http or https depending on the URI scheme
*/
private function detectScheme(array $_server)
{
if (isset($_server['HTTPS']) && filter_var($_server['HTTPS'], FILTER_VALIDATE_BOOLEAN)) {
return 'https';
} else {
return 'http';
}
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace OAuth\Common\Http\Uri;
/**
* Factory interface for uniform resource indicators
*/
interface UriFactoryInterface
{
/**
* Factory method to build a URI from a super-global $_SERVER array.
*
* @param array $_server
*
* @return UriInterface
*/
public function createFromSuperGlobalArray(array $_server);
/**
* Creates a URI from an absolute URI
*
* @param string $absoluteUri
*
* @return UriInterface
*/
public function createFromAbsolute($absoluteUri);
/**
* Factory method to build a URI from parts
*
* @param string $scheme
* @param string $userInfo
* @param string $host
* @param string $port
* @param string $path
* @param string $query
* @param string $fragment
*
* @return UriInterface
*/
public function createFromParts($scheme, $userInfo, $host, $port, $path = '', $query = '', $fragment = '');
}

View File

@@ -0,0 +1,133 @@
<?php
namespace OAuth\Common\Http\Uri;
interface UriInterface
{
/**
* @return string
*/
public function getScheme();
/**
* @param string $scheme
*/
public function setScheme($scheme);
/**
* @return string
*/
public function getHost();
/**
* @param string $host
*/
public function setHost($host);
/**
* @return int
*/
public function getPort();
/**
* @param int $port
*/
public function setPort($port);
/**
* @return string
*/
public function getPath();
/**
* @param string $path
*/
public function setPath($path);
/**
* @return string
*/
public function getQuery();
/**
* @param string $query
*/
public function setQuery($query);
/**
* Adds a param to the query string.
*
* @param string $var
* @param string $val
*/
public function addToQuery($var, $val);
/**
* @return string
*/
public function getFragment();
/**
* Should return URI user info, masking protected user info data according to rfc3986-3.2.1
*
* @return string
*/
public function getUserInfo();
/**
* @param string $userInfo
*/
public function setUserInfo($userInfo);
/**
* Should return the URI Authority, masking protected user info data according to rfc3986-3.2.1
*
* @return string
*/
public function getAuthority();
/**
* Should return the URI string, masking protected user info data according to rfc3986-3.2.1
*
* @return string the URI string with user protected info masked
*/
public function __toString();
/**
* Should return the URI Authority without masking protected user info data
*
* @return string
*/
public function getRawAuthority();
/**
* Should return the URI user info without masking protected user info data
*
* @return string
*/
public function getRawUserInfo();
/**
* Build the full URI based on all the properties
*
* @return string The full URI without masking user info
*/
public function getAbsoluteUri();
/**
* Build the relative URI based on all the properties
*
* @return string The relative URI
*/
public function getRelativeUri();
/**
* @return bool
*/
public function hasExplicitTrailingHostSlash();
/**
* @return bool
*/
public function hasExplicitPortSpecified();
}

View File

@@ -0,0 +1,100 @@
<?php
namespace OAuth\Common\Service;
use OAuth\Common\Consumer\CredentialsInterface;
use OAuth\Common\Http\Client\ClientInterface;
use OAuth\Common\Http\Uri\Uri;
use OAuth\Common\Http\Uri\UriInterface;
use OAuth\Common\Exception\Exception;
use OAuth\Common\Storage\TokenStorageInterface;
/**
* Abstract OAuth service, version-agnostic
*/
abstract class AbstractService implements ServiceInterface
{
/** @var Credentials */
protected $credentials;
/** @var ClientInterface */
protected $httpClient;
/** @var TokenStorageInterface */
protected $storage;
/**
* @param CredentialsInterface $credentials
* @param ClientInterface $httpClient
* @param TokenStorageInterface $storage
*/
public function __construct(
CredentialsInterface $credentials,
ClientInterface $httpClient,
TokenStorageInterface $storage
) {
$this->credentials = $credentials;
$this->httpClient = $httpClient;
$this->storage = $storage;
}
/**
* @param UriInterface|string $path
* @param UriInterface $baseApiUri
*
* @return UriInterface
*
* @throws Exception
*/
protected function determineRequestUriFromPath($path, UriInterface $baseApiUri = null)
{
if ($path instanceof UriInterface) {
$uri = $path;
} elseif (stripos($path, 'http://') === 0 || stripos($path, 'https://') === 0) {
$uri = new Uri($path);
} else {
if (null === $baseApiUri) {
throw new Exception(
'An absolute URI must be passed to ServiceInterface::request as no baseApiUri is set.'
);
}
$uri = clone $baseApiUri;
if (false !== strpos($path, '?')) {
$parts = explode('?', $path, 2);
$path = $parts[0];
$query = $parts[1];
$uri->setQuery($query);
}
if ($path[0] === '/') {
$path = substr($path, 1);
}
$uri->setPath($uri->getPath() . $path);
}
return $uri;
}
/**
* Accessor to the storage adapter to be able to retrieve tokens
*
* @return TokenStorageInterface
*/
public function getStorage()
{
return $this->storage;
}
/**
* @return string
*/
public function service()
{
// get class name without backslashes
$classname = get_class($this);
return preg_replace('/^.*\\\\/', '', $classname);
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace OAuth\Common\Service;
use OAuth\Common\Http\Uri\UriInterface;
/**
* Defines methods common among all OAuth services.
*/
interface ServiceInterface
{
/**
* Sends an authenticated API request to the path provided.
* If the path provided is not an absolute URI, the base API Uri (service-specific) will be used.
*
* @param string|UriInterface $path
* @param string $method HTTP method
* @param array $body Request body if applicable (an associative array will
* automatically be converted into a urlencoded body)
* @param array $extraHeaders Extra headers if applicable. These will override service-specific
* any defaults.
*
* @return string
*/
public function request($path, $method = 'GET', $body = null, array $extraHeaders = array());
/**
* Returns the url to redirect to for authorization purposes.
*
* @param array $additionalParameters
*
* @return UriInterface
*/
public function getAuthorizationUri(array $additionalParameters = array());
/**
* Returns the authorization API endpoint.
*
* @return UriInterface
*/
public function getAuthorizationEndpoint();
/**
* Returns the access token API endpoint.
*
* @return UriInterface
*/
public function getAccessTokenEndpoint();
}

View File

@@ -0,0 +1,10 @@
<?php
namespace OAuth\Common\Storage\Exception;
/**
* Exception thrown when a state is not found in storage.
*/
class AuthorizationStateNotFoundException extends StorageException
{
}

View File

@@ -0,0 +1,12 @@
<?php
namespace OAuth\Common\Storage\Exception;
use OAuth\Common\Exception\Exception;
/**
* Generic storage exception.
*/
class StorageException extends Exception
{
}

View File

@@ -0,0 +1,10 @@
<?php
namespace OAuth\Common\Storage\Exception;
/**
* Exception thrown when a token is not found in storage.
*/
class TokenNotFoundException extends StorageException
{
}

View File

@@ -0,0 +1,139 @@
<?php
namespace OAuth\Common\Storage;
use OAuth\Common\Token\TokenInterface;
use OAuth\Common\Storage\Exception\TokenNotFoundException;
use OAuth\Common\Storage\Exception\AuthorizationStateNotFoundException;
/*
* Stores a token in-memory only (destroyed at end of script execution).
*/
class Memory implements TokenStorageInterface
{
/**
* @var object|TokenInterface
*/
protected $tokens;
/**
* @var array
*/
protected $states;
public function __construct()
{
$this->tokens = array();
$this->states = array();
}
/**
* {@inheritDoc}
*/
public function retrieveAccessToken($service)
{
if ($this->hasAccessToken($service)) {
return $this->tokens[$service];
}
throw new TokenNotFoundException('Token not stored');
}
/**
* {@inheritDoc}
*/
public function storeAccessToken($service, TokenInterface $token)
{
$this->tokens[$service] = $token;
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function hasAccessToken($service)
{
return isset($this->tokens[$service]) && $this->tokens[$service] instanceof TokenInterface;
}
/**
* {@inheritDoc}
*/
public function clearToken($service)
{
if (array_key_exists($service, $this->tokens)) {
unset($this->tokens[$service]);
}
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function clearAllTokens()
{
$this->tokens = array();
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function retrieveAuthorizationState($service)
{
if ($this->hasAuthorizationState($service)) {
return $this->states[$service];
}
throw new AuthorizationStateNotFoundException('State not stored');
}
/**
* {@inheritDoc}
*/
public function storeAuthorizationState($service, $state)
{
$this->states[$service] = $state;
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function hasAuthorizationState($service)
{
return isset($this->states[$service]) && null !== $this->states[$service];
}
/**
* {@inheritDoc}
*/
public function clearAuthorizationState($service)
{
if (array_key_exists($service, $this->states)) {
unset($this->states[$service]);
}
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function clearAllAuthorizationStates()
{
$this->states = array();
// allow chaining
return $this;
}
}

View File

@@ -0,0 +1,230 @@
<?php
namespace OAuth\Common\Storage;
use OAuth\Common\Token\TokenInterface;
use OAuth\Common\Storage\Exception\TokenNotFoundException;
use OAuth\Common\Storage\Exception\AuthorizationStateNotFoundException;
use Predis\Client as Predis;
/*
* Stores a token in a Redis server. Requires the Predis library available at https://github.com/nrk/predis
*/
class Redis implements TokenStorageInterface
{
/**
* @var string
*/
protected $key;
protected $stateKey;
/**
* @var object|\Redis
*/
protected $redis;
/**
* @var object|TokenInterface
*/
protected $cachedTokens;
/**
* @var object
*/
protected $cachedStates;
/**
* @param Predis $redis An instantiated and connected redis client
* @param string $key The key to store the token under in redis
* @param string $stateKey The key to store the state under in redis.
*/
public function __construct(Predis $redis, $key, $stateKey)
{
$this->redis = $redis;
$this->key = $key;
$this->stateKey = $stateKey;
$this->cachedTokens = array();
$this->cachedStates = array();
}
/**
* {@inheritDoc}
*/
public function retrieveAccessToken($service)
{
if (!$this->hasAccessToken($service)) {
throw new TokenNotFoundException('Token not found in redis');
}
if (isset($this->cachedTokens[$service])) {
return $this->cachedTokens[$service];
}
$val = $this->redis->hget($this->key, $service);
return $this->cachedTokens[$service] = unserialize($val);
}
/**
* {@inheritDoc}
*/
public function storeAccessToken($service, TokenInterface $token)
{
// (over)write the token
$this->redis->hset($this->key, $service, serialize($token));
$this->cachedTokens[$service] = $token;
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function hasAccessToken($service)
{
if (isset($this->cachedTokens[$service])
&& $this->cachedTokens[$service] instanceof TokenInterface
) {
return true;
}
return $this->redis->hexists($this->key, $service);
}
/**
* {@inheritDoc}
*/
public function clearToken($service)
{
$this->redis->hdel($this->key, $service);
unset($this->cachedTokens[$service]);
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function clearAllTokens()
{
// memory
$this->cachedTokens = array();
// redis
$keys = $this->redis->hkeys($this->key);
$me = $this; // 5.3 compat
// pipeline for performance
$this->redis->pipeline(
function ($pipe) use ($keys, $me) {
foreach ($keys as $k) {
$pipe->hdel($me->getKey(), $k);
}
}
);
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function retrieveAuthorizationState($service)
{
if (!$this->hasAuthorizationState($service)) {
throw new AuthorizationStateNotFoundException('State not found in redis');
}
if (isset($this->cachedStates[$service])) {
return $this->cachedStates[$service];
}
$val = $this->redis->hget($this->stateKey, $service);
return $this->cachedStates[$service] = $val;
}
/**
* {@inheritDoc}
*/
public function storeAuthorizationState($service, $state)
{
// (over)write the token
$this->redis->hset($this->stateKey, $service, $state);
$this->cachedStates[$service] = $state;
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function hasAuthorizationState($service)
{
if (isset($this->cachedStates[$service])
&& null !== $this->cachedStates[$service]
) {
return true;
}
return $this->redis->hexists($this->stateKey, $service);
}
/**
* {@inheritDoc}
*/
public function clearAuthorizationState($service)
{
$this->redis->hdel($this->stateKey, $service);
unset($this->cachedStates[$service]);
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function clearAllAuthorizationStates()
{
// memory
$this->cachedStates = array();
// redis
$keys = $this->redis->hkeys($this->stateKey);
$me = $this; // 5.3 compat
// pipeline for performance
$this->redis->pipeline(
function ($pipe) use ($keys, $me) {
foreach ($keys as $k) {
$pipe->hdel($me->getKey(), $k);
}
}
);
// allow chaining
return $this;
}
/**
* @return Predis $redis
*/
public function getRedis()
{
return $this->redis;
}
/**
* @return string $key
*/
public function getKey()
{
return $this->key;
}
}

View File

@@ -0,0 +1,204 @@
<?php
namespace OAuth\Common\Storage;
use OAuth\Common\Token\TokenInterface;
use OAuth\Common\Storage\Exception\TokenNotFoundException;
use OAuth\Common\Storage\Exception\AuthorizationStateNotFoundException;
/**
* Stores a token in a PHP session.
*/
class Session implements TokenStorageInterface
{
/**
* @var bool
*/
protected $startSession;
/**
* @var string
*/
protected $sessionVariableName;
/**
* @var string
*/
protected $stateVariableName;
/**
* @param bool $startSession Whether or not to start the session upon construction.
* @param string $sessionVariableName the variable name to use within the _SESSION superglobal
* @param string $stateVariableName
*/
public function __construct(
$startSession = true,
$sessionVariableName = 'lusitanian-oauth-token',
$stateVariableName = 'lusitanian-oauth-state'
) {
if ($startSession && !$this->sessionHasStarted()) {
session_start();
}
$this->startSession = $startSession;
$this->sessionVariableName = $sessionVariableName;
$this->stateVariableName = $stateVariableName;
if (!isset($_SESSION[$sessionVariableName])) {
$_SESSION[$sessionVariableName] = array();
}
if (!isset($_SESSION[$stateVariableName])) {
$_SESSION[$stateVariableName] = array();
}
}
/**
* {@inheritDoc}
*/
public function retrieveAccessToken($service)
{
if ($this->hasAccessToken($service)) {
return unserialize($_SESSION[$this->sessionVariableName][$service]);
}
throw new TokenNotFoundException('Token not found in session, are you sure you stored it?');
}
/**
* {@inheritDoc}
*/
public function storeAccessToken($service, TokenInterface $token)
{
$serializedToken = serialize($token);
if (isset($_SESSION[$this->sessionVariableName])
&& is_array($_SESSION[$this->sessionVariableName])
) {
$_SESSION[$this->sessionVariableName][$service] = $serializedToken;
} else {
$_SESSION[$this->sessionVariableName] = array(
$service => $serializedToken,
);
}
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function hasAccessToken($service)
{
return isset($_SESSION[$this->sessionVariableName], $_SESSION[$this->sessionVariableName][$service]);
}
/**
* {@inheritDoc}
*/
public function clearToken($service)
{
if (array_key_exists($service, $_SESSION[$this->sessionVariableName])) {
unset($_SESSION[$this->sessionVariableName][$service]);
}
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function clearAllTokens()
{
unset($_SESSION[$this->sessionVariableName]);
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function storeAuthorizationState($service, $state)
{
if (isset($_SESSION[$this->stateVariableName])
&& is_array($_SESSION[$this->stateVariableName])
) {
$_SESSION[$this->stateVariableName][$service] = $state;
} else {
$_SESSION[$this->stateVariableName] = array(
$service => $state,
);
}
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function hasAuthorizationState($service)
{
return isset($_SESSION[$this->stateVariableName], $_SESSION[$this->stateVariableName][$service]);
}
/**
* {@inheritDoc}
*/
public function retrieveAuthorizationState($service)
{
if ($this->hasAuthorizationState($service)) {
return $_SESSION[$this->stateVariableName][$service];
}
throw new AuthorizationStateNotFoundException('State not found in session, are you sure you stored it?');
}
/**
* {@inheritDoc}
*/
public function clearAuthorizationState($service)
{
if (array_key_exists($service, $_SESSION[$this->stateVariableName])) {
unset($_SESSION[$this->stateVariableName][$service]);
}
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function clearAllAuthorizationStates()
{
unset($_SESSION[$this->stateVariableName]);
// allow chaining
return $this;
}
public function __destruct()
{
if ($this->startSession) {
session_write_close();
}
}
/**
* Determine if the session has started.
* @url http://stackoverflow.com/a/18542272/1470961
* @return bool
*/
protected function sessionHasStarted()
{
// For more modern PHP versions we use a more reliable method.
if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
return session_status() != PHP_SESSION_NONE;
}
// Below PHP 5.4 we should test for the current session ID.
return session_id() !== '';
}
}

View File

@@ -0,0 +1,200 @@
<?php
namespace OAuth\Common\Storage;
use OAuth\Common\Token\TokenInterface;
use OAuth\Common\Storage\Exception\TokenNotFoundException;
use OAuth\Common\Storage\Exception\AuthorizationStateNotFoundException;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class SymfonySession implements TokenStorageInterface
{
private $session;
private $sessionVariableName;
private $stateVariableName;
/**
* @param SessionInterface $session
* @param bool $startSession
* @param string $sessionVariableName
* @param string $stateVariableName
*/
public function __construct(
SessionInterface $session,
$startSession = true,
$sessionVariableName = 'lusitanian_oauth_token',
$stateVariableName = 'lusitanian_oauth_state'
) {
$this->session = $session;
$this->sessionVariableName = $sessionVariableName;
$this->stateVariableName = $stateVariableName;
}
/**
* {@inheritDoc}
*/
public function retrieveAccessToken($service)
{
if ($this->hasAccessToken($service)) {
// get from session
$tokens = $this->session->get($this->sessionVariableName);
// one item
return $tokens[$service];
}
throw new TokenNotFoundException('Token not found in session, are you sure you stored it?');
}
/**
* {@inheritDoc}
*/
public function storeAccessToken($service, TokenInterface $token)
{
// get previously saved tokens
$tokens = $this->session->get($this->sessionVariableName);
if (!is_array($tokens)) {
$tokens = array();
}
$tokens[$service] = $token;
// save
$this->session->set($this->sessionVariableName, $tokens);
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function hasAccessToken($service)
{
// get from session
$tokens = $this->session->get($this->sessionVariableName);
return is_array($tokens)
&& isset($tokens[$service])
&& $tokens[$service] instanceof TokenInterface;
}
/**
* {@inheritDoc}
*/
public function clearToken($service)
{
// get previously saved tokens
$tokens = $this->session->get($this->sessionVariableName);
if (is_array($tokens) && array_key_exists($service, $tokens)) {
unset($tokens[$service]);
// Replace the stored tokens array
$this->session->set($this->sessionVariableName, $tokens);
}
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function clearAllTokens()
{
$this->session->remove($this->sessionVariableName);
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function retrieveAuthorizationState($service)
{
if ($this->hasAuthorizationState($service)) {
// get from session
$states = $this->session->get($this->stateVariableName);
// one item
return $states[$service];
}
throw new AuthorizationStateNotFoundException('State not found in session, are you sure you stored it?');
}
/**
* {@inheritDoc}
*/
public function storeAuthorizationState($service, $state)
{
// get previously saved tokens
$states = $this->session->get($this->stateVariableName);
if (!is_array($states)) {
$states = array();
}
$states[$service] = $state;
// save
$this->session->set($this->stateVariableName, $states);
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function hasAuthorizationState($service)
{
// get from session
$states = $this->session->get($this->stateVariableName);
return is_array($states)
&& isset($states[$service])
&& null !== $states[$service];
}
/**
* {@inheritDoc}
*/
public function clearAuthorizationState($service)
{
// get previously saved tokens
$states = $this->session->get($this->stateVariableName);
if (is_array($states) && array_key_exists($service, $states)) {
unset($states[$service]);
// Replace the stored tokens array
$this->session->set($this->stateVariableName, $states);
}
// allow chaining
return $this;
}
/**
* {@inheritDoc}
*/
public function clearAllAuthorizationStates()
{
$this->session->remove($this->stateVariableName);
// allow chaining
return $this;
}
/**
* @return Session
*/
public function getSession()
{
return $this->session;
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace OAuth\Common\Storage;
use OAuth\Common\Token\TokenInterface;
use OAuth\Common\Storage\Exception\TokenNotFoundException;
/**
* All token storage providers must implement this interface.
*/
interface TokenStorageInterface
{
/**
* @param string $service
*
* @return TokenInterface
*
* @throws TokenNotFoundException
*/
public function retrieveAccessToken($service);
/**
* @param string $service
* @param TokenInterface $token
*
* @return TokenStorageInterface
*/
public function storeAccessToken($service, TokenInterface $token);
/**
* @param string $service
*
* @return bool
*/
public function hasAccessToken($service);
/**
* Delete the users token. Aka, log out.
*
* @param string $service
*
* @return TokenStorageInterface
*/
public function clearToken($service);
/**
* Delete *ALL* user tokens. Use with care. Most of the time you will likely
* want to use clearToken() instead.
*
* @return TokenStorageInterface
*/
public function clearAllTokens();
/**
* Store the authorization state related to a given service
*
* @param string $service
* @param string $state
*
* @return TokenStorageInterface
*/
public function storeAuthorizationState($service, $state);
/**
* Check if an authorization state for a given service exists
*
* @param string $service
*
* @return bool
*/
public function hasAuthorizationState($service);
/**
* Retrieve the authorization state for a given service
*
* @param string $service
*
* @return string
*/
public function retrieveAuthorizationState($service);
/**
* Clear the authorization state of a given service
*
* @param string $service
*
* @return TokenStorageInterface
*/
public function clearAuthorizationState($service);
/**
* Delete *ALL* user authorization states. Use with care. Most of the time you will likely
* want to use clearAuthorization() instead.
*
* @return TokenStorageInterface
*/
public function clearAllAuthorizationStates();
}

View File

@@ -0,0 +1,128 @@
<?php
namespace OAuth\Common\Token;
/**
* Base token implementation for any OAuth version.
*/
abstract class AbstractToken implements TokenInterface
{
/**
* @var string
*/
protected $accessToken;
/**
* @var string
*/
protected $refreshToken;
/**
* @var int
*/
protected $endOfLife;
/**
* @var array
*/
protected $extraParams = array();
/**
* @param string $accessToken
* @param string $refreshToken
* @param int $lifetime
* @param array $extraParams
*/
public function __construct($accessToken = null, $refreshToken = null, $lifetime = null, $extraParams = array())
{
$this->accessToken = $accessToken;
$this->refreshToken = $refreshToken;
$this->setLifetime($lifetime);
$this->extraParams = $extraParams;
}
/**
* @return string
*/
public function getAccessToken()
{
return $this->accessToken;
}
/**
* @return string
*/
public function getRefreshToken()
{
return $this->refreshToken;
}
/**
* @return int
*/
public function getEndOfLife()
{
return $this->endOfLife;
}
/**
* @param array $extraParams
*/
public function setExtraParams(array $extraParams)
{
$this->extraParams = $extraParams;
}
/**
* @return array
*/
public function getExtraParams()
{
return $this->extraParams;
}
/**
* @param string $accessToken
*/
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
}
/**
* @param int $endOfLife
*/
public function setEndOfLife($endOfLife)
{
$this->endOfLife = $endOfLife;
}
/**
* @param int $lifetime
*/
public function setLifetime($lifetime)
{
if (0 === $lifetime || static::EOL_NEVER_EXPIRES === $lifetime) {
$this->endOfLife = static::EOL_NEVER_EXPIRES;
} elseif (null !== $lifetime) {
$this->endOfLife = intval($lifetime) + time();
} else {
$this->endOfLife = static::EOL_UNKNOWN;
}
}
/**
* @param string $refreshToken
*/
public function setRefreshToken($refreshToken)
{
$this->refreshToken = $refreshToken;
}
public function isExpired()
{
return ($this->getEndOfLife() !== TokenInterface::EOL_NEVER_EXPIRES
&& $this->getEndOfLife() !== TokenInterface::EOL_UNKNOWN
&& time() > $this->getEndOfLife());
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace OAuth\Common\Token\Exception;
use OAuth\Common\Exception\Exception;
/**
* Exception thrown when an expired token is attempted to be used.
*/
class ExpiredTokenException extends Exception
{
}

View File

@@ -0,0 +1,64 @@
<?php
namespace OAuth\Common\Token;
/**
* Base token interface for any OAuth version.
*/
interface TokenInterface
{
/**
* Denotes an unknown end of life time.
*/
const EOL_UNKNOWN = -9001;
/**
* Denotes a token which never expires, should only happen in OAuth1.
*/
const EOL_NEVER_EXPIRES = -9002;
/**
* @return string
*/
public function getAccessToken();
/**
* @return int
*/
public function getEndOfLife();
/**
* @return array
*/
public function getExtraParams();
/**
* @param string $accessToken
*/
public function setAccessToken($accessToken);
/**
* @param int $endOfLife
*/
public function setEndOfLife($endOfLife);
/**
* @param int $lifetime
*/
public function setLifetime($lifetime);
/**
* @param array $extraParams
*/
public function setExtraParams(array $extraParams);
/**
* @return string
*/
public function getRefreshToken();
/**
* @param string $refreshToken
*/
public function setRefreshToken($refreshToken);
}