diff --git a/app/Commands/GenerateTrackFilesCommand.php b/app/Commands/GenerateTrackFilesCommand.php index 228dac75..1c2a75ba 100644 --- a/app/Commands/GenerateTrackFilesCommand.php +++ b/app/Commands/GenerateTrackFilesCommand.php @@ -173,6 +173,9 @@ class GenerateTrackFilesCommand extends CommandBase throw $e; } + // This ensures that any updates to the track record, like from parsed + // tags, are reflected in the command's response. + $this->track = $this->track->fresh(); return CommandResponse::succeed([ 'id' => $this->track->id, 'name' => $this->track->name, diff --git a/app/Commands/ParseTrackTagsCommand.php b/app/Commands/ParseTrackTagsCommand.php index f0577a74..5365268a 100644 --- a/app/Commands/ParseTrackTagsCommand.php +++ b/app/Commands/ParseTrackTagsCommand.php @@ -111,7 +111,7 @@ class ParseTrackTagsCommand extends CommandBase $vars = $track->getAttributes(); foreach ($vars as $key => $value) { - if ($value == null) { + if ($value === null) { unset($track->{"$key"}); } } diff --git a/app/Exceptions/InvalidAccessTokenException.php b/app/Exceptions/InvalidAccessTokenException.php deleted file mode 100644 index 39c3f57d..00000000 --- a/app/Exceptions/InvalidAccessTokenException.php +++ /dev/null @@ -1,34 +0,0 @@ -. - */ - -namespace Poniverse\Ponyfm\Exceptions; - -use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; - -/** - * Class InvalidAccessTokenException - * @package Poniverse\Ponyfm - * - * This exception indicates that an access token we attempted to introspect - * through the Poniverse API is expired or otherwise unusable. - */ -class InvalidAccessTokenException extends AccessDeniedHttpException -{ -}; diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index bdb7b0f4..1587f219 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -20,12 +20,16 @@ namespace Poniverse\Ponyfm\Http\Controllers; +use Carbon\Carbon; +use Illuminate\Support\Facades\Input; +use League\OAuth2\Client\Provider\Exception\IdentityProviderException; +use Log; +use Poniverse\Lib\Client; use Poniverse\Ponyfm\Models\User; use Auth; use Config; use DB; -use Illuminate\Support\Facades\Request; -use Poniverse; +use Request; use Redirect; class AuthController extends Controller @@ -34,14 +38,16 @@ class AuthController extends Controller public function __construct() { - $this->poniverse = new Poniverse(Config::get('poniverse.client_id'), Config::get('poniverse.secret')); - $this->poniverse->setRedirectUri(action('AuthController@getOAuth')); + $this->poniverse = new Client(config('poniverse.client_id'), config('poniverse.secret'), new \GuzzleHttp\Client()); } public function getLogin() { if (Auth::guest()) { - return Redirect::to($this->poniverse->getAuthenticationUrl('login')); + return Redirect::to( + $this->poniverse + ->getOAuthProvider(['redirectUri' => action('AuthController@getOAuth')]) + ->getAuthorizationUrl()); } return Redirect::to('/'); @@ -50,25 +56,22 @@ class AuthController extends Controller public function postLogout() { Auth::logout(); - return Redirect::to('/'); } public function getOAuth() { - $code = $this->poniverse->getClient()->getAccessToken( - Config::get('poniverse.urls')['token'], - 'authorization_code', - [ + $oauthProvider = $this->poniverse->getOAuthProvider(); + + try { + $accessToken = $oauthProvider->getAccessToken('authorization_code', [ 'code' => Request::query('code'), 'redirect_uri' => action('AuthController@getOAuth') - ] - ); - - if ($code['code'] != 200) { - if ($code['code'] == 400 && $code['result']['error_description'] == 'The authorization code has expired' && !isset($this->request['login_attempt'])) { - return Redirect::to($this->poniverse->getAuthenticationUrl('login_attempt')); - } + ]); + $this->poniverse->setAccessToken($accessToken); + $resourceOwner = $oauthProvider->getResourceOwner($accessToken); + } catch (IdentityProviderException $e) { + Log::error($e); return Redirect::to('/')->with( 'message', @@ -76,47 +79,44 @@ class AuthController extends Controller ); } - $this->poniverse->setAccessToken($code['result']['access_token']); - $poniverseUser = $this->poniverse->getUser(); - $token = DB::table('oauth2_tokens')->where('external_user_id', '=', $poniverseUser['id'])->where( - 'service', - '=', - 'poniverse' - )->first(); + /** @var \Poniverse\Lib\Entity\Poniverse\User $poniverseUser */ + $poniverseUser = $resourceOwner; - $setData = [ - 'access_token' => $code['result']['access_token'], - 'expires' => date('Y-m-d H:i:s', strtotime("+".$code['result']['expires_in']." Seconds", time())), - 'type' => $code['result']['token_type'], - ]; + $token = DB::table('oauth2_tokens') + ->where('external_user_id', '=', $poniverseUser->id) + ->where('service', '=', 'poniverse') + ->first(); - if (isset($code['result']['refresh_token']) && !empty($code['result']['refresh_token'])) { - $setData['refresh_token'] = $code['result']['refresh_token']; - } + $setData = [ + 'access_token' => $accessToken, + 'expires' => Carbon::createFromTimestampUTC($accessToken->getExpires()), + 'type' => 'Bearer', + ]; - if ($token) { - //User already exists, update access token and refresh token if provided. - DB::table('oauth2_tokens')->where('id', '=', $token->id)->update($setData); + if (!empty($accessToken->getRefreshToken())) { + $setData['refresh_token'] = $accessToken->getRefreshToken(); + } - return $this->loginRedirect(User::find($token->user_id)); - } + if ($token) { + //User already exists, update access token and refresh token if provided. + DB::table('oauth2_tokens')->where('id', '=', $token->id)->update($setData); + return $this->loginRedirect(User::find($token->user_id)); + } // Check by login name to see if they already have an account - $user = User::findOrCreate($poniverseUser['username'], $poniverseUser['display_name'], $poniverseUser['email']); - - if ($user->wasRecentlyCreated) { - return $this->loginRedirect($user); - } - - // We need to insert a new token row :O + $user = User::findOrCreate($poniverseUser->username, $poniverseUser->display_name, $poniverseUser->email); + if (!$user->wasRecentlyCreated) { + // We need to insert a new token row :O $setData['user_id'] = $user->id; - $setData['external_user_id'] = $poniverseUser['id']; + $setData['external_user_id'] = $poniverseUser->id; $setData['service'] = 'poniverse'; - DB::table('oauth2_tokens')->insert($setData); + } - return $this->loginRedirect($user); + + return $this->loginRedirect($user); + } } protected function loginRedirect($user, $rememberMe = true) diff --git a/app/Http/Middleware/AuthenticateOAuth.php b/app/Http/Middleware/AuthenticateOAuth.php index 8a391e0d..90e2a743 100644 --- a/app/Http/Middleware/AuthenticateOAuth.php +++ b/app/Http/Middleware/AuthenticateOAuth.php @@ -21,18 +21,19 @@ namespace Poniverse\Ponyfm\Http\Middleware; use Closure; -use GuzzleHttp; -use Illuminate\Auth\Guard; +use Illuminate\Contracts\Auth\Guard; use Illuminate\Http\Request; use Illuminate\Session\Store; +use League\OAuth2\Client\Token\AccessToken; use Poniverse; +use Poniverse\Lib\Client; use Poniverse\Ponyfm\Models\User; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; class AuthenticateOAuth { /** - * @var Poniverse + * @var Client */ private $poniverse; @@ -46,9 +47,9 @@ class AuthenticateOAuth */ private $session; - public function __construct(Poniverse $poniverse, Guard $auth, Store $session) + public function __construct(Guard $auth, Store $session) { - $this->poniverse = $poniverse; + $this->poniverse = new Client(config('poniverse.client_id'), config('poniverse.secret'), new \GuzzleHttp\Client()); $this->auth = $auth; $this->session = $session; } @@ -60,7 +61,7 @@ class AuthenticateOAuth * @param \Closure $next * @param string $requiredScope * @return mixed - * @throws \OAuth2\Exception + * @throws Poniverse\Lib\Errors\ApiException */ public function handle(Request $request, Closure $next, $requiredScope) { @@ -68,7 +69,7 @@ class AuthenticateOAuth $accessToken = $this->determineAccessToken($request, false); // check that access token is valid at Poniverse.net - $accessTokenInfo = $this->poniverse->getAccessTokenInfo($accessToken); + $accessTokenInfo = $this->poniverse->poniverse()->accessTokenInfo()->introspect($accessToken); if (!$accessTokenInfo->getIsActive()) { throw new AccessDeniedHttpException('This access token is expired or invalid!'); @@ -79,13 +80,14 @@ class AuthenticateOAuth } // Log in as the given user, creating the account if necessary. - $this->poniverse->setAccessToken($accessToken); + $this->poniverse->setAccessToken(new AccessToken(['access_token' => $accessToken])); $this->session->put('api_client_id', $accessTokenInfo->getClientId()); - $poniverseUser = $this->poniverse->getUser(); + /** @var Poniverse\Lib\Entity\Poniverse\User $poniverseUser */ + $poniverseUser = $this->poniverse->getOAuthProvider()->getResourceOwner($accessToken); - $user = User::findOrCreate($poniverseUser['username'], $poniverseUser['display_name'], $poniverseUser['email']); - $this->auth->onceUsingId($user); + $user = User::findOrCreate($poniverseUser->username, $poniverseUser->display_name, $poniverseUser->email); + $this->auth->setUser($user); return $next($request); } diff --git a/app/Library/Poniverse/AccessTokenInfo.php b/app/Library/Poniverse/AccessTokenInfo.php deleted file mode 100644 index 2e522564..00000000 --- a/app/Library/Poniverse/AccessTokenInfo.php +++ /dev/null @@ -1,243 +0,0 @@ -. - */ - -namespace Poniverse; - -/** - * Class AccessTokenInfo - * - * A container for the fields in the draft OAuth Token Introspection proposal. - * - * @link https://tools.ietf.org/html/draft-richer-oauth-introspection-06 - * @package Poniverse - */ -class AccessTokenInfo -{ - protected $token; - - protected $isActive; - protected $expiresAt; - protected $issuedAt; - protected $scopes; - protected $clientId; - protected $sub; - protected $userId; - protected $intendedAudience; - protected $issuer; - protected $tokenType; - - public function __construct($accessToken) - { - $this->token = $accessToken; - } - - /** - * @return mixed - */ - public function getToken() - { - return $this->token; - } - - /** - * @return bool - */ - public function getIsActive() - { - return $this->isActive; - } - - /** - * @param bool $isActive - * @return AccessTokenInfo - */ - public function setIsActive($isActive) - { - $this->isActive = $isActive; - return $this; - } - - /** - * @return mixed - */ - public function getExpiresAt() - { - return $this->expiresAt; - } - - /** - * @param mixed $expiresAt - * @return AccessTokenInfo - */ - public function setExpiresAt($expiresAt) - { - $this->expiresAt = $expiresAt; - return $this; - } - - /** - * @return mixed - */ - public function getIssuedAt() - { - return $this->issuedAt; - } - - /** - * @param mixed $issuedAt - * @return AccessTokenInfo - */ - public function setIssuedAt($issuedAt) - { - $this->issuedAt = $issuedAt; - return $this; - } - - /** - * @return array - */ - public function getScopes() - { - return $this->scopes; - } - - /** - * @param array|string $scopes - * @return AccessTokenInfo - */ - public function setScopes($scopes) - { - if (is_array($scopes)) { - $this->scopes = $scopes; - } else { - $this->scopes = mb_split(' ', $scopes); - } - - return $this; - } - - /** - * @return mixed - */ - public function getClientId() - { - return $this->clientId; - } - - /** - * @param mixed $clientId - * @return AccessTokenInfo - */ - public function setClientId($clientId) - { - $this->clientId = $clientId; - return $this; - } - - /** - * @return mixed - */ - public function getSub() - { - return $this->sub; - } - - /** - * @param mixed $sub - * @return AccessTokenInfo - */ - public function setSub($sub) - { - $this->sub = $sub; - return $this; - } - - /** - * @return mixed - */ - public function getUserId() - { - return $this->userId; - } - - /** - * @param mixed $userId - * @return AccessTokenInfo - */ - public function setUserId($userId) - { - $this->userId = $userId; - return $this; - } - - /** - * @return mixed - */ - public function getIntendedAudience() - { - return $this->intendedAudience; - } - - /** - * @param mixed $intendedAudience - * @return AccessTokenInfo - */ - public function setIntendedAudience($intendedAudience) - { - $this->intendedAudience = $intendedAudience; - return $this; - } - - /** - * @return mixed - */ - public function getIssuer() - { - return $this->issuer; - } - - /** - * @param mixed $issuer - * @return AccessTokenInfo - */ - public function setIssuer($issuer) - { - $this->issuer = $issuer; - return $this; - } - - /** - * @return mixed - */ - public function getTokenType() - { - return $this->tokenType; - } - - /** - * @param mixed $tokenType - * @return AccessTokenInfo - */ - public function setTokenType($tokenType) - { - $this->tokenType = $tokenType; - return $this; - } -} diff --git a/app/Library/Poniverse/Poniverse.php b/app/Library/Poniverse/Poniverse.php deleted file mode 100644 index 8a039239..00000000 --- a/app/Library/Poniverse/Poniverse.php +++ /dev/null @@ -1,163 +0,0 @@ -. - */ - -use OAuth2\Client; -use Poniverse\Ponyfm\Exceptions\InvalidAccessTokenException; - -/** - * Class Poniverse - * - * Just for the sake of being sane without an autoloader - * this class is going to be a simple flat api class. - */ - -class Poniverse -{ - protected $clientId; - protected $clientSecret; - protected $accessToken; - protected $redirectUri; - protected $urls; - - /** - * @var OAuth2\Client - */ - protected $client; - - /** - * Initialises the class - * - * @param string $clientId - * @param string $clientSecret - * @param string $accessToken - */ - public function __construct($clientId, $clientSecret, $accessToken = '') - { - $this->urls = Config::get('poniverse.urls'); - - $this->clientId = $clientId; - $this->clientSecret = $clientSecret; - $this->accessToken = $accessToken; - - //Setup Dependencies - $this->setupOAuth2(); - $this->setupHttpful(); - } - - protected function setupOAuth2() - { - require_once('oauth2/Client.php'); - require_once('oauth2/GrantType/IGrantType.php'); - require_once('oauth2/GrantType/AuthorizationCode.php'); - - $this->client = new \OAuth2\Client($this->clientId, $this->clientSecret); - } - - protected function setupHttpful() - { - require_once('autoloader.php'); - $autoloader = new SplClassLoader('Httpful', __DIR__."/httpful/src/"); - $autoloader->register(); - } - - public function setAccessToken($accessToken) - { - $this->accessToken = $accessToken; - } - - public function getAuthenticationUrl($state) - { - return $this->client->getAuthenticationUrl($this->urls['auth'], $this->redirectUri, ['state' => $state]); - } - - public function setRedirectUri($redirectUri) - { - $this->redirectUri = $redirectUri; - } - - /** - * Gets the OAuth2 Client - * - * @return \OAuth2\Client - */ - public function getClient() - { - return $this->client; - } - - /** - * Gets data about the currently logged in user - * - * @return array - */ - public function getUser() - { - $data = \Httpful\Request::get($this->urls['api'] . "users?access_token=" . $this->accessToken); - - $result = $data->addHeader('Accept', 'application/json')->send(); - - return json_decode($result, true); - } - - /** - * Gets information about the given access token. - * - * @link https://tools.ietf.org/html/draft-richer-oauth-introspection-06 - * - * @param $accessTokenToIntrospect - * @return \Poniverse\AccessTokenInfo - * @throws InvalidAccessTokenException - * @throws \Symfony\Component\HttpKernel\Exception\HttpException - */ - public function getAccessTokenInfo($accessTokenToIntrospect) - { - $token = $this->client->getAccessToken( - Config::get('poniverse.urls.token'), - Client::GRANT_TYPE_CLIENT_CREDENTIALS, - [] - )['result']['access_token']; - - - $request = \Httpful\Request::post($this->urls['api']. 'meta/introspect?token='.$accessTokenToIntrospect); - - /** @var Httpful\Response $result */ - $result = $request - ->addHeader('Accept', 'application/json') - ->addHeader('Authorization', 'Bearer '.$token) - ->send(); - $data = json_decode($result, true); - - if (404 === $result->code) { - throw new InvalidAccessTokenException('This access token is expired or invalid!'); - } - - if (200 !== $result->code) { - throw new \Symfony\Component\HttpKernel\Exception\HttpException(500, 'An unknown error occurred while contacting the Poniverse API.'); - } - - $tokenInfo = new \Poniverse\AccessTokenInfo($accessTokenToIntrospect); - $tokenInfo - ->setIsActive($data['active']) - ->setScopes($data['scope']) - ->setClientId($data['client_id']); - - return $tokenInfo; - } -} diff --git a/app/Library/Poniverse/autoloader.php b/app/Library/Poniverse/autoloader.php deleted file mode 100644 index d1ee4eb0..00000000 --- a/app/Library/Poniverse/autoloader.php +++ /dev/null @@ -1,137 +0,0 @@ -register(); - * - * @author Jonathan H. Wage - * @author Roman S. Borschel - * @author Matthew Weier O'Phinney - * @author Kris Wallsmith - * @author Fabien Potencier - */ -class SplClassLoader -{ - private $_fileExtension = '.php'; - private $_namespace; - private $_includePath; - private $_namespaceSeparator = '\\'; - - /** - * Creates a new SplClassLoader that loads classes of the - * specified namespace. - * - * @param string $ns The namespace to use. - * @param string $includePath - */ - public function __construct($ns = null, $includePath = null) - { - $this->_namespace = $ns; - $this->_includePath = $includePath; - } - - /** - * Sets the namespace separator used by classes in the namespace of this class loader. - * - * @param string $sep The separator to use. - */ - public function setNamespaceSeparator($sep) - { - $this->_namespaceSeparator = $sep; - } - - /** - * Gets the namespace seperator used by classes in the namespace of this class loader. - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->_namespaceSeparator; - } - - /** - * Sets the base include path for all class files in the namespace of this class loader. - * - * @param string $includePath - */ - public function setIncludePath($includePath) - { - $this->_includePath = $includePath; - } - - /** - * Gets the base include path for all class files in the namespace of this class loader. - * - * @return string $includePath - */ - public function getIncludePath() - { - return $this->_includePath; - } - - /** - * Sets the file extension of class files in the namespace of this class loader. - * - * @param string $fileExtension - */ - public function setFileExtension($fileExtension) - { - $this->_fileExtension = $fileExtension; - } - - /** - * Gets the file extension of class files in the namespace of this class loader. - * - * @return string $fileExtension - */ - public function getFileExtension() - { - return $this->_fileExtension; - } - - /** - * Installs this class loader on the SPL autoload stack. - */ - public function register() - { - spl_autoload_register([$this, 'loadClass']); - } - - /** - * Uninstalls this class loader from the SPL autoloader stack. - */ - public function unregister() - { - spl_autoload_unregister([$this, 'loadClass']); - } - - /** - * Loads the given class or interface. - * - * @param string $className The name of the class to load. - * @return void - */ - public function loadClass($className) - { - if (null === $this->_namespace || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) { - $fileName = ''; - $namespace = ''; - if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) { - $namespace = substr($className, 0, $lastNsPos); - $className = substr($className, $lastNsPos + 1); - $fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; - } - $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension; - - require($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName; - } - } -} diff --git a/app/Library/Poniverse/httpful/.gitignore b/app/Library/Poniverse/httpful/.gitignore deleted file mode 100644 index d1584ef4..00000000 --- a/app/Library/Poniverse/httpful/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.DS_Store -composer.lock -vendor -downloads diff --git a/app/Library/Poniverse/httpful/.travis.yml b/app/Library/Poniverse/httpful/.travis.yml deleted file mode 100644 index ba03761e..00000000 --- a/app/Library/Poniverse/httpful/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: php -before_script: cd tests -php: - - 5.3 - - 5.4 \ No newline at end of file diff --git a/app/Library/Poniverse/httpful/LICENSE.txt b/app/Library/Poniverse/httpful/LICENSE.txt deleted file mode 100644 index 90892706..00000000 --- a/app/Library/Poniverse/httpful/LICENSE.txt +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2012 Nate Good - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/app/Library/Poniverse/httpful/README.md b/app/Library/Poniverse/httpful/README.md deleted file mode 100644 index f816015a..00000000 --- a/app/Library/Poniverse/httpful/README.md +++ /dev/null @@ -1,150 +0,0 @@ -# Httpful - -[![Build Status](https://secure.travis-ci.org/nategood/httpful.png?branch=master)](http://travis-ci.org/nategood/httpful) - -[Httpful](http://phphttpclient.com) is a simple Http Client library for PHP 5.3+. There is an emphasis of readability, simplicity, and flexibility – basically provide the features and flexibility to get the job done and make those features really easy to use. - -Features - - - Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, PATCH and OPTIONS) - - Custom Headers - - Automatic "Smart" Parsing - - Automatic Payload Serialization - - Basic Auth - - Client Side Certificate Auth - - Request "Templates" - -# Sneak Peak - -Here's something to whet your appetite. Search the twitter API for tweets containing "#PHP". Include a trivial header for the heck of it. Notice that the library automatically interprets the response as JSON (can override this if desired) and parses it as an array of objects. - - $url = "http://search.twitter.com/search.json?q=" . urlencode('#PHP'); - $response = Request::get($url) - ->withXTrivialHeader('Just as a demo') - ->send(); - - foreach ($response->body->results as $tweet) { - echo "@{$tweet->from_user} tweets \"{$tweet->text}\"\n"; - } - -# Installation - -## Phar - -A [PHP Archive](http://php.net/manual/en/book.phar.php) (or .phar) file is available for [downloading](http://phphttpclient.com/httpful.phar). Simply [download](http://phphttpclient.com/httpful.phar) the .phar, drop it into your project, and include it like you would any other php file. _This method is ideal smaller projects, one off scripts, and quick API hacking_. - - sendIt(); - ... - -## Composer - -Httpful is PSR-0 compliant and can be installed using [composer](http://getcomposer.org/). Simply add `nategood/httpful` to your composer.json file. _Composer is the sane alternative to PEAR. It is excellent for managing dependancies in larger projects_. - - { - "require": { - "nategood/httpful": "*" - } - } - -## Install from Source - -Because Httpful is PSR-0 compliant, you can also just clone the Httpful repository and use a PSR-0 compatible autoloader to load the library, like [Symfony's](http://symfony.com/doc/current/components/class_loader.html). Alternatively you can use the PSR-0 compliant autoloader included with the Httpful (simply `require("bootstrap.php")`). - -# Show Me More! - -You can checkout the [Httpful Landing Page](http://phphttpclient.com) for more info including many examples and [documentation](http:://phphttpclient.com/docs). - -# Contributing - -Httpful highly encourages sending in pull requests. When submitting a pull request please: - - - All pull requests should target the `dev` branch (not `master`) - - Make sure your code follows the [coding conventions](http://pear.php.net/manual/en/standards.php) - - Please use soft tabs (four spaces) instead of hard tabs - - Make sure you add appropriate test coverage for your changes - - Run all unit tests in the test directory via `phpunit ./tests` - - Include commenting where appropriate and add a descriptive pull request message - -# Changelog - -## 0.2.6 - - - FIX [I #85](https://github.com/nategood/httpful/issues/85) Empty Content Length issue resolved - -## 0.2.5 - - - FEATURE [I #80](https://github.com/nategood/httpful/issues/80) [I #81](https://github.com/nategood/httpful/issues/81) Proxy support added with `useProxy` method. - -## 0.2.4 - - - FEATURE [I #77](https://github.com/nategood/httpful/issues/77) Convenience method for setting a timeout (seconds) `$req->timeoutIn(10);` - - FIX [I #75](https://github.com/nategood/httpful/issues/75) [I #78](https://github.com/nategood/httpful/issues/78) Bug with checking if digest auth is being used. - -## 0.2.3 - - - FIX Overriding default Mime Handlers - - FIX [PR #73](https://github.com/nategood/httpful/pull/73) Parsing http status codes - -## 0.2.2 - - - FEATURE Add support for parsing JSON responses as associative arrays instead of objects - - FEATURE Better support for setting constructor arguments on Mime Handlers - -## 0.2.1 - - - FEATURE [PR #72](https://github.com/nategood/httpful/pull/72) Allow support for custom Accept header - -## 0.2.0 - - - REFACTOR [PR #49](https://github.com/nategood/httpful/pull/49) Broke headers out into their own class - - REFACTOR [PR #54](https://github.com/nategood/httpful/pull/54) Added more specific Exceptions - - FIX [PR #58](https://github.com/nategood/httpful/pull/58) Fixes throwing an error on an empty xml response - - FEATURE [PR #57](https://github.com/nategood/httpful/pull/57) Adds support for digest authentication - -## 0.1.6 - - - Ability to set the number of max redirects via overloading `followRedirects(int max_redirects)` - - Standards Compliant fix to `Accepts` header - - Bug fix for bootstrap process when installed via Composer - -## 0.1.5 - - - Use `DIRECTORY_SEPARATOR` constant [PR #33](https://github.com/nategood/httpful/pull/32) - - [PR #35](https://github.com/nategood/httpful/pull/35) - - Added the raw\_headers property reference to response. - - Compose request header and added raw\_header to Request object. - - Fixed response has errors and added more comments for clarity. - - Fixed header parsing to allow the minimum (status line only) and also cater for the actual CRLF ended headers as per RFC2616. - - Added the perfect test Accept: header for all Acceptable scenarios see @b78e9e82cd9614fbe137c01bde9439c4e16ca323 for details. - - Added default User-Agent header - - `User-Agent: Httpful/0.1.5` + curl version + server software + PHP version - - To bypass this "default" operation simply add a User-Agent to the request headers even a blank User-Agent is sufficient and more than simple enough to produce me thinks. - - Completed test units for additions. - - Added phpunit coverage reporting and helped phpunit auto locate the tests a bit easier. - -## 0.1.4 - - - Add support for CSV Handling [PR #32](https://github.com/nategood/httpful/pull/32) - -## 0.1.3 - - - Handle empty responses in JsonParser and XmlParser - -## 0.1.2 - - - Added support for setting XMLHandler configuration options - - Added examples for overriding XmlHandler and registering a custom parser - - Removed the httpful.php download (deprecated in favor of httpful.phar) - -## 0.1.1 - - - Bug fix serialization default case and phpunit tests - -## 0.1.0 - - - Added Support for Registering Mime Handlers - - Created AbstractMimeHandler type that all Mime Handlers must extend - - Pulled out the parsing/serializing logic from the Request/Response classes into their own MimeHandler classes - - Added ability to register new mime handlers for mime types diff --git a/app/Library/Poniverse/httpful/bootstrap.php b/app/Library/Poniverse/httpful/bootstrap.php deleted file mode 100644 index 10f2a7cf..00000000 --- a/app/Library/Poniverse/httpful/bootstrap.php +++ /dev/null @@ -1,4 +0,0 @@ -setStub($stub); -} catch(Exception $e) { - $phar = false; -} -exit_unless($phar, "Unable to create a phar. Make certain you have phar.readonly=0 set in your ini file."); -$phar->buildFromDirectory(dirname($source_dir)); -echo "[ OK ]\n"; - - - -// Add it to git! -echo "Adding httpful.phar to the repo... "; -$return_code = 0; -passthru("git add $phar_path", $return_code); -exit_unless($return_code === 0, "Unable to add download files to git."); -echo "[ OK ]\n"; -echo "\nBuild completed successfully.\n\n"; diff --git a/app/Library/Poniverse/httpful/composer.json b/app/Library/Poniverse/httpful/composer.json deleted file mode 100644 index 6d61e6e7..00000000 --- a/app/Library/Poniverse/httpful/composer.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "nategood/httpful", - "description": "A Readable, Chainable, REST friendly, PHP HTTP Client", - "homepage": "http://github.com/nategood/httpful", - "license": "MIT", - "keywords": ["http", "curl", "rest", "restful", "api", "requests"], - "version": "0.2.6", - "authors": [ - { - "name": "Nate Good", - "email": "me@nategood.com", - "homepage": "http://nategood.com" - } - ], - "require": { - "php": ">=5.3", - "ext-curl": "*" - }, - "autoload": { - "psr-0": { - "Httpful": "src/" - } - }, - "require-dev": { - "phpunit/phpunit": "*" - } -} diff --git a/app/Library/Poniverse/httpful/examples/freebase.php b/app/Library/Poniverse/httpful/examples/freebase.php deleted file mode 100644 index 96e4152e..00000000 --- a/app/Library/Poniverse/httpful/examples/freebase.php +++ /dev/null @@ -1,12 +0,0 @@ -expectsJson() - ->sendIt(); - -echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n"; diff --git a/app/Library/Poniverse/httpful/examples/github.php b/app/Library/Poniverse/httpful/examples/github.php deleted file mode 100644 index ee98b3e0..00000000 --- a/app/Library/Poniverse/httpful/examples/github.php +++ /dev/null @@ -1,9 +0,0 @@ -send(); - -echo "{$request->body->name} joined GitHub on " . date('M jS', strtotime($request->body->{'created-at'})) ."\n"; diff --git a/app/Library/Poniverse/httpful/examples/override.php b/app/Library/Poniverse/httpful/examples/override.php deleted file mode 100644 index 1a876b4e..00000000 --- a/app/Library/Poniverse/httpful/examples/override.php +++ /dev/null @@ -1,44 +0,0 @@ - 'http://example.com']; -\Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf)); - -// We can also add the parsers with our own... -class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter -{ - /** - * Takes a response body, and turns it into - * a two dimensional array. - * - * @param string $body - * @return mixed - */ - public function parse($body) - { - return str_getcsv($body); - } - - /** - * Takes a two dimensional array and turns it - * into a serialized string to include as the - * body of a request - * - * @param mixed $payload - * @return string - */ - public function serialize($payload) - { - $serialized = ''; - foreach ($payload as $line) { - $serialized .= '"' . implode('","', $line) . '"' . "\n"; - } - return $serialized; - } -} - -\Httpful\Httpful::register('text/csv', new SimpleCsvHandler()); diff --git a/app/Library/Poniverse/httpful/examples/showclix.php b/app/Library/Poniverse/httpful/examples/showclix.php deleted file mode 100644 index fbc200e0..00000000 --- a/app/Library/Poniverse/httpful/examples/showclix.php +++ /dev/null @@ -1,24 +0,0 @@ -expectsType('json') - ->sendIt(); - -// Print out the event details -echo "The event {$response->body->event} will take place on {$response->body->event_start}\n"; - -// Example overriding the default JSON handler with one that encodes the response as an array -\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(['decode_as_array' => true])); - -$response = Request::get($uri) - ->expectsType('json') - ->sendIt(); - -// Print out the event details -echo "The event {$response->body['event']} will take place on {$response->body['event_start']}\n"; diff --git a/app/Library/Poniverse/httpful/src/Httpful/Bootstrap.php b/app/Library/Poniverse/httpful/src/Httpful/Bootstrap.php deleted file mode 100644 index 6c304c48..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Bootstrap.php +++ /dev/null @@ -1,98 +0,0 @@ - - */ -class Bootstrap -{ - - const DIR_GLUE = DIRECTORY_SEPARATOR; - const NS_GLUE = '\\'; - - public static $registered = false; - - /** - * Register the autoloader and any other setup needed - */ - public static function init() - { - spl_autoload_register(['\Httpful\Bootstrap', 'autoload']); - self::registerHandlers(); - } - - /** - * The autoload magic (PSR-0 style) - * - * @param string $classname - */ - public static function autoload($classname) - { - self::_autoload(dirname(dirname(__FILE__)), $classname); - } - - /** - * Register the autoloader and any other setup needed - */ - public static function pharInit() - { - spl_autoload_register(['\Httpful\Bootstrap', 'pharAutoload']); - self::registerHandlers(); - } - - /** - * Phar specific autoloader - * - * @param string $classname - */ - public static function pharAutoload($classname) - { - self::_autoload('phar://httpful.phar', $classname); - } - - /** - * @param string base - * @param string classname - */ - private static function _autoload($base, $classname) - { - $parts = explode(self::NS_GLUE, $classname); - $path = $base . self::DIR_GLUE . implode(self::DIR_GLUE, $parts) . '.php'; - - if (file_exists($path)) { - require_once($path); - } - } - /** - * Register default mime handlers. Is idempotent. - */ - public static function registerHandlers() - { - if (self::$registered === true) { - return; - } - - // @todo check a conf file to load from that instead of - // hardcoding into the library? - $handlers = [ - \Httpful\Mime::JSON => new \Httpful\Handlers\JsonHandler(), - \Httpful\Mime::XML => new \Httpful\Handlers\XmlHandler(), - \Httpful\Mime::FORM => new \Httpful\Handlers\FormHandler(), - \Httpful\Mime::CSV => new \Httpful\Handlers\CsvHandler(), - ]; - - foreach ($handlers as $mime => $handler) { - // Don't overwrite if the handler has already been registered - if (Httpful::hasParserRegistered($mime)) { - continue; - } - Httpful::register($mime, $handler); - } - - self::$registered = true; - } -} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Exception/ConnectionErrorException.php b/app/Library/Poniverse/httpful/src/Httpful/Exception/ConnectionErrorException.php deleted file mode 100644 index aeeb84a8..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Exception/ConnectionErrorException.php +++ /dev/null @@ -1,7 +0,0 @@ - - */ - -namespace Httpful\Handlers; - -class CsvHandler extends MimeHandlerAdapter -{ - /** - * @param string $body - * @return mixed - */ - public function parse($body) - { - if (empty($body)) { - return null; - } - - $parsed = []; - $fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r'); - while (($r = fgetcsv($fp)) !== false) { - $parsed[] = $r; - } - - if (empty($parsed)) { - throw new \Exception("Unable to parse response as CSV"); - } - return $parsed; - } - - /** - * @param mixed $payload - * @return string - */ - public function serialize($payload) - { - $fp = fopen('php://temp/maxmemory:'. (6*1024*1024), 'r+'); - $i = 0; - foreach ($payload as $fields) { - if ($i++ == 0) { - fputcsv($fp, array_keys($fields)); - } - fputcsv($fp, $fields); - } - rewind($fp); - $data = stream_get_contents($fp); - fclose($fp); - return $data; - } -} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Handlers/FormHandler.php b/app/Library/Poniverse/httpful/src/Httpful/Handlers/FormHandler.php deleted file mode 100644 index c8a5cc73..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Handlers/FormHandler.php +++ /dev/null @@ -1,30 +0,0 @@ - - */ - -namespace Httpful\Handlers; - -class FormHandler extends MimeHandlerAdapter -{ - /** - * @param string $body - * @return mixed - */ - public function parse($body) - { - $parsed = []; - parse_str($body, $parsed); - return $parsed; - } - - /** - * @param mixed $payload - * @return string - */ - public function serialize($payload) - { - return http_build_query($payload, null, '&'); - } -} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Handlers/JsonHandler.php b/app/Library/Poniverse/httpful/src/Httpful/Handlers/JsonHandler.php deleted file mode 100644 index ebb46684..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Handlers/JsonHandler.php +++ /dev/null @@ -1,42 +0,0 @@ - - */ - -namespace Httpful\Handlers; - -class JsonHandler extends MimeHandlerAdapter -{ - private $decode_as_array = false; - - public function init(array $args) - { - $this->decode_as_array = !!(array_key_exists('decode_as_array', $args) ? $args['decode_as_array'] : false); - } - - /** - * @param string $body - * @return mixed - */ - public function parse($body) - { - if (empty($body)) { - return null; - } - $parsed = json_decode($body, $this->decode_as_array); - if (is_null($parsed)) { - throw new \Exception("Unable to parse response as JSON"); - } - return $parsed; - } - - /** - * @param mixed $payload - * @return string - */ - public function serialize($payload) - { - return json_encode($payload); - } -} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Handlers/MimeHandlerAdapter.php b/app/Library/Poniverse/httpful/src/Httpful/Handlers/MimeHandlerAdapter.php deleted file mode 100644 index 868bfb95..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Handlers/MimeHandlerAdapter.php +++ /dev/null @@ -1,43 +0,0 @@ -init($args); - } - - /** - * Initial setup of - * @param array $args - */ - public function init(array $args) - { - } - - /** - * @param string $body - * @return mixed - */ - public function parse($body) - { - return $body; - } - - /** - * @param mixed $payload - * @return string - */ - function serialize($payload) - { - return (string) $payload; - } -} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Handlers/README.md b/app/Library/Poniverse/httpful/src/Httpful/Handlers/README.md deleted file mode 100644 index 5542d406..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Handlers/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# Handlers - -Handlers are simple classes that are used to parse response bodies and serialize request payloads. All Handlers must extend the `MimeHandlerAdapter` class and implement two methods: `serialize($payload)` and `parse($response)`. Let's build a very basic Handler to register for the `text/csv` mime type. - - - */ - -namespace Httpful\Handlers; - -class XHtmlHandler extends MimeHandlerAdapter -{ - // @todo add html specific parsing - // see DomDocument::load http://docs.php.net/manual/en/domdocument.loadhtml.php -} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Handlers/XmlHandler.php b/app/Library/Poniverse/httpful/src/Httpful/Handlers/XmlHandler.php deleted file mode 100644 index 04610a3f..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Handlers/XmlHandler.php +++ /dev/null @@ -1,122 +0,0 @@ - - * @author Nathan Good - */ - -namespace Httpful\Handlers; - -class XmlHandler extends MimeHandlerAdapter -{ - /** - * @var string $namespace xml namespace to use with simple_load_string - */ - private $namespace; - - /** - * @var int $libxml_opts see http://www.php.net/manual/en/libxml.constants.php - */ - private $libxml_opts; - - /** - * @param array $conf sets configuration options - */ - public function __construct(array $conf = []) - { - $this->namespace = isset($conf['namespace']) ? $conf['namespace'] : ''; - $this->libxml_opts = isset($conf['libxml_opts']) ? $conf['libxml_opts'] : 0; - } - - /** - * @param string $body - * @return mixed - * @throws Exception if unable to parse - */ - public function parse($body) - { - if (empty($body)) { - return null; - } - $parsed = simplexml_load_string($body, null, $this->libxml_opts, $this->namespace); - if ($parsed === false) { - throw new \Exception("Unable to parse response as XML"); - } - return $parsed; - } - - /** - * @param mixed $payload - * @return string - * @throws Exception if unable to serialize - */ - public function serialize($payload) - { - list($_, $dom) = $this->_future_serializeAsXml($payload); - return $dom->saveXml(); - } - - /** - * @author Zack Douglas - */ - private function _future_serializeAsXml($value, $node = null, $dom = null) - { - if (!$dom) { - $dom = new \DOMDocument; - } - if (!$node) { - if (!is_object($value)) { - $node = $dom->createElement('response'); - $dom->appendChild($node); - } else { - $node = $dom; - } - } - if (is_object($value)) { - $objNode = $dom->createElement(get_class($value)); - $node->appendChild($objNode); - $this->_future_serializeObjectAsXml($value, $objNode, $dom); - } else if (is_array($value)) { - $arrNode = $dom->createElement('array'); - $node->appendChild($arrNode); - $this->_future_serializeArrayAsXml($value, $arrNode, $dom); - } else if (is_bool($value)) { - $node->appendChild($dom->createTextNode($value?'TRUE':'FALSE')); - } else { - $node->appendChild($dom->createTextNode($value)); - } - return [$node, $dom]; - } - /** - * @author Zack Douglas - */ - private function _future_serializeArrayAsXml($value, &$parent, &$dom) - { - foreach ($value as $k => &$v) { - $n = $k; - if (is_numeric($k)) { - $n = "child-{$n}"; - } - $el = $dom->createElement($n); - $parent->appendChild($el); - $this->_future_serializeAsXml($v, $el, $dom); - } - return [$parent, $dom]; - } - /** - * @author Zack Douglas - */ - private function _future_serializeObjectAsXml($value, &$parent, &$dom) - { - $refl = new \ReflectionObject($value); - foreach ($refl->getProperties() as $pr) { - if (!$pr->isPrivate()) { - $el = $dom->createElement($pr->getName()); - $parent->appendChild($el); - $this->_future_serializeAsXml($pr->getValue($value), $el, $dom); - } - } - return [$parent, $dom]; - } -} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Http.php b/app/Library/Poniverse/httpful/src/Httpful/Http.php deleted file mode 100644 index 770a29ed..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Http.php +++ /dev/null @@ -1,85 +0,0 @@ - - */ -class Http -{ - const HEAD = 'HEAD'; - const GET = 'GET'; - const POST = 'POST'; - const PUT = 'PUT'; - const DELETE = 'DELETE'; - const PATCH = 'PATCH'; - const OPTIONS = 'OPTIONS'; - const TRACE = 'TRACE'; - - /** - * @return array of HTTP method strings - */ - public static function safeMethods() - { - return [self::HEAD, self::GET, self::OPTIONS, self::TRACE]; - } - - /** - * @return bool - * @param string HTTP method - */ - public static function isSafeMethod($method) - { - return in_array($method, self::safeMethods()); - } - - /** - * @return bool - * @param string HTTP method - */ - public static function isUnsafeMethod($method) - { - return !in_array($method, self::safeMethods()); - } - - /** - * @return array list of (always) idempotent HTTP methods - */ - public static function idempotentMethods() - { - // Though it is possible to be idempotent, POST - // is not guarunteed to be, and more often than - // not, it is not. - return [self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH]; - } - - /** - * @return bool - * @param string HTTP method - */ - public static function isIdempotent($method) - { - return in_array($method, self::safeidempotentMethodsMethods()); - } - - /** - * @return bool - * @param string HTTP method - */ - public static function isNotIdempotent($method) - { - return !in_array($method, self::idempotentMethods()); - } - - /** - * @deprecated Technically anything *can* have a body, - * they just don't have semantic meaning. So say's Roy - * http://tech.groups.yahoo.com/group/rest-discuss/message/9962 - * - * @return array of HTTP method strings - */ - public static function canHaveBody() - { - return [self::POST, self::PUT, self::PATCH, self::OPTIONS]; - } -} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Httpful.php b/app/Library/Poniverse/httpful/src/Httpful/Httpful.php deleted file mode 100644 index 321b0ef2..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Httpful.php +++ /dev/null @@ -1,47 +0,0 @@ - - */ -class Mime -{ - const JSON = 'application/json'; - const XML = 'application/xml'; - const XHTML = 'application/html+xml'; - const FORM = 'application/x-www-form-urlencoded'; - const PLAIN = 'text/plain'; - const JS = 'text/javascript'; - const HTML = 'text/html'; - const YAML = 'application/x-yaml'; - const CSV = 'text/csv'; - - /** - * Map short name for a mime type - * to a full proper mime type - */ - public static $mimes = [ - 'json' => self::JSON, - 'xml' => self::XML, - 'form' => self::FORM, - 'plain' => self::PLAIN, - 'text' => self::PLAIN, - 'html' => self::HTML, - 'xhtml' => self::XHTML, - 'js' => self::JS, - 'javascript'=> self::JS, - 'yaml' => self::YAML, - 'csv' => self::CSV, - ]; - - /** - * Get the full Mime Type name from a "short name". - * Returns the short if no mapping was found. - * @return string full mime type (e.g. application/json) - * @param string common name for mime type (e.g. json) - */ - public static function getFullMime($short_name) - { - return array_key_exists($short_name, self::$mimes) ? self::$mimes[$short_name] : $short_name; - } - - /** - * @return bool - * @param string $short_name - */ - public static function supportsMimeType($short_name) - { - return array_key_exists($short_name, self::$mimes); - } -} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Request.php b/app/Library/Poniverse/httpful/src/Httpful/Request.php deleted file mode 100644 index c8ed5e80..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Request.php +++ /dev/null @@ -1,1050 +0,0 @@ - - */ -class Request -{ - - // Option constants - const SERIALIZE_PAYLOAD_NEVER = 0; - const SERIALIZE_PAYLOAD_ALWAYS = 1; - const SERIALIZE_PAYLOAD_SMART = 2; - - const MAX_REDIRECTS_DEFAULT = 25; - - public $uri, - $method = Http::GET, - $headers = [], - $raw_headers = '', - $strict_ssl = false, - $content_type, - $expected_type, - $additional_curl_opts = [], - $auto_parse = true, - $serialize_payload_method = self::SERIALIZE_PAYLOAD_SMART, - $username, - $password, - $serialized_payload, - $payload, - $parse_callback, - $error_callback, - $follow_redirects = false, - $max_redirects = self::MAX_REDIRECTS_DEFAULT, - $payload_serializers = []; - - // Options - // private $_options = array( - // 'serialize_payload_method' => self::SERIALIZE_PAYLOAD_SMART - // 'auto_parse' => true - // ); - - // Curl Handle - public $_ch, - $_debug; - - // Template Request object - private static $_template; - - /** - * We made the constructor private to force the factory style. This was - * done to keep the syntax cleaner and better the support the idea of - * "default templates". Very basic and flexible as it is only intended - * for internal use. - * @param array $attrs hash of initial attribute values - */ - private function __construct($attrs = null) - { - if (!is_array($attrs)) { - return; - } - foreach ($attrs as $attr => $value) { - $this->$attr = $value; - } - } - - // Defaults Management - - /** - * Let's you configure default settings for this - * class from a template Request object. Simply construct a - * Request object as much as you want to and then pass it to - * this method. It will then lock in those settings from - * that template object. - * The most common of which may be default mime - * settings or strict ssl settings. - * Again some slight memory overhead incurred here but in the grand - * scheme of things as it typically only occurs once - * @param Request $template - */ - public static function ini(Request $template) - { - self::$_template = clone $template; - } - - /** - * Reset the default template back to the - * library defaults. - */ - public static function resetIni() - { - self::_initializeDefaults(); - } - - /** - * Get default for a value based on the template object - * @return mixed default value - * @param string|null $attr Name of attribute (e.g. mime, headers) - * if null just return the whole template object; - */ - public static function d($attr) - { - return isset($attr) ? self::$_template->$attr : self::$_template; - } - - // Accessors - - /** - * @return bool does the request have a timeout? - */ - public function hasTimeout() - { - return isset($this->timeout); - } - - /** - * @return bool has the internal curl request been initialized? - */ - public function hasBeenInitialized() - { - return isset($this->_ch); - } - - /** - * @return bool Is this request setup for basic auth? - */ - public function hasBasicAuth() - { - return isset($this->password) && isset($this->username); - } - - /** - * @return bool Is this request setup for digest auth? - */ - public function hasDigestAuth() - { - return isset($this->password) && isset($this->username) && $this->additional_curl_opts[CURLOPT_HTTPAUTH] == CURLAUTH_DIGEST; - } - - /** - * Specify a HTTP timeout - * @return Request $this - * @param |int $timeout seconds to timeout the HTTP call - */ - public function timeout($timeout) - { - $this->timeout = $timeout; - return $this; - } - - // alias timeout - public function timeoutIn($seconds) - { - return $this->timeout($seconds); - } - - /** - * If the response is a 301 or 302 redirect, automatically - * send off another request to that location - * @return Request $this - * @param bool|int $follow follow or not to follow or maximal number of redirects - */ - public function followRedirects($follow = true) - { - $this->max_redirects = $follow === true ? self::MAX_REDIRECTS_DEFAULT : max(0, $follow); - $this->follow_redirects = (bool) $follow; - return $this; - } - - /** - * @return Request $this - * @see Request::followRedirects() - */ - public function doNotFollowRedirects() - { - return $this->followRedirects(false); - } - - /** - * Actually send off the request, and parse the response - * @return string|associative array of parsed results - * @throws ConnectionErrorException when unable to parse or communicate w server - */ - public function send() - { - if (!$this->hasBeenInitialized()) { - $this->_curlPrep(); - } - - $result = curl_exec($this->_ch); - - if ($result === false) { - $this->_error(curl_error($this->_ch)); - throw new ConnectionErrorException('Unable to connect.'); - } - - $info = curl_getinfo($this->_ch); - $response = explode("\r\n\r\n", $result, 2 + $info['redirect_count']); - - $body = array_pop($response); - $headers = array_pop($response); - - return new Response($body, $headers, $this); - } - public function sendIt() - { - return $this->send(); - } - - // Setters - - /** - * @return Request this - * @param string $uri - */ - public function uri($uri) - { - $this->uri = $uri; - return $this; - } - - /** - * User Basic Auth. - * Only use when over SSL/TSL/HTTPS. - * @return Request this - * @param string $username - * @param string $password - */ - public function basicAuth($username, $password) - { - $this->username = $username; - $this->password = $password; - return $this; - } - // @alias of basicAuth - public function authenticateWith($username, $password) - { - return $this->basicAuth($username, $password); - } - // @alias of basicAuth - public function authenticateWithBasic($username, $password) - { - return $this->basicAuth($username, $password); - } - - /** - * User Digest Auth. - * @return Request this - * @param string $username - * @param string $password - */ - public function digestAuth($username, $password) - { - $this->addOnCurlOption(CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); - return $this->basicAuth($username, $password); - } - - // @alias of digestAuth - public function authenticateWithDigest($username, $password) - { - return $this->digestAuth($username, $password); - } - - /** - * @return is this request setup for client side cert? - */ - public function hasClientSideCert() - { - return isset($this->client_cert) && isset($this->client_key); - } - - /** - * Use Client Side Cert Authentication - * @return Request $this - * @param string $key file path to client key - * @param string $cert file path to client cert - * @param string $passphrase for client key - * @param string $encoding default PEM - */ - public function clientSideCert($cert, $key, $passphrase = null, $encoding = 'PEM') - { - $this->client_cert = $cert; - $this->client_key = $key; - $this->client_passphrase = $passphrase; - $this->client_encoding = $encoding; - - return $this; - } - // @alias of basicAuth - public function authenticateWithCert($cert, $key, $passphrase = null, $encoding = 'PEM') - { - return $this->clientSideCert($cert, $key, $passphrase, $encoding); - } - - /** - * Set the body of the request - * @return Request this - * @param mixed $payload - * @param string $mimeType - */ - public function body($payload, $mimeType = null) - { - $this->mime($mimeType); - $this->payload = $payload; - // Iserntentially don't call _serializePayload yet. Wait until - // we actually send off the request to convert payload to string. - // At that time, the `serialized_payload` is set accordingly. - return $this; - } - - /** - * Helper function to set the Content type and Expected as same in - * one swoop - * @return Request this - * @param string $mime mime type to use for content type and expected return type - */ - public function mime($mime) - { - if (empty($mime)) { - return $this; - } - $this->content_type = $this->expected_type = Mime::getFullMime($mime); - return $this; - } - // @alias of mime - public function sendsAndExpectsType($mime) - { - return $this->mime($mime); - } - // @alias of mime - public function sendsAndExpects($mime) - { - return $this->mime($mime); - } - - /** - * Set the method. Shouldn't be called often as the preferred syntax - * for instantiation is the method specific factory methods. - * @return Request this - * @param string $method - */ - public function method($method) - { - if (empty($method)) { - return $this; - } - $this->method = $method; - return $this; - } - - /** - * @return Request this - * @param string $mime - */ - public function expects($mime) - { - if (empty($mime)) { - return $this; - } - $this->expected_type = Mime::getFullMime($mime); - return $this; - } - // @alias of expects - public function expectsType($mime) - { - return $this->expects($mime); - } - - /** - * @return Request this - * @param string $mime - */ - public function contentType($mime) - { - if (empty($mime)) { - return $this; - } - $this->content_type = Mime::getFullMime($mime); - return $this; - } - // @alias of contentType - public function sends($mime) - { - return $this->contentType($mime); - } - // @alias of contentType - public function sendsType($mime) - { - return $this->contentType($mime); - } - - /** - * Do we strictly enforce SSL verification? - * @return Request this - * @param bool $strict - */ - public function strictSSL($strict) - { - $this->strict_ssl = $strict; - return $this; - } - public function withoutStrictSSL() - { - return $this->strictSSL(false); - } - public function withStrictSSL() - { - return $this->strictSSL(true); - } - - /** - * Use proxy configuration - * @return Request this - * @param string $proxy_host Hostname or address of the proxy - * @param number $proxy_port Port of the proxy. Default 80 - * @param string $auth_type Authentication type or null. Accepted values are CURLAUTH_BASIC, CURLAUTH_NTLM. Default null, no authentication - * @param string $auth_username Authentication username. Default null - * @param string $auth_password Authentication password. Default null - */ - public function useProxy($proxy_host, $proxy_port = 80, $auth_type = null, $auth_username = null, $auth_password = null) - { - $this->addOnCurlOption(CURLOPT_PROXY, "{$proxy_host}:{$proxy_port}"); - if (in_array($auth_type, [CURLAUTH_BASIC,CURLAUTH_NTLM])) { - $this->addOnCurlOption(CURLOPT_PROXYAUTH, $auth_type) - ->addOnCurlOption(CURLOPT_PROXYUSERPWD, "{$auth_username}:{$auth_password}"); - } - return $this; - } - - /** - * @return is this request setup for using proxy? - */ - public function hasProxy() - { - return is_string($this->additional_curl_opts[CURLOPT_PROXY]); - } - - /** - * Determine how/if we use the built in serialization by - * setting the serialize_payload_method - * The default (SERIALIZE_PAYLOAD_SMART) is... - * - if payload is not a scalar (object/array) - * use the appropriate serialize method according to - * the Content-Type of this request. - * - if the payload IS a scalar (int, float, string, bool) - * than just return it as is. - * When this option is set SERIALIZE_PAYLOAD_ALWAYS, - * it will always use the appropriate - * serialize option regardless of whether payload is scalar or not - * When this option is set SERIALIZE_PAYLOAD_NEVER, - * it will never use any of the serialization methods. - * Really the only use for this is if you want the serialize methods - * to handle strings or not (e.g. Blah is not valid JSON, but "Blah" - * is). Forcing the serialization helps prevent that kind of error from - * happening. - * @return Request $this - * @param int $mode - */ - public function serializePayload($mode) - { - $this->serialize_payload_method = $mode; - return $this; - } - - /** - * @see Request::serializePayload() - * @return Request - */ - public function neverSerializePayload() - { - return $this->serializePayload(self::SERIALIZE_PAYLOAD_NEVER); - } - - /** - * This method is the default behavior - * @see Request::serializePayload() - * @return Request - */ - public function smartSerializePayload() - { - return $this->serializePayload(self::SERIALIZE_PAYLOAD_SMART); - } - - /** - * @see Request::serializePayload() - * @return Request - */ - public function alwaysSerializePayload() - { - return $this->serializePayload(self::SERIALIZE_PAYLOAD_ALWAYS); - } - - /** - * Add an additional header to the request - * Can also use the cleaner syntax of - * $Request->withMyHeaderName($my_value); - * @see Request::__call() - * - * @return Request this - * @param string $header_name - * @param string $value - */ - public function addHeader($header_name, $value) - { - $this->headers[$header_name] = $value; - return $this; - } - - /** - * Add group of headers all at once. Note: This is - * here just as a convenience in very specific cases. - * The preferred "readable" way would be to leverage - * the support for custom header methods. - * @return Response $this - * @param array $headers - */ - public function addHeaders(array $headers) - { - foreach ($headers as $header => $value) { - $this->addHeader($header, $value); - } - return $this; - } - - /** - * @return Request - * @param bool $auto_parse perform automatic "smart" - * parsing based on Content-Type or "expectedType" - * If not auto parsing, Response->body returns the body - * as a string. - */ - public function autoParse($auto_parse = true) - { - $this->auto_parse = $auto_parse; - return $this; - } - - /** - * @see Request::autoParse() - * @return Request - */ - public function withoutAutoParsing() - { - return $this->autoParse(false); - } - - /** - * @see Request::autoParse() - * @return Request - */ - public function withAutoParsing() - { - return $this->autoParse(true); - } - - /** - * Use a custom function to parse the response. - * @return Request this - * @param \Closure $callback Takes the raw body of - * the http response and returns a mixed - */ - public function parseWith(\Closure $callback) - { - $this->parse_callback = $callback; - return $this; - } - - /** - * @see Request::parseResponsesWith() - * @return Request $this - * @param \Closure $callback - */ - public function parseResponsesWith(\Closure $callback) - { - return $this->parseWith($callback); - } - - /** - * Register a callback that will be used to serialize the payload - * for a particular mime type. When using "*" for the mime - * type, it will use that parser for all responses regardless of the mime - * type. If a custom '*' and 'application/json' exist, the custom - * 'application/json' would take precedence over the '*' callback. - * - * @return Request $this - * @param string $mime mime type we're registering - * @param Closure $callback takes one argument, $payload, - * which is the payload that we'll be - */ - public function registerPayloadSerializer($mime, \Closure $callback) - { - $this->payload_serializers[Mime::getFullMime($mime)] = $callback; - return $this; - } - - /** - * @see Request::registerPayloadSerializer() - * @return Request $this - * @param Closure $callback - */ - public function serializePayloadWith(\Closure $callback) - { - return $this->regregisterPayloadSerializer('*', $callback); - } - - /** - * Magic method allows for neatly setting other headers in a - * similar syntax as the other setters. This method also allows - * for the sends* syntax. - * @return Request this - * @param string $method "missing" method name called - * the method name called should be the name of the header that you - * are trying to set in camel case without dashes e.g. to set a - * header for Content-Type you would use contentType() or more commonly - * to add a custom header like X-My-Header, you would use xMyHeader(). - * To promote readability, you can optionally prefix these methods with - * "with" (e.g. withXMyHeader("blah") instead of xMyHeader("blah")). - * @param array $args in this case, there should only ever be 1 argument provided - * and that argument should be a string value of the header we're setting - */ - public function __call($method, $args) - { - // This method supports the sends* methods - // like sendsJSON, sendsForm - //!method_exists($this, $method) && - if (substr($method, 0, 5) === 'sends') { - $mime = strtolower(substr($method, 5)); - if (Mime::supportsMimeType($mime)) { - $this->sends(Mime::getFullMime($mime)); - return $this; - } - // else { - // throw new \Exception("Unsupported Content-Type $mime"); - // } - } - if (substr($method, 0, 7) === 'expects') { - $mime = strtolower(substr($method, 7)); - if (Mime::supportsMimeType($mime)) { - $this->expects(Mime::getFullMime($mime)); - return $this; - } - // else { - // throw new \Exception("Unsupported Content-Type $mime"); - // } - } - - // This method also adds the custom header support as described in the - // method comments - if (count($args) === 0) { - return; - } - - // Strip the sugar. If it leads with "with", strip. - // This is okay because: No defined HTTP headers begin with with, - // and if you are defining a custom header, the standard is to prefix it - // with an "X-", so that should take care of any collisions. - if (substr($method, 0, 4) === 'with') { - $method = substr($method, 4); - } - - // Precede upper case letters with dashes, uppercase the first letter of method - $header = ucwords(implode('-', preg_split('/([A-Z][^A-Z]*)/', $method, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY))); - $this->addHeader($header, $args[0]); - return $this; - } - - // Internal Functions - - /** - * This is the default template to use if no - * template has been provided. The template - * tells the class which default values to use. - * While there is a slight overhead for object - * creation once per execution (not once per - * Request instantiation), it promotes readability - * and flexibility within the class. - */ - private static function _initializeDefaults() - { - // This is the only place you will - // see this constructor syntax. It - // is only done here to prevent infinite - // recusion. Do not use this syntax elsewhere. - // It goes against the whole readability - // and transparency idea. - self::$_template = new Request(['method' => Http::GET]); - - // This is more like it... - self::$_template - ->withoutStrictSSL(); - } - - /** - * Set the defaults on a newly instantiated object - * Doesn't copy variables prefixed with _ - * @return Request this - */ - private function _setDefaults() - { - if (!isset(self::$_template)) { - self::_initializeDefaults(); - } - foreach (self::$_template as $k => $v) { - if ($k[0] != '_') { - $this->$k = $v; - } - } - return $this; - } - - private function _error($error) - { - // Default actions write to error log - // TODO add in support for various Loggers - error_log($error); - } - - /** - * Factory style constructor works nicer for chaining. This - * should also really only be used internally. The Request::get, - * Request::post syntax is preferred as it is more readable. - * @return Request - * @param string $method Http Method - * @param string $mime Mime Type to Use - */ - public static function init($method = null, $mime = null) - { - // Setup our handlers, can call it here as it's idempotent - Bootstrap::init(); - - // Setup the default template if need be - if (!isset(self::$_template)) { - self::_initializeDefaults(); - } - - $request = new Request(); - return $request - ->_setDefaults() - ->method($method) - ->sendsType($mime) - ->expectsType($mime); - } - - /** - * Does the heavy lifting. Uses de facto HTTP - * library cURL to set up the HTTP request. - * Note: It does NOT actually send the request - * @return Request $this; - */ - public function _curlPrep() - { - // Check for required stuff - if (!isset($this->uri)) { - throw new \Exception('Attempting to send a request before defining a URI endpoint.'); - } - - $ch = curl_init($this->uri); - - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->method); - - if ($this->hasBasicAuth()) { - curl_setopt($ch, CURLOPT_USERPWD, $this->username . ':' . $this->password); - } - - if ($this->hasClientSideCert()) { - if (!file_exists($this->client_key)) { - throw new \Exception('Could not read Client Key'); - } - - if (!file_exists($this->client_cert)) { - throw new \Exception('Could not read Client Certificate'); - } - - curl_setopt($ch, CURLOPT_SSLCERTTYPE, $this->client_encoding); - curl_setopt($ch, CURLOPT_SSLKEYTYPE, $this->client_encoding); - curl_setopt($ch, CURLOPT_SSLCERT, $this->client_cert); - curl_setopt($ch, CURLOPT_SSLKEY, $this->client_key); - curl_setopt($ch, CURLOPT_SSLKEYPASSWD, $this->client_passphrase); - // curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->client_cert_passphrase); - } - - if ($this->hasTimeout()) { - curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); - } - - if ($this->follow_redirects) { - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($ch, CURLOPT_MAXREDIRS, $this->max_redirects); - } - - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->strict_ssl); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - - // https://github.com/nategood/httpful/issues/84 - // set Content-Length to the size of the payload if present - if (isset($this->payload)) { - $this->serialized_payload = $this->_serializePayload($this->payload); - curl_setopt($ch, CURLOPT_POSTFIELDS, $this->serialized_payload); - $this->headers['Content-Length'] = strlen($this->serialized_payload); - } - - $headers = []; - // https://github.com/nategood/httpful/issues/37 - // Except header removes any HTTP 1.1 Continue from response headers - $headers[] = 'Expect:'; - - if (!isset($this->headers['User-Agent'])) { - $headers[] = $this->buildUserAgent(); - } - - $headers[] = "Content-Type: {$this->content_type}"; - - // allow custom Accept header if set - if (!isset($this->headers['Accept'])) { - // http://pretty-rfc.herokuapp.com/RFC2616#header.accept - $accept = 'Accept: */*; q=0.5, text/plain; q=0.8, text/html;level=3;'; - - if (!empty($this->expected_type)) { - $accept .= "q=0.9, {$this->expected_type}"; - } - - $headers[] = $accept; - } - - // Solve a bug on squid proxy, NONE/411 when miss content length - if (!isset($this->headers['Content-Length'])) { - $this->headers['Content-Length'] = 0; - } - - foreach ($this->headers as $header => $value) { - $headers[] = "$header: $value"; - } - - $url = \parse_url($this->uri); - $path = (isset($url['path']) ? $url['path'] : '/').(isset($url['query']) ? '?'.$url['query'] : ''); - $this->raw_headers = "{$this->method} $path HTTP/1.1\r\n"; - $host = (isset($url['host']) ? $url['host'] : 'localhost').(isset($url['port']) ? ':'.$url['port'] : ''); - $this->raw_headers .= "Host: $host\r\n"; - $this->raw_headers .= \implode("\r\n", $headers); - $this->raw_headers .= "\r\n"; - - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - - if ($this->_debug) { - curl_setopt($ch, CURLOPT_VERBOSE, true); - } - - curl_setopt($ch, CURLOPT_HEADER, 1); - - // If there are some additional curl opts that the user wants - // to set, we can tack them in here - foreach ($this->additional_curl_opts as $curlopt => $curlval) { - curl_setopt($ch, $curlopt, $curlval); - } - - $this->_ch = $ch; - - return $this; - } - - public function buildUserAgent() - { - $user_agent = 'User-Agent: Httpful/' . Httpful::VERSION . ' (cURL/'; - $curl = \curl_version(); - - if (isset($curl['version'])) { - $user_agent .= $curl['version']; - } else { - $user_agent .= '?.?.?'; - } - - $user_agent .= ' PHP/'. PHP_VERSION . ' (' . PHP_OS . ')'; - - if (isset($_SERVER['SERVER_SOFTWARE'])) { - $user_agent .= ' ' . \preg_replace( - '~PHP/[\d\.]+~U', - '', - $_SERVER['SERVER_SOFTWARE'] - ); - } else { - if (isset($_SERVER['TERM_PROGRAM'])) { - $user_agent .= " {$_SERVER['TERM_PROGRAM']}"; - } - - if (isset($_SERVER['TERM_PROGRAM_VERSION'])) { - $user_agent .= "/{$_SERVER['TERM_PROGRAM_VERSION']}"; - } - } - - if (isset($_SERVER['HTTP_USER_AGENT'])) { - $user_agent .= " {$_SERVER['HTTP_USER_AGENT']}"; - } - - $user_agent .= ')'; - - return $user_agent; - } - - /** - * Semi-reluctantly added this as a way to add in curl opts - * that are not otherwise accessible from the rest of the API. - * @return Request $this - * @param string $curlopt - * @param mixed $curloptval - */ - public function addOnCurlOption($curlopt, $curloptval) - { - $this->additional_curl_opts[$curlopt] = $curloptval; - return $this; - } - - /** - * Turn payload from structured data into - * a string based on the current Mime type. - * This uses the auto_serialize option to determine - * it's course of action. See serialize method for more. - * Renamed from _detectPayload to _serializePayload as of - * 2012-02-15. - * - * Added in support for custom payload serializers. - * The serialize_payload_method stuff still holds true though. - * @see Request::registerPayloadSerializer() - * - * @return string - * @param mixed $payload - */ - private function _serializePayload($payload) - { - if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER) { - return $payload; - } - - // When we are in "smart" mode, don't serialize strings/scalars, assume they are already serialized - if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload)) { - return $payload; - } - - // Use a custom serializer if one is registered for this mime type - if (isset($this->payload_serializers['*']) || isset($this->payload_serializers[$this->content_type])) { - $key = isset($this->payload_serializers[$this->content_type]) ? $this->content_type : '*'; - return call_user_func($this->payload_serializers[$key], $payload); - } - - return Httpful::get($this->content_type)->serialize($payload); - } - - /** - * HTTP Method Get - * @return Request - * @param string $uri optional uri to use - * @param string $mime expected - */ - public static function get($uri, $mime = null) - { - return self::init(Http::GET)->uri($uri)->mime($mime); - } - - - /** - * Like Request:::get, except that it sends off the request as well - * returning a response - * @return Response - * @param string $uri optional uri to use - * @param string $mime expected - */ - public static function getQuick($uri, $mime = null) - { - return self::get($uri, $mime)->send(); - } - - /** - * HTTP Method Post - * @return Request - * @param string $uri optional uri to use - * @param string $payload data to send in body of request - * @param string $mime MIME to use for Content-Type - */ - public static function post($uri, $payload = null, $mime = null) - { - return self::init(Http::POST)->uri($uri)->body($payload, $mime); - } - - /** - * HTTP Method Put - * @return Request - * @param string $uri optional uri to use - * @param string $payload data to send in body of request - * @param string $mime MIME to use for Content-Type - */ - public static function put($uri, $payload = null, $mime = null) - { - return self::init(Http::PUT)->uri($uri)->body($payload, $mime); - } - - /** - * HTTP Method Patch - * @return Request - * @param string $uri optional uri to use - * @param string $payload data to send in body of request - * @param string $mime MIME to use for Content-Type - */ - public static function patch($uri, $payload = null, $mime = null) - { - return self::init(Http::PATCH)->uri($uri)->body($payload, $mime); - } - - /** - * HTTP Method Delete - * @return Request - * @param string $uri optional uri to use - */ - public static function delete($uri, $mime = null) - { - return self::init(Http::DELETE)->uri($uri)->mime($mime); - } - - /** - * HTTP Method Head - * @return Request - * @param string $uri optional uri to use - */ - public static function head($uri) - { - return self::init(Http::HEAD)->uri($uri); - } - - /** - * HTTP Method Options - * @return Request - * @param string $uri optional uri to use - */ - public static function options($uri) - { - return self::init(Http::OPTIONS)->uri($uri); - } -} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Response.php b/app/Library/Poniverse/httpful/src/Httpful/Response.php deleted file mode 100644 index d130198b..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Response.php +++ /dev/null @@ -1,189 +0,0 @@ - - */ -class Response -{ - - public $body, - $raw_body, - $headers, - $raw_headers, - $request, - $code = 0, - $content_type, - $parent_type, - $charset, - $is_mime_vendor_specific = false, - $is_mime_personal = false; - - private $parsers; - /** - * @param string $body - * @param string $headers - * @param Request $request - */ - public function __construct($body, $headers, Request $request) - { - $this->request = $request; - $this->raw_headers = $headers; - $this->raw_body = $body; - - $this->code = $this->_parseCode($headers); - $this->headers = Response\Headers::fromString($headers); - - $this->_interpretHeaders(); - - $this->body = $this->_parse($body); - } - - /** - * Status Code Definitions - * - * Informational 1xx - * Successful 2xx - * Redirection 3xx - * Client Error 4xx - * Server Error 5xx - * - * http://pretty-rfc.herokuapp.com/RFC2616#status.codes - * - * @return bool Did we receive a 4xx or 5xx? - */ - public function hasErrors() - { - return $this->code >= 400; - } - - /** - * @return return bool - */ - public function hasBody() - { - return !empty($this->body); - } - - /** - * Parse the response into a clean data structure - * (most often an associative array) based on the expected - * Mime type. - * @return array|string|object the response parse accordingly - * @param string Http response body - */ - public function _parse($body) - { - // If the user decided to forgo the automatic - // smart parsing, short circuit. - if (!$this->request->auto_parse) { - return $body; - } - - // If provided, use custom parsing callback - if (isset($this->request->parse_callback)) { - return call_user_func($this->request->parse_callback, $body); - } - - // Decide how to parse the body of the response in the following order - // 1. If provided, use the mime type specifically set as part of the `Request` - // 2. If a MimeHandler is registered for the content type, use it - // 3. If provided, use the "parent type" of the mime type from the response - // 4. Default to the content-type provided in the response - $parse_with = $this->request->expected_type; - if (empty($this->request->expected_type)) { - $parse_with = Httpful::hasParserRegistered($this->content_type) - ? $this->content_type - : $this->parent_type; - } - - return Httpful::get($parse_with)->parse($body); - } - - /** - * Parse text headers from response into - * array of key value pairs - * @return array parse headers - * @param string $headers raw headers - */ - public function _parseHeaders($headers) - { - $headers = preg_split("/(\r|\n)+/", $headers, -1, \PREG_SPLIT_NO_EMPTY); - $parse_headers = []; - for ($i = 1; $i < count($headers); $i++) { - list($key, $raw_value) = explode(':', $headers[$i], 2); - $key = trim($key); - $value = trim($raw_value); - if (array_key_exists($key, $parse_headers)) { - // See HTTP RFC Sec 4.2 Paragraph 5 - // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 - // If a header appears more than once, it must also be able to - // be represented as a single header with a comma-separated - // list of values. We transform accordingly. - $parse_headers[$key] .= ',' . $value; - } else { - $parse_headers[$key] = $value; - } - } - return $parse_headers; - } - - public function _parseCode($headers) - { - $parts = explode(' ', substr($headers, 0, strpos($headers, "\r\n"))); - if (count($parts) < 2 || !is_numeric($parts[1])) { - throw new \Exception("Unable to parse response code from HTTP response due to malformed response"); - } - return intval($parts[1]); - } - - /** - * After we've parse the headers, let's clean things - * up a bit and treat some headers specially - */ - public function _interpretHeaders() - { - // Parse the Content-Type and charset - $content_type = isset($this->headers['Content-Type']) ? $this->headers['Content-Type'] : ''; - $content_type = explode(';', $content_type); - - $this->content_type = $content_type[0]; - if (count($content_type) == 2 && strpos($content_type[1], '=') !== false) { - list($nill, $this->charset) = explode('=', $content_type[1]); - } - - // RFC 2616 states "text/*" Content-Types should have a default - // charset of ISO-8859-1. "application/*" and other Content-Types - // are assumed to have UTF-8 unless otherwise specified. - // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1 - // http://www.w3.org/International/O-HTTP-charset.en.php - if (!isset($this->charset)) { - $this->charset = substr($this->content_type, 5) === 'text/' ? 'iso-8859-1' : 'utf-8'; - } - - // Is vendor type? Is personal type? - if (strpos($this->content_type, '/') !== false) { - list($type, $sub_type) = explode('/', $this->content_type); - $this->is_mime_vendor_specific = substr($sub_type, 0, 4) === 'vnd.'; - $this->is_mime_personal = substr($sub_type, 0, 4) === 'prs.'; - } - - // Parent type (e.g. xml for application/vnd.github.message+xml) - $this->parent_type = $this->content_type; - if (strpos($this->content_type, '+') !== false) { - list($vendor, $this->parent_type) = explode('+', $this->content_type, 2); - $this->parent_type = Mime::getFullMime($this->parent_type); - } - } - - /** - * @return string - */ - public function __toString() - { - return $this->raw_body; - } -} diff --git a/app/Library/Poniverse/httpful/src/Httpful/Response/Headers.php b/app/Library/Poniverse/httpful/src/Httpful/Response/Headers.php deleted file mode 100644 index f7b1f7ab..00000000 --- a/app/Library/Poniverse/httpful/src/Httpful/Response/Headers.php +++ /dev/null @@ -1,58 +0,0 @@ -headers = $headers; - } - - public static function fromString($string) - { - $lines = preg_split("/(\r|\n)+/", $string, -1, PREG_SPLIT_NO_EMPTY); - array_shift($lines); // HTTP HEADER - $headers = []; - foreach ($lines as $line) { - list($name, $value) = explode(':', $line, 2); - $headers[strtolower(trim($name))] = trim($value); - } - return new self($headers); - } - - public function offsetExists($offset) - { - return isset($this->headers[strtolower($offset)]); - } - - public function offsetGet($offset) - { - if (isset($this->headers[$name = strtolower($offset)])) { - return $this->headers[$name]; - } - } - - public function offsetSet($offset, $value) - { - throw new \Exception("Headers are read-only."); - } - - public function offsetUnset($offset) - { - throw new \Exception("Headers are read-only."); - } - - public function count() - { - return count($this->headers); - } - - public function toArray() - { - return $this->headers; - } -} diff --git a/app/Library/Poniverse/httpful/tests/Httpful/HttpfulTest.php b/app/Library/Poniverse/httpful/tests/Httpful/HttpfulTest.php deleted file mode 100644 index 0478af2f..00000000 --- a/app/Library/Poniverse/httpful/tests/Httpful/HttpfulTest.php +++ /dev/null @@ -1,462 +0,0 @@ - - */ -namespace Httpful\Test; - -require(dirname(dirname(dirname(__FILE__))) . '/bootstrap.php'); -\Httpful\Bootstrap::init(); - -use Httpful\Httpful; -use Httpful\Request; -use Httpful\Mime; -use Httpful\Http; -use Httpful\Response; - -class HttpfulTest extends \PHPUnit_Framework_TestCase -{ - const TEST_SERVER = '127.0.0.1:8008'; - const TEST_URL = 'http://127.0.0.1:8008'; - const TEST_URL_400 = 'http://127.0.0.1:8008/400'; - - const SAMPLE_JSON_HEADER = - "HTTP/1.1 200 OK -Content-Type: application/json -Connection: keep-alive -Transfer-Encoding: chunked\r\n"; - const SAMPLE_JSON_RESPONSE = '{"key":"value","object":{"key":"value"},"array":[1,2,3,4]}'; - const SAMPLE_CSV_HEADER = - "HTTP/1.1 200 OK -Content-Type: text/csv -Connection: keep-alive -Transfer-Encoding: chunked\r\n"; - const SAMPLE_CSV_RESPONSE = - "Key1,Key2 -Value1,Value2 -\"40.0\",\"Forty\""; - const SAMPLE_XML_RESPONSE = '2a stringTRUE'; - const SAMPLE_XML_HEADER = - "HTTP/1.1 200 OK -Content-Type: application/xml -Connection: keep-alive -Transfer-Encoding: chunked\r\n"; - const SAMPLE_VENDOR_HEADER = - "HTTP/1.1 200 OK -Content-Type: application/vnd.nategood.message+xml -Connection: keep-alive -Transfer-Encoding: chunked\r\n"; - const SAMPLE_VENDOR_TYPE = "application/vnd.nategood.message+xml"; - const SAMPLE_MULTI_HEADER = - "HTTP/1.1 200 OK -Content-Type: application/json -Connection: keep-alive -Transfer-Encoding: chunked -X-My-Header:Value1 -X-My-Header:Value2\r\n"; - function testInit() - { - $r = Request::init(); - // Did we get a 'Request' object? - $this->assertEquals('Httpful\Request', get_class($r)); - } - - function testMethods() - { - $valid_methods = ['get', 'post', 'delete', 'put', 'options', 'head']; - $url = 'http://example.com/'; - foreach ($valid_methods as $method) { - $r = call_user_func(['Httpful\Request', $method], $url); - $this->assertEquals('Httpful\Request', get_class($r)); - $this->assertEquals(strtoupper($method), $r->method); - } - } - - function testDefaults() - { - // Our current defaults are as follows - $r = Request::init(); - $this->assertEquals(Http::GET, $r->method); - $this->assertFalse($r->strict_ssl); - } - - function testShortMime() - { - // Valid short ones - $this->assertEquals(Mime::JSON, Mime::getFullMime('json')); - $this->assertEquals(Mime::XML, Mime::getFullMime('xml')); - $this->assertEquals(Mime::HTML, Mime::getFullMime('html')); - $this->assertEquals(Mime::CSV, Mime::getFullMime('csv')); - - // Valid long ones - $this->assertEquals(Mime::JSON, Mime::getFullMime(Mime::JSON)); - $this->assertEquals(Mime::XML, Mime::getFullMime(Mime::XML)); - $this->assertEquals(Mime::HTML, Mime::getFullMime(Mime::HTML)); - $this->assertEquals(Mime::CSV, Mime::getFullMime(Mime::CSV)); - - // No false positives - $this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::HTML)); - $this->assertNotEquals(Mime::JSON, Mime::getFullMime(Mime::XML)); - $this->assertNotEquals(Mime::HTML, Mime::getFullMime(Mime::JSON)); - $this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::CSV)); - } - - function testSettingStrictSsl() - { - $r = Request::init() - ->withStrictSsl(); - - $this->assertTrue($r->strict_ssl); - - $r = Request::init() - ->withoutStrictSsl(); - - $this->assertFalse($r->strict_ssl); - } - - function testSendsAndExpectsType() - { - $r = Request::init() - ->sendsAndExpectsType(Mime::JSON); - $this->assertEquals(Mime::JSON, $r->expected_type); - $this->assertEquals(Mime::JSON, $r->content_type); - - $r = Request::init() - ->sendsAndExpectsType('html'); - $this->assertEquals(Mime::HTML, $r->expected_type); - $this->assertEquals(Mime::HTML, $r->content_type); - - $r = Request::init() - ->sendsAndExpectsType('form'); - $this->assertEquals(Mime::FORM, $r->expected_type); - $this->assertEquals(Mime::FORM, $r->content_type); - - $r = Request::init() - ->sendsAndExpectsType('application/x-www-form-urlencoded'); - $this->assertEquals(Mime::FORM, $r->expected_type); - $this->assertEquals(Mime::FORM, $r->content_type); - - $r = Request::init() - ->sendsAndExpectsType(Mime::CSV); - $this->assertEquals(Mime::CSV, $r->expected_type); - $this->assertEquals(Mime::CSV, $r->content_type); - } - - function testIni() - { - // Test setting defaults/templates - - // Create the template - $template = Request::init() - ->method(Http::POST) - ->withStrictSsl() - ->expectsType(Mime::HTML) - ->sendsType(Mime::FORM); - - Request::ini($template); - - $r = Request::init(); - - $this->assertTrue($r->strict_ssl); - $this->assertEquals(Http::POST, $r->method); - $this->assertEquals(Mime::HTML, $r->expected_type); - $this->assertEquals(Mime::FORM, $r->content_type); - - // Test the default accessor as well - $this->assertTrue(Request::d('strict_ssl')); - $this->assertEquals(Http::POST, Request::d('method')); - $this->assertEquals(Mime::HTML, Request::d('expected_type')); - $this->assertEquals(Mime::FORM, Request::d('content_type')); - - Request::resetIni(); - } - - function testAccept() - { - $r = Request::get('http://example.com/') - ->expectsType(Mime::JSON); - - $this->assertEquals(Mime::JSON, $r->expected_type); - $r->_curlPrep(); - $this->assertContains('application/json', $r->raw_headers); - } - - function testCustomAccept() - { - $accept = 'application/api-1.0+json'; - $r = Request::get('http://example.com/') - ->addHeader('Accept', $accept); - - $r->_curlPrep(); - $this->assertContains($accept, $r->raw_headers); - $this->assertEquals($accept, $r->headers['Accept']); - } - - function testUserAgent() - { - $r = Request::get('http://example.com/') - ->withUserAgent('ACME/1.2.3'); - - $this->assertArrayHasKey('User-Agent', $r->headers); - $r->_curlPrep(); - $this->assertContains('User-Agent: ACME/1.2.3', $r->raw_headers); - $this->assertNotContains('User-Agent: HttpFul/1.0', $r->raw_headers); - - $r = Request::get('http://example.com/') - ->withUserAgent(''); - - $this->assertArrayHasKey('User-Agent', $r->headers); - $r->_curlPrep(); - $this->assertContains('User-Agent:', $r->raw_headers); - $this->assertNotContains('User-Agent: HttpFul/1.0', $r->raw_headers); - } - - function testAuthSetup() - { - $username = 'nathan'; - $password = 'opensesame'; - - $r = Request::get('http://example.com/') - ->authenticateWith($username, $password); - - $this->assertEquals($username, $r->username); - $this->assertEquals($password, $r->password); - $this->assertTrue($r->hasBasicAuth()); - } - - function testDigestAuthSetup() - { - $username = 'nathan'; - $password = 'opensesame'; - - $r = Request::get('http://example.com/') - ->authenticateWithDigest($username, $password); - - $this->assertEquals($username, $r->username); - $this->assertEquals($password, $r->password); - $this->assertTrue($r->hasDigestAuth()); - } - - function testJsonResponseParse() - { - $req = Request::init()->sendsAndExpects(Mime::JSON); - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); - - $this->assertEquals("value", $response->body->key); - $this->assertEquals("value", $response->body->object->key); - $this->assertInternalType('array', $response->body->array); - $this->assertEquals(1, $response->body->array[0]); - } - - function testXMLResponseParse() - { - $req = Request::init()->sendsAndExpects(Mime::XML); - $response = new Response(self::SAMPLE_XML_RESPONSE, self::SAMPLE_XML_HEADER, $req); - $sxe = $response->body; - $this->assertEquals("object", gettype($sxe)); - $this->assertEquals("SimpleXMLElement", get_class($sxe)); - $bools = $sxe->xpath('/stdClass/boolProp'); - list( , $bool ) = each($bools); - $this->assertEquals("TRUE", (string) $bool); - $ints = $sxe->xpath('/stdClass/arrayProp/array/k1/myClass/intProp'); - list( , $int ) = each($ints); - $this->assertEquals("2", (string) $int); - $strings = $sxe->xpath('/stdClass/stringProp'); - list( , $string ) = each($strings); - $this->assertEquals("a string", (string) $string); - } - - function testCsvResponseParse() - { - $req = Request::init()->sendsAndExpects(Mime::CSV); - $response = new Response(self::SAMPLE_CSV_RESPONSE, self::SAMPLE_CSV_HEADER, $req); - - $this->assertEquals("Key1", $response->body[0][0]); - $this->assertEquals("Value1", $response->body[1][0]); - $this->assertInternalType('string', $response->body[2][0]); - $this->assertEquals("40.0", $response->body[2][0]); - } - - function testParsingContentTypeCharset() - { - $req = Request::init()->sendsAndExpects(Mime::JSON); - // $response = new Response(SAMPLE_JSON_RESPONSE, "", $req); - // // Check default content type of iso-8859-1 - $response = new Response(self::SAMPLE_JSON_RESPONSE, "HTTP/1.1 200 OK -Content-Type: text/plain; charset=utf-8\r\n", $req); - $this->assertInstanceOf('Httpful\Response\Headers', $response->headers); - $this->assertEquals($response->headers['Content-Type'], 'text/plain; charset=utf-8'); - $this->assertEquals($response->content_type, 'text/plain'); - $this->assertEquals($response->charset, 'utf-8'); - } - - function testEmptyResponseParse() - { - $req = Request::init()->sendsAndExpects(Mime::JSON); - $response = new Response("", self::SAMPLE_JSON_HEADER, $req); - $this->assertEquals(null, $response->body); - - $reqXml = Request::init()->sendsAndExpects(Mime::XML); - $responseXml = new Response("", self::SAMPLE_XML_HEADER, $reqXml); - $this->assertEquals(null, $responseXml->body); - } - - function testNoAutoParse() - { - $req = Request::init()->sendsAndExpects(Mime::JSON)->withoutAutoParsing(); - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); - $this->assertInternalType('string', $response->body); - $req = Request::init()->sendsAndExpects(Mime::JSON)->withAutoParsing(); - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); - $this->assertInternalType('object', $response->body); - } - - function testParseHeaders() - { - $req = Request::init()->sendsAndExpects(Mime::JSON); - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); - $this->assertEquals('application/json', $response->headers['Content-Type']); - } - - function testRawHeaders() - { - $req = Request::init()->sendsAndExpects(Mime::JSON); - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); - $this->assertContains('Content-Type: application/json', $response->raw_headers); - } - - function testHasErrors() - { - $req = Request::init()->sendsAndExpects(Mime::JSON); - $response = new Response('', "HTTP/1.1 100 Continue\r\n", $req); - $this->assertFalse($response->hasErrors()); - $response = new Response('', "HTTP/1.1 200 OK\r\n", $req); - $this->assertFalse($response->hasErrors()); - $response = new Response('', "HTTP/1.1 300 Multiple Choices\r\n", $req); - $this->assertFalse($response->hasErrors()); - $response = new Response('', "HTTP/1.1 400 Bad Request\r\n", $req); - $this->assertTrue($response->hasErrors()); - $response = new Response('', "HTTP/1.1 500 Internal Server Error\r\n", $req); - $this->assertTrue($response->hasErrors()); - } - - function test_parseCode() - { - $req = Request::init()->sendsAndExpects(Mime::JSON); - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); - $code = $response->_parseCode("HTTP/1.1 406 Not Acceptable\r\n"); - $this->assertEquals(406, $code); - } - - function testToString() - { - $req = Request::init()->sendsAndExpects(Mime::JSON); - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); - $this->assertEquals(self::SAMPLE_JSON_RESPONSE, (string)$response); - } - - function test_parseHeaders() - { - $parse_headers = Response\Headers::fromString(self::SAMPLE_JSON_HEADER); - $this->assertCount(3, $parse_headers); - $this->assertEquals('application/json', $parse_headers['Content-Type']); - $this->assertTrue(isset($parse_headers['Connection'])); - } - - function testMultiHeaders() - { - $req = Request::init(); - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_MULTI_HEADER, $req); - $parse_headers = $response->_parseHeaders(self::SAMPLE_MULTI_HEADER); - $this->assertEquals('Value1,Value2', $parse_headers['X-My-Header']); - } - - function testDetectContentType() - { - $req = Request::init(); - $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req); - $this->assertEquals('application/json', $response->headers['Content-Type']); - } - - function testMissingBodyContentType() - { - $body = 'A string'; - $request = Request::post(HttpfulTest::TEST_URL, $body)->_curlPrep(); - $this->assertEquals($body, $request->serialized_payload); - } - - function testParentType() - { - // Parent type - $request = Request::init()->sendsAndExpects(Mime::XML); - $response = new Response('Nathan', self::SAMPLE_VENDOR_HEADER, $request); - - $this->assertEquals("application/xml", $response->parent_type); - $this->assertEquals(self::SAMPLE_VENDOR_TYPE, $response->content_type); - $this->assertTrue($response->is_mime_vendor_specific); - - // Make sure we still parsed as if it were plain old XML - $this->assertEquals("Nathan", $response->body->name->__toString()); - } - - function testMissingContentType() - { - // Parent type - $request = Request::init()->sendsAndExpects(Mime::XML); - $response = new Response( - 'Nathan', - "HTTP/1.1 200 OK -Connection: keep-alive -Transfer-Encoding: chunked\r\n", - $request - ); - - $this->assertEquals("", $response->content_type); - } - - function testCustomMimeRegistering() - { - // Register new mime type handler for "application/vnd.nategood.message+xml" - Httpful::register(self::SAMPLE_VENDOR_TYPE, new DemoMimeHandler()); - - $this->assertTrue(Httpful::hasParserRegistered(self::SAMPLE_VENDOR_TYPE)); - - $request = Request::init(); - $response = new Response('Nathan', self::SAMPLE_VENDOR_HEADER, $request); - - $this->assertEquals(self::SAMPLE_VENDOR_TYPE, $response->content_type); - $this->assertEquals('custom parse', $response->body); - } - - public function testShorthandMimeDefinition() - { - $r = Request::init()->expects('json'); - $this->assertEquals(Mime::JSON, $r->expected_type); - - $r = Request::init()->expectsJson(); - $this->assertEquals(Mime::JSON, $r->expected_type); - } - - public function testOverrideXmlHandler() - { - // Lazy test... - $prev = \Httpful\Httpful::get(\Httpful\Mime::XML); - $this->assertEquals($prev, new \Httpful\Handlers\XmlHandler()); - $conf = ['namespace' => 'http://example.com']; - \Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf)); - $new = \Httpful\Httpful::get(\Httpful\Mime::XML); - $this->assertNotEquals($prev, $new); - } -} - -class DemoMimeHandler extends \Httpful\Handlers\MimeHandlerAdapter -{ - public function parse($body) - { - return 'custom parse'; - } -} diff --git a/app/Library/Poniverse/httpful/tests/phpunit.xml b/app/Library/Poniverse/httpful/tests/phpunit.xml deleted file mode 100644 index 8f62e80a..00000000 --- a/app/Library/Poniverse/httpful/tests/phpunit.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - . - - - - - - diff --git a/app/Library/Poniverse/oauth2/Client.php b/app/Library/Poniverse/oauth2/Client.php deleted file mode 100644 index 49b8ec8e..00000000 --- a/app/Library/Poniverse/oauth2/Client.php +++ /dev/null @@ -1,519 +0,0 @@ - - * @author Anis Berejeb - * @version 1.2-dev - */ -namespace OAuth2; - -class Client -{ - /** - * Different AUTH method - */ - const AUTH_TYPE_URI = 0; - const AUTH_TYPE_AUTHORIZATION_BASIC = 1; - const AUTH_TYPE_FORM = 2; - - /** - * Different Access token type - */ - const ACCESS_TOKEN_URI = 0; - const ACCESS_TOKEN_BEARER = 1; - const ACCESS_TOKEN_OAUTH = 2; - const ACCESS_TOKEN_MAC = 3; - - /** - * Different Grant types - */ - const GRANT_TYPE_AUTH_CODE = 'authorization_code'; - const GRANT_TYPE_PASSWORD = 'password'; - const GRANT_TYPE_CLIENT_CREDENTIALS = 'client_credentials'; - const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token'; - - /** - * HTTP Methods - */ - const HTTP_METHOD_GET = 'GET'; - const HTTP_METHOD_POST = 'POST'; - const HTTP_METHOD_PUT = 'PUT'; - const HTTP_METHOD_DELETE = 'DELETE'; - const HTTP_METHOD_HEAD = 'HEAD'; - const HTTP_METHOD_PATCH = 'PATCH'; - - /** - * HTTP Form content types - */ - const HTTP_FORM_CONTENT_TYPE_APPLICATION = 0; - const HTTP_FORM_CONTENT_TYPE_MULTIPART = 1; - - /** - * Client ID - * - * @var string - */ - protected $client_id = null; - - /** - * Client Secret - * - * @var string - */ - protected $client_secret = null; - - /** - * Client Authentication method - * - * @var int - */ - protected $client_auth = self::AUTH_TYPE_URI; - - /** - * Access Token - * - * @var string - */ - protected $access_token = null; - - /** - * Access Token Type - * - * @var int - */ - protected $access_token_type = self::ACCESS_TOKEN_URI; - - /** - * Access Token Secret - * - * @var string - */ - protected $access_token_secret = null; - - /** - * Access Token crypt algorithm - * - * @var string - */ - protected $access_token_algorithm = null; - - /** - * Access Token Parameter name - * - * @var string - */ - protected $access_token_param_name = 'access_token'; - - /** - * The path to the certificate file to use for https connections - * - * @var string Defaults to . - */ - protected $certificate_file = null; - - /** - * cURL options - * - * @var array - */ - protected $curl_options = []; - - /** - * Construct - * - * @param string $client_id Client ID - * @param string $client_secret Client Secret - * @param int $client_auth (AUTH_TYPE_URI, AUTH_TYPE_AUTHORIZATION_BASIC, AUTH_TYPE_FORM) - * @param string $certificate_file Indicates if we want to use a certificate file to trust the server. Optional, defaults to null. - * @return void - */ - public function __construct($client_id, $client_secret, $client_auth = self::AUTH_TYPE_URI, $certificate_file = null) - { - if (!extension_loaded('curl')) { - throw new Exception('The PHP exention curl must be installed to use this library.', Exception::CURL_NOT_FOUND); - } - - $this->client_id = $client_id; - $this->client_secret = $client_secret; - $this->client_auth = $client_auth; - $this->certificate_file = $certificate_file; - if (!empty($this->certificate_file) && !is_file($this->certificate_file)) { - throw new InvalidArgumentException('The certificate file was not found', InvalidArgumentException::CERTIFICATE_NOT_FOUND); - } - } - - /** - * Get the client Id - * - * @return string Client ID - */ - public function getClientId() - { - return $this->client_id; - } - - /** - * Get the client Secret - * - * @return string Client Secret - */ - public function getClientSecret() - { - return $this->client_secret; - } - - /** - * getAuthenticationUrl - * - * @param string $auth_endpoint Url of the authentication endpoint - * @param string $redirect_uri Redirection URI - * @param array $extra_parameters Array of extra parameters like scope or state (Ex: array('scope' => null, 'state' => '')) - * @return string URL used for authentication - */ - public function getAuthenticationUrl($auth_endpoint, $redirect_uri, array $extra_parameters = []) - { - $parameters = array_merge([ - 'response_type' => 'code', - 'client_id' => $this->client_id, - 'redirect_uri' => $redirect_uri - ], $extra_parameters); - return $auth_endpoint . '?' . http_build_query($parameters, null, '&'); - } - - /** - * getAccessToken - * - * @param string $token_endpoint Url of the token endpoint - * @param int $grant_type Grant Type ('authorization_code', 'password', 'client_credentials', 'refresh_token', or a custom code (@see GrantType Classes) - * @param array $parameters Array sent to the server (depend on which grant type you're using) - * @return array Array of parameters required by the grant_type (CF SPEC) - * @throws Exception - */ - public function getAccessToken($token_endpoint, $grant_type, array $parameters) - { - if (!$grant_type) { - throw new InvalidArgumentException('The grant_type is mandatory.', InvalidArgumentException::INVALID_GRANT_TYPE); - } - $grantTypeClassName = $this->convertToCamelCase($grant_type); - $grantTypeClass = __NAMESPACE__ . '\\GrantType\\' . $grantTypeClassName; - if (!class_exists($grantTypeClass)) { - throw new InvalidArgumentException('Unknown grant type \'' . $grant_type . '\'', InvalidArgumentException::INVALID_GRANT_TYPE); - } - $grantTypeObject = new $grantTypeClass(); - $grantTypeObject->validateParameters($parameters); - if (!defined($grantTypeClass . '::GRANT_TYPE')) { - throw new Exception('Unknown constant GRANT_TYPE for class ' . $grantTypeClassName, Exception::GRANT_TYPE_ERROR); - } - $parameters['grant_type'] = $grantTypeClass::GRANT_TYPE; - $http_headers = []; - switch ($this->client_auth) { - case self::AUTH_TYPE_URI: - case self::AUTH_TYPE_FORM: - $parameters['client_id'] = $this->client_id; - $parameters['client_secret'] = $this->client_secret; - break; - case self::AUTH_TYPE_AUTHORIZATION_BASIC: - $parameters['client_id'] = $this->client_id; - $http_headers['Authorization'] = 'Basic ' . base64_encode($this->client_id . ':' . $this->client_secret); - break; - default: - throw new Exception('Unknown client auth type.', Exception::INVALID_CLIENT_AUTHENTICATION_TYPE); - break; - } - - return $this->executeRequest($token_endpoint, $parameters, self::HTTP_METHOD_POST, $http_headers, self::HTTP_FORM_CONTENT_TYPE_APPLICATION); - } - - /** - * setToken - * - * @param string $token Set the access token - * @return void - */ - public function setAccessToken($token) - { - $this->access_token = $token; - } - - /** - * Set the client authentication type - * - * @param string $client_auth (AUTH_TYPE_URI, AUTH_TYPE_AUTHORIZATION_BASIC, AUTH_TYPE_FORM) - * @return void - */ - public function setClientAuthType($client_auth) - { - $this->client_auth = $client_auth; - } - - /** - * Set an option for the curl transfer - * - * @param int $option The CURLOPT_XXX option to set - * @param mixed $value The value to be set on option - * @return void - */ - public function setCurlOption($option, $value) - { - $this->curl_options[$option] = $value; - } - - /** - * Set multiple options for a cURL transfer - * - * @param array $options An array specifying which options to set and their values - * @return void - */ - public function setCurlOptions($options) - { - $this->curl_options = array_merge($this->curl_options, $options); - } - - /** - * Set the access token type - * - * @param int $type Access token type (ACCESS_TOKEN_BEARER, ACCESS_TOKEN_MAC, ACCESS_TOKEN_URI) - * @param string $secret The secret key used to encrypt the MAC header - * @param string $algorithm Algorithm used to encrypt the signature - * @return void - */ - public function setAccessTokenType($type, $secret = null, $algorithm = null) - { - $this->access_token_type = $type; - $this->access_token_secret = $secret; - $this->access_token_algorithm = $algorithm; - } - - /** - * Fetch a protected ressource - * - * @param string $protected_ressource_url Protected resource URL - * @param array $parameters Array of parameters - * @param string $http_method HTTP Method to use (POST, PUT, GET, HEAD, DELETE) - * @param array $http_headers HTTP headers - * @param int $form_content_type HTTP form content type to use - * @return array - */ - public function fetch($protected_resource_url, $parameters = [], $http_method = self::HTTP_METHOD_GET, array $http_headers = [], $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) - { - if ($this->access_token) { - switch ($this->access_token_type) { - case self::ACCESS_TOKEN_URI: - if (is_array($parameters)) { - $parameters[$this->access_token_param_name] = $this->access_token; - } else { - throw new InvalidArgumentException( - 'You need to give parameters as array if you want to give the token within the URI.', - InvalidArgumentException::REQUIRE_PARAMS_AS_ARRAY - ); - } - break; - case self::ACCESS_TOKEN_BEARER: - $http_headers['Authorization'] = 'Bearer ' . $this->access_token; - break; - case self::ACCESS_TOKEN_OAUTH: - $http_headers['Authorization'] = 'OAuth ' . $this->access_token; - break; - case self::ACCESS_TOKEN_MAC: - $http_headers['Authorization'] = 'MAC ' . $this->generateMACSignature($protected_resource_url, $parameters, $http_method); - break; - default: - throw new Exception('Unknown access token type.', Exception::INVALID_ACCESS_TOKEN_TYPE); - break; - } - } - return $this->executeRequest($protected_resource_url, $parameters, $http_method, $http_headers, $form_content_type); - } - - /** - * Generate the MAC signature - * - * @param string $url Called URL - * @param array $parameters Parameters - * @param string $http_method Http Method - * @return string - */ - private function generateMACSignature($url, $parameters, $http_method) - { - $timestamp = time(); - $nonce = uniqid(); - $parsed_url = parse_url($url); - if (!isset($parsed_url['port'])) { - $parsed_url['port'] = ($parsed_url['scheme'] == 'https') ? 443 : 80; - } - if ($http_method == self::HTTP_METHOD_GET) { - if (is_array($parameters)) { - $parsed_url['path'] .= '?' . http_build_query($parameters, null, '&'); - } elseif ($parameters) { - $parsed_url['path'] .= '?' . $parameters; - } - } - - $signature = base64_encode(hash_hmac( - $this->access_token_algorithm, - $timestamp . "\n" - . $nonce . "\n" - . $http_method . "\n" - . $parsed_url['path'] . "\n" - . $parsed_url['host'] . "\n" - . $parsed_url['port'] . "\n\n", - $this->access_token_secret, - true - )); - - return 'id="' . $this->access_token . '", ts="' . $timestamp . '", nonce="' . $nonce . '", mac="' . $signature . '"'; - } - - /** - * Execute a request (with curl) - * - * @param string $url URL - * @param mixed $parameters Array of parameters - * @param string $http_method HTTP Method - * @param array $http_headers HTTP Headers - * @param int $form_content_type HTTP form content type to use - * @return array - */ - private function executeRequest($url, $parameters = [], $http_method = self::HTTP_METHOD_GET, array $http_headers = null, $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) - { - $curl_options = [ - CURLOPT_RETURNTRANSFER => true, - CURLOPT_SSL_VERIFYPEER => true, - CURLOPT_CUSTOMREQUEST => $http_method - ]; - - switch ($http_method) { - case self::HTTP_METHOD_POST: - $curl_options[CURLOPT_POST] = true; - /* No break */ - case self::HTTP_METHOD_PUT: - case self::HTTP_METHOD_PATCH: - /** - * Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, - * while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded. - * http://php.net/manual/en/function.curl-setopt.php - */ - if (is_array($parameters) && self::HTTP_FORM_CONTENT_TYPE_APPLICATION === $form_content_type) { - $parameters = http_build_query($parameters, null, '&'); - } - $curl_options[CURLOPT_POSTFIELDS] = $parameters; - break; - case self::HTTP_METHOD_HEAD: - $curl_options[CURLOPT_NOBODY] = true; - /* No break */ - case self::HTTP_METHOD_DELETE: - case self::HTTP_METHOD_GET: - if (is_array($parameters)) { - $url .= '?' . http_build_query($parameters, null, '&'); - } elseif ($parameters) { - $url .= '?' . $parameters; - } - break; - default: - break; - } - - $curl_options[CURLOPT_URL] = $url; - - if (is_array($http_headers)) { - $header = []; - foreach ($http_headers as $key => $parsed_urlvalue) { - $header[] = "$key: $parsed_urlvalue"; - } - $curl_options[CURLOPT_HTTPHEADER] = $header; - } - - $ch = curl_init(); - curl_setopt_array($ch, $curl_options); - // https handling - if (!empty($this->certificate_file)) { - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); - curl_setopt($ch, CURLOPT_CAINFO, $this->certificate_file); - } else { - // bypass ssl verification - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - } - if (!empty($this->curl_options)) { - curl_setopt_array($ch, $this->curl_options); - } - $result = curl_exec($ch); - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); - if ($curl_error = curl_error($ch)) { - throw new Exception($curl_error, Exception::CURL_ERROR); - } else { - $json_decode = json_decode($result, true); - } - curl_close($ch); - - return [ - 'result' => (null === $json_decode) ? $result : $json_decode, - 'code' => $http_code, - 'content_type' => $content_type - ]; - } - - /** - * Set the name of the parameter that carry the access token - * - * @param string $name Token parameter name - * @return void - */ - public function setAccessTokenParamName($name) - { - $this->access_token_param_name = $name; - } - - /** - * Converts the class name to camel case - * - * @param mixed $grant_type the grant type - * @return string - */ - private function convertToCamelCase($grant_type) - { - $parts = explode('_', $grant_type); - array_walk($parts, function (&$item) { - $item = ucfirst($item); - }); - return implode('', $parts); - } -} - -class Exception extends \Exception -{ - const CURL_NOT_FOUND = 0x01; - const CURL_ERROR = 0x02; - const GRANT_TYPE_ERROR = 0x03; - const INVALID_CLIENT_AUTHENTICATION_TYPE = 0x04; - const INVALID_ACCESS_TOKEN_TYPE = 0x05; -} - -class InvalidArgumentException extends \InvalidArgumentException -{ - const INVALID_GRANT_TYPE = 0x01; - const CERTIFICATE_NOT_FOUND = 0x02; - const REQUIRE_PARAMS_AS_ARRAY = 0x03; - const MISSING_PARAMETER = 0x04; -} diff --git a/app/Library/Poniverse/oauth2/GrantType/AuthorizationCode.php b/app/Library/Poniverse/oauth2/GrantType/AuthorizationCode.php deleted file mode 100644 index 79b79a84..00000000 --- a/app/Library/Poniverse/oauth2/GrantType/AuthorizationCode.php +++ /dev/null @@ -1,38 +0,0 @@ -getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI); - header('Location: ' . $auth_url); - die('Redirect'); -} -else -{ - $params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI); - $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); - parse_str($response['result'], $info); - $client->setAccessToken($info['access_token']); - $response = $client->fetch('https://graph.facebook.com/me'); - var_dump($response, $response['result']); -} - -How can I add a new Grant Type ? -================================ -Simply write a new class in the namespace OAuth2\GrantType. You can place the class file under GrantType. -Here is an example : - -namespace OAuth2\GrantType; - -/** - * MyCustomGrantType Grant Type - */ -class MyCustomGrantType implements IGrantType -{ - /** - * Defines the Grant Type - * - * @var string Defaults to 'my_custom_grant_type'. - */ - const GRANT_TYPE = 'my_custom_grant_type'; - - /** - * Adds a specific Handling of the parameters - * - * @return array of Specific parameters to be sent. - * @param mixed $parameters the parameters array (passed by reference) - */ - public function validateParameters(&$parameters) - { - if (!isset($parameters['first_mandatory_parameter'])) - { - throw new \Exception('The \'first_mandatory_parameter\' parameter must be defined for the Password grant type'); - } - elseif (!isset($parameters['second_mandatory_parameter'])) - { - throw new \Exception('The \'seconde_mandatory_parameter\' parameter must be defined for the Password grant type'); - } - } -} - -call the OAuth client getAccessToken with the grantType you defined in the GRANT_TYPE constant, As following : -$response = $client->getAccessToken(TOKEN_ENDPOINT, 'my_custom_grant_type', $params); - diff --git a/app/Library/Poniverse/oauth2/composer.json b/app/Library/Poniverse/oauth2/composer.json deleted file mode 100644 index 2e052a52..00000000 --- a/app/Library/Poniverse/oauth2/composer.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "adoy/oauth2", - "description": "Light PHP wrapper for the OAuth 2.0 protocol (based on OAuth 2.0 Authorization Protocol draft-ietf-oauth-v2-15)", - "authors": [ - { - "name": "Charron Pierrick", - "email": "pierrick@webstart.fr" - }, - { - "name": "Berejeb Anis", - "email": "anis.berejeb@gmail.com" - } - ], - "autoload": { - "classmap": [ - "../" - ] - } -} diff --git a/app/Models/Track.php b/app/Models/Track.php index a78dba19..b17b8e7d 100644 --- a/app/Models/Track.php +++ b/app/Models/Track.php @@ -643,7 +643,6 @@ class Track extends Model implements Searchable, Commentable, Favouritable public function setTitleAttribute($value) { $this->setTitleAttributeSlug($value); - ; $this->updateHash(); } diff --git a/composer.json b/composer.json index 517887c6..17b0918b 100644 --- a/composer.json +++ b/composer.json @@ -25,7 +25,8 @@ "ksubileau/color-thief-php": "^1.3", "graham-campbell/exceptions": "^9.1", "minishlink/web-push": "^1.0", - "alsofronie/eloquent-uuid": "^1.0" + "alsofronie/eloquent-uuid": "^1.0", + "poniverse/api": "dev-rewrite" }, "require-dev": { "fzaninotto/faker": "~1.4", diff --git a/composer.lock b/composer.lock index 19cf09ae..4e13e672 100644 --- a/composer.lock +++ b/composer.lock @@ -4,8 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "9b2297ef01f39e9d732b9ff50dc60203", - "content-hash": "4b9f2079d6a15098a09e1546396ac762", + "content-hash": "d5c92590895fa239010545ebde821cec", "packages": [ { "name": "alsofronie/eloquent-uuid", @@ -45,7 +44,7 @@ } ], "description": "A Laravel Eloquent Model trait for using UUID's as primary keys", - "time": "2016-10-22 20:21:20" + "time": "2016-10-22T20:21:20+00:00" }, { "name": "barryvdh/laravel-debugbar", @@ -99,7 +98,7 @@ "profiler", "webprofiler" ], - "time": "2016-09-15 14:05:56" + "time": "2016-09-15T14:05:56+00:00" }, { "name": "barryvdh/laravel-ide-helper", @@ -165,7 +164,7 @@ "phpstorm", "sublime" ], - "time": "2016-07-04 11:52:48" + "time": "2016-07-04T11:52:48+00:00" }, { "name": "barryvdh/reflection-docblock", @@ -214,7 +213,7 @@ "email": "mike.vanriel@naenius.com" } ], - "time": "2016-06-13 19:28:20" + "time": "2016-06-13T19:28:20+00:00" }, { "name": "beberlei/assert", @@ -273,7 +272,7 @@ "assertion", "validation" ], - "time": "2016-07-28 19:35:30" + "time": "2016-07-28T19:35:30+00:00" }, { "name": "classpreloader/classpreloader", @@ -327,7 +326,7 @@ "class", "preload" ], - "time": "2015-11-09 22:51:51" + "time": "2015-11-09T22:51:51+00:00" }, { "name": "codescale/ffmpeg-php", @@ -371,7 +370,7 @@ "ffmpeg", "video" ], - "time": "2013-05-05 09:10:04" + "time": "2013-05-05T09:10:04+00:00" }, { "name": "cviebrock/laravel-elasticsearch", @@ -420,7 +419,7 @@ "laravel", "search" ], - "time": "2016-06-27 15:11:36" + "time": "2016-06-27T15:11:36+00:00" }, { "name": "dnoegel/php-xdg-base-dir", @@ -453,7 +452,7 @@ "MIT" ], "description": "implementation of xdg base directory specification for php", - "time": "2014-10-24 07:27:01" + "time": "2014-10-24T07:27:01+00:00" }, { "name": "doctrine/annotations", @@ -521,7 +520,7 @@ "docblock", "parser" ], - "time": "2015-08-31 12:32:49" + "time": "2015-08-31T12:32:49+00:00" }, { "name": "doctrine/cache", @@ -591,7 +590,7 @@ "cache", "caching" ], - "time": "2015-12-31 16:37:02" + "time": "2015-12-31T16:37:02+00:00" }, { "name": "doctrine/collections", @@ -657,7 +656,7 @@ "collections", "iterator" ], - "time": "2015-04-14 22:21:58" + "time": "2015-04-14T22:21:58+00:00" }, { "name": "doctrine/common", @@ -730,7 +729,7 @@ "persistence", "spl" ], - "time": "2015-12-25 13:18:31" + "time": "2015-12-25T13:18:31+00:00" }, { "name": "doctrine/dbal", @@ -801,7 +800,7 @@ "persistence", "queryobject" ], - "time": "2016-09-09 19:13:33" + "time": "2016-09-09T19:13:33+00:00" }, { "name": "doctrine/inflector", @@ -868,7 +867,7 @@ "singularize", "string" ], - "time": "2015-11-06 14:35:42" + "time": "2015-11-06T14:35:42+00:00" }, { "name": "doctrine/lexer", @@ -922,7 +921,7 @@ "lexer", "parser" ], - "time": "2014-09-09 13:34:57" + "time": "2014-09-09T13:34:57+00:00" }, { "name": "elasticsearch/elasticsearch", @@ -976,7 +975,7 @@ "elasticsearch", "search" ], - "time": "2016-07-14 14:13:40" + "time": "2016-07-14T14:13:40+00:00" }, { "name": "fgrosse/phpasn1", @@ -1045,7 +1044,7 @@ "x509", "x690" ], - "time": "2015-10-02 06:11:35" + "time": "2015-10-02T06:11:35+00:00" }, { "name": "graham-campbell/exceptions", @@ -1114,7 +1113,7 @@ "laravel", "whoops" ], - "time": "2016-08-19 08:58:30" + "time": "2016-08-19T08:58:30+00:00" }, { "name": "guzzlehttp/guzzle", @@ -1176,7 +1175,7 @@ "rest", "web service" ], - "time": "2016-07-15 17:22:37" + "time": "2016-07-15T17:22:37+00:00" }, { "name": "guzzlehttp/promises", @@ -1227,7 +1226,7 @@ "keywords": [ "promise" ], - "time": "2016-05-18 16:56:05" + "time": "2016-05-18T16:56:05+00:00" }, { "name": "guzzlehttp/psr7", @@ -1285,7 +1284,7 @@ "stream", "uri" ], - "time": "2016-06-24 23:00:38" + "time": "2016-06-24T23:00:38+00:00" }, { "name": "guzzlehttp/ringphp", @@ -1336,7 +1335,7 @@ } ], "description": "Provides a simple API and specification that abstracts away the details of HTTP into a single PHP function.", - "time": "2015-05-20 03:37:09" + "time": "2015-05-20T03:37:09+00:00" }, { "name": "guzzlehttp/streams", @@ -1386,7 +1385,7 @@ "Guzzle", "stream" ], - "time": "2014-10-12 19:18:40" + "time": "2014-10-12T19:18:40+00:00" }, { "name": "intouch/laravel-newrelic", @@ -1430,7 +1429,7 @@ "new relic", "newrelic" ], - "time": "2016-05-05 12:30:20" + "time": "2016-05-05T12:30:20+00:00" }, { "name": "intouch/newrelic", @@ -1471,7 +1470,108 @@ "new relic", "newrelic" ], - "time": "2014-08-18 12:08:45" + "time": "2014-08-18T12:08:45+00:00" + }, + { + "name": "ircmaxell/random-lib", + "version": "v1.2.0", + "source": { + "type": "git", + "url": "https://github.com/ircmaxell/RandomLib.git", + "reference": "e9e0204f40e49fa4419946c677eccd3fa25b8cf4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ircmaxell/RandomLib/zipball/e9e0204f40e49fa4419946c677eccd3fa25b8cf4", + "reference": "e9e0204f40e49fa4419946c677eccd3fa25b8cf4", + "shasum": "" + }, + "require": { + "ircmaxell/security-lib": "^1.1", + "php": ">=5.3.2" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^1.11", + "mikey179/vfsstream": "^1.6", + "phpunit/phpunit": "^4.8|^5.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "autoload": { + "psr-0": { + "RandomLib": "lib" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@ircmaxell.com", + "homepage": "http://blog.ircmaxell.com" + } + ], + "description": "A Library For Generating Secure Random Numbers", + "homepage": "https://github.com/ircmaxell/RandomLib", + "keywords": [ + "cryptography", + "random", + "random-numbers", + "random-strings" + ], + "time": "2016-09-07T15:52:06+00:00" + }, + { + "name": "ircmaxell/security-lib", + "version": "v1.1.0", + "source": { + "type": "git", + "url": "https://github.com/ircmaxell/SecurityLib.git", + "reference": "f3db6de12c20c9bcd1aa3db4353a1bbe0e44e1b5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ircmaxell/SecurityLib/zipball/f3db6de12c20c9bcd1aa3db4353a1bbe0e44e1b5", + "reference": "f3db6de12c20c9bcd1aa3db4353a1bbe0e44e1b5", + "shasum": "" + }, + "require": { + "php": ">=5.3.2" + }, + "require-dev": { + "mikey179/vfsstream": "1.1.*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-0": { + "SecurityLib": "lib" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@ircmaxell.com", + "homepage": "http://blog.ircmaxell.com" + } + ], + "description": "A Base Security Library", + "homepage": "https://github.com/ircmaxell/SecurityLib", + "time": "2015-03-20T14:31:23+00:00" }, { "name": "jakub-onderka/php-console-color", @@ -1514,7 +1614,7 @@ "homepage": "http://www.acci.cz" } ], - "time": "2014-04-08 15:00:19" + "time": "2014-04-08T15:00:19+00:00" }, { "name": "jakub-onderka/php-console-highlighter", @@ -1558,7 +1658,7 @@ "homepage": "http://www.acci.cz/" } ], - "time": "2015-04-20 18:58:01" + "time": "2015-04-20T18:58:01+00:00" }, { "name": "jeremeamia/SuperClosure", @@ -1616,7 +1716,7 @@ "serialize", "tokenizer" ], - "time": "2015-12-05 17:17:57" + "time": "2015-12-05T17:17:57+00:00" }, { "name": "kriswallsmith/buzz", @@ -1664,7 +1764,7 @@ "curl", "http client" ], - "time": "2015-06-25 17:26:56" + "time": "2015-06-25T17:26:56+00:00" }, { "name": "ksubileau/color-thief-php", @@ -1717,7 +1817,7 @@ "php", "thief" ], - "time": "2016-01-17 18:55:16" + "time": "2016-01-17T18:55:16+00:00" }, { "name": "laravel/framework", @@ -1845,7 +1945,7 @@ "framework", "laravel" ], - "time": "2016-09-29 22:13:17" + "time": "2016-09-29T22:13:17+00:00" }, { "name": "league/flysystem", @@ -1928,7 +2028,70 @@ "sftp", "storage" ], - "time": "2016-08-10 08:55:11" + "time": "2016-08-10T08:55:11+00:00" + }, + { + "name": "league/oauth2-client", + "version": "1.4.2", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-client.git", + "reference": "01f955b85040b41cf48885b078f7fd39a8be5411" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-client/zipball/01f955b85040b41cf48885b078f7fd39a8be5411", + "reference": "01f955b85040b41cf48885b078f7fd39a8be5411", + "shasum": "" + }, + "require": { + "ext-curl": "*", + "guzzlehttp/guzzle": "~6.0", + "ircmaxell/random-lib": "~1.1", + "php": ">=5.5.0" + }, + "require-dev": { + "jakub-onderka/php-parallel-lint": "0.8.*", + "mockery/mockery": "~0.9", + "phpunit/phpunit": "~4.0", + "satooshi/php-coveralls": "0.6.*", + "squizlabs/php_codesniffer": "~2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alex Bilbie", + "email": "hello@alexbilbie.com", + "homepage": "http://www.alexbilbie.com", + "role": "Developer" + } + ], + "description": "OAuth 2.0 Client Library", + "keywords": [ + "Authentication", + "SSO", + "authorization", + "identity", + "idp", + "oauth", + "oauth2", + "single sign on" + ], + "time": "2016-07-28T13:20:43+00:00" }, { "name": "maximebf/debugbar", @@ -1989,7 +2152,7 @@ "debug", "debugbar" ], - "time": "2016-09-15 14:01:59" + "time": "2016-09-15T14:01:59+00:00" }, { "name": "mdanter/ecc", @@ -2055,7 +2218,7 @@ "phpecc", "secp256k1" ], - "time": "2016-06-26 18:37:24" + "time": "2016-06-26T18:37:24+00:00" }, { "name": "minishlink/web-push", @@ -2108,7 +2271,7 @@ "push", "web" ], - "time": "2016-07-28 22:53:50" + "time": "2016-07-28T22:53:50+00:00" }, { "name": "monolog/monolog", @@ -2186,7 +2349,7 @@ "logging", "psr-3" ], - "time": "2016-07-29 03:23:52" + "time": "2016-07-29T03:23:52+00:00" }, { "name": "mtdowling/cron-expression", @@ -2230,7 +2393,7 @@ "cron", "schedule" ], - "time": "2016-01-26 21:23:30" + "time": "2016-01-26T21:23:30+00:00" }, { "name": "nesbot/carbon", @@ -2277,7 +2440,7 @@ "datetime", "time" ], - "time": "2015-11-04 20:07:17" + "time": "2015-11-04T20:07:17+00:00" }, { "name": "nikic/php-parser", @@ -2328,7 +2491,7 @@ "parser", "php" ], - "time": "2016-09-16 12:04:44" + "time": "2016-09-16T12:04:44+00:00" }, { "name": "paragonie/random_compat", @@ -2376,7 +2539,7 @@ "pseudorandom", "random" ], - "time": "2016-04-03 06:00:07" + "time": "2016-04-03T06:00:07+00:00" }, { "name": "pda/pheanstalk", @@ -2426,7 +2589,56 @@ "keywords": [ "beanstalkd" ], - "time": "2015-08-07 21:42:41" + "time": "2015-08-07T21:42:41+00:00" + }, + { + "name": "poniverse/api", + "version": "dev-rewrite", + "source": { + "type": "git", + "url": "https://github.com/Poniverse/poniverse-php.git", + "reference": "851f9ea1495142dcbf0307d48131cedc70d4e44e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Poniverse/poniverse-php/zipball/851f9ea1495142dcbf0307d48131cedc70d4e44e", + "reference": "851f9ea1495142dcbf0307d48131cedc70d4e44e", + "shasum": "" + }, + "require": { + "guzzlehttp/guzzle": "~6.0", + "illuminate/support": "5.1.*|5.2.*|5.3.*|5.4.*", + "league/oauth2-client": "^1.1", + "php": ">=5.5.0" + }, + "require-dev": { + "mockery/mockery": "0.9.*", + "phpunit/phpunit": "~4.0", + "satooshi/php-coveralls": "~1.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Poniverse\\Lib\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Adam Lavin", + "email": "adam@lavoaster.co.uk" + } + ], + "description": "PHP Library to access the Poniverse APi", + "keywords": [ + "api", + "laravel", + "laravel4" + ], + "time": "2016-12-29 16:04:47" }, { "name": "predis/predis", @@ -2476,7 +2688,7 @@ "predis", "redis" ], - "time": "2016-06-16 16:22:20" + "time": "2016-06-16T16:22:20+00:00" }, { "name": "psr/http-message", @@ -2526,7 +2738,7 @@ "request", "response" ], - "time": "2016-08-06 14:39:51" + "time": "2016-08-06T14:39:51+00:00" }, { "name": "psr/log", @@ -2573,7 +2785,7 @@ "psr", "psr-3" ], - "time": "2016-09-19 16:02:08" + "time": "2016-09-19T16:02:08+00:00" }, { "name": "psy/psysh", @@ -2645,7 +2857,7 @@ "interactive", "shell" ], - "time": "2016-03-09 05:03:14" + "time": "2016-03-09T05:03:14+00:00" }, { "name": "ramsey/uuid", @@ -2725,7 +2937,7 @@ "identifier", "uuid" ], - "time": "2016-08-02 18:39:32" + "time": "2016-08-02T18:39:32+00:00" }, { "name": "react/promise", @@ -2769,7 +2981,7 @@ } ], "description": "A lightweight implementation of CommonJS Promises/A for PHP", - "time": "2016-05-03 17:50:52" + "time": "2016-05-03T17:50:52+00:00" }, { "name": "spomky-labs/base64url", @@ -2821,7 +3033,7 @@ "safe", "url" ], - "time": "2016-01-21 19:50:30" + "time": "2016-01-21T19:50:30+00:00" }, { "name": "spomky-labs/php-aes-gcm", @@ -2878,7 +3090,7 @@ "Galois Counter Mode", "gcm" ], - "time": "2016-04-28 13:58:02" + "time": "2016-04-28T13:58:02+00:00" }, { "name": "swiftmailer/swiftmailer", @@ -2931,7 +3143,7 @@ "mail", "mailer" ], - "time": "2016-07-08 11:51:25" + "time": "2016-07-08T11:51:25+00:00" }, { "name": "symfony/class-loader", @@ -2987,7 +3199,7 @@ ], "description": "Symfony ClassLoader Component", "homepage": "https://symfony.com", - "time": "2016-08-23 13:39:15" + "time": "2016-08-23T13:39:15+00:00" }, { "name": "symfony/console", @@ -3047,7 +3259,7 @@ ], "description": "Symfony Console Component", "homepage": "https://symfony.com", - "time": "2016-08-19 06:48:39" + "time": "2016-08-19T06:48:39+00:00" }, { "name": "symfony/debug", @@ -3104,7 +3316,7 @@ ], "description": "Symfony Debug Component", "homepage": "https://symfony.com", - "time": "2016-08-23 13:39:15" + "time": "2016-08-23T13:39:15+00:00" }, { "name": "symfony/event-dispatcher", @@ -3164,7 +3376,7 @@ ], "description": "Symfony EventDispatcher Component", "homepage": "https://symfony.com", - "time": "2016-07-19 10:45:57" + "time": "2016-07-19T10:45:57+00:00" }, { "name": "symfony/finder", @@ -3213,7 +3425,7 @@ ], "description": "Symfony Finder Component", "homepage": "https://symfony.com", - "time": "2016-08-26 12:04:02" + "time": "2016-08-26T12:04:02+00:00" }, { "name": "symfony/http-foundation", @@ -3266,7 +3478,7 @@ ], "description": "Symfony HttpFoundation Component", "homepage": "https://symfony.com", - "time": "2016-08-22 12:11:19" + "time": "2016-08-22T12:11:19+00:00" }, { "name": "symfony/http-kernel", @@ -3348,7 +3560,7 @@ ], "description": "Symfony HttpKernel Component", "homepage": "https://symfony.com", - "time": "2016-09-03 15:28:24" + "time": "2016-09-03T15:28:24+00:00" }, { "name": "symfony/polyfill-mbstring", @@ -3407,7 +3619,7 @@ "portable", "shim" ], - "time": "2016-05-18 14:26:46" + "time": "2016-05-18T14:26:46+00:00" }, { "name": "symfony/polyfill-php56", @@ -3463,7 +3675,7 @@ "portable", "shim" ], - "time": "2016-05-18 14:26:46" + "time": "2016-05-18T14:26:46+00:00" }, { "name": "symfony/polyfill-util", @@ -3515,7 +3727,7 @@ "polyfill", "shim" ], - "time": "2016-05-18 14:26:46" + "time": "2016-05-18T14:26:46+00:00" }, { "name": "symfony/process", @@ -3564,7 +3776,7 @@ ], "description": "Symfony Process Component", "homepage": "https://symfony.com", - "time": "2016-08-16 14:58:24" + "time": "2016-08-16T14:58:24+00:00" }, { "name": "symfony/routing", @@ -3639,7 +3851,7 @@ "uri", "url" ], - "time": "2016-08-16 14:58:24" + "time": "2016-08-16T14:58:24+00:00" }, { "name": "symfony/translation", @@ -3703,7 +3915,7 @@ ], "description": "Symfony Translation Component", "homepage": "https://symfony.com", - "time": "2016-08-05 08:37:39" + "time": "2016-08-05T08:37:39+00:00" }, { "name": "symfony/var-dumper", @@ -3766,7 +3978,7 @@ "debug", "dump" ], - "time": "2016-08-31 09:05:42" + "time": "2016-08-31T09:05:42+00:00" }, { "name": "venturecraft/revisionable", @@ -3814,7 +4026,7 @@ "model", "revision" ], - "time": "2016-08-02 02:32:00" + "time": "2016-08-02T02:32:00+00:00" }, { "name": "vlucas/phpdotenv", @@ -3864,7 +4076,7 @@ "env", "environment" ], - "time": "2016-09-01 10:05:43" + "time": "2016-09-01T10:05:43+00:00" }, { "name": "webpatser/laravel-uuid", @@ -3911,7 +4123,7 @@ "keywords": [ "UUID RFC4122" ], - "time": "2016-05-09 09:22:18" + "time": "2016-05-09T09:22:18+00:00" } ], "packages-dev": [ @@ -3967,7 +4179,7 @@ "constructor", "instantiate" ], - "time": "2015-06-14 21:17:01" + "time": "2015-06-14T21:17:01+00:00" }, { "name": "filp/whoops", @@ -4027,7 +4239,7 @@ "whoops", "zf2" ], - "time": "2016-05-06 18:25:35" + "time": "2016-05-06T18:25:35+00:00" }, { "name": "fzaninotto/faker", @@ -4075,7 +4287,7 @@ "faker", "fixtures" ], - "time": "2016-04-29 12:21:54" + "time": "2016-04-29T12:21:54+00:00" }, { "name": "hamcrest/hamcrest-php", @@ -4120,7 +4332,7 @@ "keywords": [ "test" ], - "time": "2015-05-11 14:41:42" + "time": "2015-05-11T14:41:42+00:00" }, { "name": "mockery/mockery", @@ -4185,7 +4397,7 @@ "test double", "testing" ], - "time": "2016-05-22 21:52:33" + "time": "2016-05-22T21:52:33+00:00" }, { "name": "myclabs/deep-copy", @@ -4227,7 +4439,7 @@ "object", "object graph" ], - "time": "2016-09-16 13:37:59" + "time": "2016-09-16T13:37:59+00:00" }, { "name": "phpdocumentor/reflection-common", @@ -4281,7 +4493,7 @@ "reflection", "static analysis" ], - "time": "2015-12-27 11:43:31" + "time": "2015-12-27T11:43:31+00:00" }, { "name": "phpdocumentor/reflection-docblock", @@ -4326,7 +4538,7 @@ } ], "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", - "time": "2016-06-10 09:48:41" + "time": "2016-06-10T09:48:41+00:00" }, { "name": "phpdocumentor/type-resolver", @@ -4373,7 +4585,7 @@ "email": "me@mikevanriel.com" } ], - "time": "2016-06-10 07:14:17" + "time": "2016-06-10T07:14:17+00:00" }, { "name": "phpspec/php-diff", @@ -4407,7 +4619,7 @@ } ], "description": "A comprehensive library for generating differences between two hashable objects (strings or arrays).", - "time": "2013-11-01 13:02:21" + "time": "2013-11-01T13:02:21+00:00" }, { "name": "phpspec/phpspec", @@ -4485,7 +4697,7 @@ "testing", "tests" ], - "time": "2016-09-26 20:28:11" + "time": "2016-09-26T20:28:11+00:00" }, { "name": "phpspec/prophecy", @@ -4547,7 +4759,7 @@ "spy", "stub" ], - "time": "2016-06-07 08:13:47" + "time": "2016-06-07T08:13:47+00:00" }, { "name": "phpunit/php-code-coverage", @@ -4610,7 +4822,7 @@ "testing", "xunit" ], - "time": "2016-07-26 14:39:29" + "time": "2016-07-26T14:39:29+00:00" }, { "name": "phpunit/php-file-iterator", @@ -4657,7 +4869,7 @@ "filesystem", "iterator" ], - "time": "2015-06-21 13:08:43" + "time": "2015-06-21T13:08:43+00:00" }, { "name": "phpunit/php-text-template", @@ -4698,7 +4910,7 @@ "keywords": [ "template" ], - "time": "2015-06-21 13:50:34" + "time": "2015-06-21T13:50:34+00:00" }, { "name": "phpunit/php-timer", @@ -4742,7 +4954,7 @@ "keywords": [ "timer" ], - "time": "2016-05-12 18:03:57" + "time": "2016-05-12T18:03:57+00:00" }, { "name": "phpunit/php-token-stream", @@ -4791,20 +5003,20 @@ "keywords": [ "tokenizer" ], - "time": "2015-09-15 10:49:45" + "time": "2015-09-15T10:49:45+00:00" }, { "name": "phpunit/phpunit", - "version": "5.5.5", + "version": "5.6.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "a57126dc681b08289fef6ac96a48e30656f84350" + "reference": "4ddb822f1de421b4cadb47570a525fd7d9359493" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/a57126dc681b08289fef6ac96a48e30656f84350", - "reference": "a57126dc681b08289fef6ac96a48e30656f84350", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/4ddb822f1de421b4cadb47570a525fd7d9359493", + "reference": "4ddb822f1de421b4cadb47570a525fd7d9359493", "shasum": "" }, "require": { @@ -4832,13 +5044,14 @@ "symfony/yaml": "~2.1|~3.0" }, "conflict": { - "phpdocumentor/reflection-docblock": "3.0.2" + "phpdocumentor/reflection-docblock": "3.0.2", + "sebastian/object-enumerator": "1.0.1", + "sebastian/recursion-context": "1.0.3 || 1.0.4" }, "require-dev": { "ext-pdo": "*" }, "suggest": { - "ext-tidy": "*", "ext-xdebug": "*", "phpunit/php-invoker": "~1.1" }, @@ -4848,7 +5061,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "5.5.x-dev" + "dev-master": "5.6.x-dev" } }, "autoload": { @@ -4874,7 +5087,7 @@ "testing", "xunit" ], - "time": "2016-09-21 14:40:13" + "time": "2016-11-18T09:50:51+00:00" }, { "name": "phpunit/phpunit-mock-objects", @@ -4933,7 +5146,7 @@ "mock", "xunit" ], - "time": "2016-09-06 16:07:45" + "time": "2016-09-06T16:07:45+00:00" }, { "name": "sebastian/code-unit-reverse-lookup", @@ -4978,7 +5191,7 @@ ], "description": "Looks up which function or method a line of code belongs to", "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/", - "time": "2016-02-13 06:45:14" + "time": "2016-02-13T06:45:14+00:00" }, { "name": "sebastian/comparator", @@ -5042,7 +5255,7 @@ "compare", "equality" ], - "time": "2015-07-26 15:48:44" + "time": "2015-07-26T15:48:44+00:00" }, { "name": "sebastian/diff", @@ -5094,7 +5307,7 @@ "keywords": [ "diff" ], - "time": "2015-12-08 07:14:41" + "time": "2015-12-08T07:14:41+00:00" }, { "name": "sebastian/environment", @@ -5144,7 +5357,7 @@ "environment", "hhvm" ], - "time": "2016-08-18 05:49:44" + "time": "2016-08-18T05:49:44+00:00" }, { "name": "sebastian/exporter", @@ -5211,7 +5424,7 @@ "export", "exporter" ], - "time": "2016-06-17 09:04:28" + "time": "2016-06-17T09:04:28+00:00" }, { "name": "sebastian/global-state", @@ -5262,7 +5475,7 @@ "keywords": [ "global state" ], - "time": "2015-10-12 03:26:01" + "time": "2015-10-12T03:26:01+00:00" }, { "name": "sebastian/object-enumerator", @@ -5308,7 +5521,7 @@ ], "description": "Traverses array structures and object graphs to enumerate all referenced objects", "homepage": "https://github.com/sebastianbergmann/object-enumerator/", - "time": "2016-01-28 13:25:10" + "time": "2016-01-28T13:25:10+00:00" }, { "name": "sebastian/recursion-context", @@ -5361,7 +5574,7 @@ ], "description": "Provides functionality to recursively process PHP variables", "homepage": "http://www.github.com/sebastianbergmann/recursion-context", - "time": "2015-11-11 19:50:13" + "time": "2015-11-11T19:50:13+00:00" }, { "name": "sebastian/resource-operations", @@ -5403,7 +5616,7 @@ ], "description": "Provides a list of PHP built-in functions that operate on resources", "homepage": "https://www.github.com/sebastianbergmann/resource-operations", - "time": "2015-07-28 20:34:47" + "time": "2015-07-28T20:34:47+00:00" }, { "name": "sebastian/version", @@ -5446,7 +5659,7 @@ ], "description": "Library that helps with managing the version number of Git-hosted PHP projects", "homepage": "https://github.com/sebastianbergmann/version", - "time": "2016-02-04 12:56:52" + "time": "2016-02-04T12:56:52+00:00" }, { "name": "symfony/css-selector", @@ -5499,7 +5712,7 @@ ], "description": "Symfony CssSelector Component", "homepage": "https://symfony.com", - "time": "2016-06-29 05:41:56" + "time": "2016-06-29T05:41:56+00:00" }, { "name": "symfony/dom-crawler", @@ -5555,7 +5768,7 @@ ], "description": "Symfony DomCrawler Component", "homepage": "https://symfony.com", - "time": "2016-08-05 08:37:39" + "time": "2016-08-05T08:37:39+00:00" }, { "name": "symfony/yaml", @@ -5604,7 +5817,7 @@ ], "description": "Symfony Yaml Component", "homepage": "https://symfony.com", - "time": "2016-09-02 02:12:52" + "time": "2016-09-02T02:12:52+00:00" }, { "name": "webmozart/assert", @@ -5654,12 +5867,14 @@ "check", "validate" ], - "time": "2016-08-09 15:02:57" + "time": "2016-08-09T15:02:57+00:00" } ], "aliases": [], "minimum-stability": "stable", - "stability-flags": [], + "stability-flags": { + "poniverse/api": 20 + }, "prefer-stable": false, "prefer-lowest": false, "platform": { diff --git a/config/app.php b/config/app.php index 8549b3c8..118ebd9f 100644 --- a/config/app.php +++ b/config/app.php @@ -168,6 +168,7 @@ return [ Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class, Cviebrock\LaravelElasticsearch\ServiceProvider::class, GrahamCampbell\Exceptions\ExceptionsServiceProvider::class, + Poniverse\Lib\PoniverseServiceProvider::class ], @@ -195,14 +196,14 @@ return [ 'DB' => Illuminate\Support\Facades\DB::class, 'Eloquent' => Illuminate\Database\Eloquent\Model::class, 'Event' => Illuminate\Support\Facades\Event::class, -// 'File' => Illuminate\Support\Facades\File::class, + // 'File' => Illuminate\Support\Facades\File::class, 'Gate' => Illuminate\Support\Facades\Gate::class, 'Hash' => Illuminate\Support\Facades\Hash::class, 'Inspiring' => Illuminate\Foundation\Inspiring::class, 'Lang' => Illuminate\Support\Facades\Lang::class, 'Log' => Illuminate\Support\Facades\Log::class, 'Mail' => Illuminate\Support\Facades\Mail::class, - 'Notification' => Illuminate\Support\Facades\Notification::class, + // 'Notification' => Illuminate\Support\Facades\Notification::class, 'Password' => Illuminate\Support\Facades\Password::class, 'Queue' => Illuminate\Support\Facades\Queue::class, 'Redirect' => Illuminate\Support\Facades\Redirect::class, diff --git a/config/poniverse.php b/config/poniverse.php index ff60876d..5aa25751 100644 --- a/config/poniverse.php +++ b/config/poniverse.php @@ -1,12 +1,5 @@ 1, - 'urls' => [ - 'api' => env('PONI_API_URL', 'https://api.poniverse.net/v1/'), - 'register' => env('PONI_REGISTER_URL', 'https://poniverse.net/register?site=pony.fm'), - 'auth' => env('PONI_AUTH_URL', 'https://poniverse.net/oauth/authorize'), - 'token' => env('PONI_TOKEN_URL', 'https://poniverse.net/oauth/access_token') - ], 'client_id' => env('PONI_CLIENT_ID'), 'secret' => env('PONI_CLIENT_SECRET') ]; diff --git a/database/migrations/2016_07_10_000354_add_deleted_at_column_to_activities.php b/database/migrations/2016_07_10_000354_add_deleted_at_column_to_activities.php index 6c4bad34..ed990ad4 100644 --- a/database/migrations/2016_07_10_000354_add_deleted_at_column_to_activities.php +++ b/database/migrations/2016_07_10_000354_add_deleted_at_column_to_activities.php @@ -35,34 +35,36 @@ class AddDeletedAtColumnToActivities extends Migration $table->softDeletes()->index(); }); - // Retroactively fix activities that should be marked as deleted. - // Tracks - DB::table('activities') - ->where('resource_type', 2) - ->join('tracks', 'activities.resource_id', '=', 'tracks.id') - ->whereNotNull('tracks.deleted_at') - ->update(['deleted_at' => DB::raw('tracks.deleted_at')]); + if ('sqlite' !== DB::getDriverName()) { + // Retroactively fix activities that should be marked as deleted. + // Tracks + DB::table('activities') + ->where('resource_type', 2) + ->join('tracks', 'activities.resource_id', '=', 'tracks.id') + ->whereNotNull('tracks.deleted_at') + ->update(['deleted_at' => DB::raw('tracks.deleted_at')]); - // Albums - DB::table('activities') - ->where('resource_type', 3) - ->join('albums', 'activities.resource_id', '=', 'albums.id') - ->whereNotNull('albums.deleted_at') - ->update(['deleted_at' => DB::raw('albums.deleted_at')]); + // Albums + DB::table('activities') + ->where('resource_type', 3) + ->join('albums', 'activities.resource_id', '=', 'albums.id') + ->whereNotNull('albums.deleted_at') + ->update(['deleted_at' => DB::raw('albums.deleted_at')]); - // Playlists - DB::table('activities') - ->where('resource_type', 4) - ->join('playlists', 'activities.resource_id', '=', 'playlists.id') - ->whereNotNull('playlists.deleted_at') - ->update(['deleted_at' => DB::raw('playlists.deleted_at')]); + // Playlists + DB::table('activities') + ->where('resource_type', 4) + ->join('playlists', 'activities.resource_id', '=', 'playlists.id') + ->whereNotNull('playlists.deleted_at') + ->update(['deleted_at' => DB::raw('playlists.deleted_at')]); - // Comments - DB::table('activities') - ->where('resource_type', 5) - ->join('comments', 'activities.resource_id', '=', 'comments.id') - ->whereNotNull('comments.deleted_at') - ->update(['deleted_at' => DB::raw('comments.deleted_at')]); + // Comments + DB::table('activities') + ->where('resource_type', 5) + ->join('comments', 'activities.resource_id', '=', 'comments.id') + ->whereNotNull('comments.deleted_at') + ->update(['deleted_at' => DB::raw('comments.deleted_at')]); + } } } diff --git a/database/migrations/2016_08_15_103625_add_version_column_to_tracks_table.php b/database/migrations/2016_08_15_103625_add_version_column_to_tracks_table.php index 9577b082..09292981 100644 --- a/database/migrations/2016_08_15_103625_add_version_column_to_tracks_table.php +++ b/database/migrations/2016_08_15_103625_add_version_column_to_tracks_table.php @@ -26,8 +26,7 @@ class AddVersionColumnToTracksTable extends Migration public function down() { Schema::table('tracks', function (Blueprint $table) { - $table->dropColumn('current_version'); - $table->dropColumn('version_upload_status'); + $table->dropColumn(['current_version', 'version_upload_status']); }); } } diff --git a/database/migrations/2016_09_29_222123_update_sessions_table_for_laravel_52.php b/database/migrations/2016_09_29_222123_update_sessions_table_for_laravel_52.php index a602807e..002cd45a 100644 --- a/database/migrations/2016_09_29_222123_update_sessions_table_for_laravel_52.php +++ b/database/migrations/2016_09_29_222123_update_sessions_table_for_laravel_52.php @@ -27,9 +27,7 @@ class UpdateSessionsTableForLaravel52 extends Migration public function down() { Schema::table('sessions', function(Blueprint $table) { - $table->dropColumn('user_id'); - $table->dropColumn('ip_address'); - $table->dropColumn('user_agent'); + $table->dropColumn(['user_id', 'ip_address', 'user_agent']); }); } } diff --git a/tests/ApiAuthTest.php b/tests/ApiAuthTest.php index 65b97803..52942d66 100644 --- a/tests/ApiAuthTest.php +++ b/tests/ApiAuthTest.php @@ -21,6 +21,7 @@ use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; +use Poniverse\Lib\AccessToken; use Poniverse\Ponyfm\Models\User; class ApiAuthTest extends TestCase @@ -35,22 +36,22 @@ class ApiAuthTest extends TestCase public function testApiCreatesNewUser() { $user = factory(User::class)->make(); - $accessTokenInfo = new \Poniverse\AccessTokenInfo('nonsense-token'); + $accessTokenInfo = new AccessToken('nonsense-token'); $accessTokenInfo->setIsActive(true); $accessTokenInfo->setScopes(['basic', 'ponyfm:tracks:upload']); - $poniverse = Mockery::mock('overload:Poniverse'); - $poniverse->shouldReceive('getUser') - ->andReturn([ + $poniverse = Mockery::mock('overload:Poniverse\Lib\OAuth2\PoniverseProvider'); + $poniverse->shouldReceive('getResourceOwner') + ->andReturn(new \Poniverse\Lib\Entity\Poniverse\User([ + 'id' => $user->id, 'username' => $user->username, 'display_name' => $user->display_name, 'email' => $user->email, - ]); - + ])); $poniverse->shouldReceive('setAccessToken'); - $poniverse - ->shouldReceive('getAccessTokenInfo') + $accessTokenService = Mockery::mock('overload:Poniverse\Lib\Service\Poniverse\AccessTokenInfo'); + $accessTokenService->shouldReceive('introspect') ->andReturn($accessTokenInfo); $this->dontSeeInDatabase('users', ['username' => $user->username]); @@ -61,23 +62,25 @@ class ApiAuthTest extends TestCase public function testApiClientIdIsRecordedWhenUploadingTrack() { $user = factory(User::class)->make(); - $accessTokenInfo = new \Poniverse\AccessTokenInfo('nonsense-token'); + + $accessTokenInfo = new AccessToken('nonsense-token'); $accessTokenInfo->setIsActive(true); $accessTokenInfo->setClientId('Unicorns and rainbows'); $accessTokenInfo->setScopes(['basic', 'ponyfm:tracks:upload']); - $poniverse = Mockery::mock('overload:Poniverse'); - $poniverse->shouldReceive('getUser') - ->andReturn([ + $poniverse = Mockery::mock('overload:Poniverse\Lib\OAuth2\PoniverseProvider'); + $poniverse->shouldReceive('getResourceOwner') + ->andReturn(new \Poniverse\Lib\Entity\Poniverse\User([ + 'id' => $user->id, 'username' => $user->username, 'display_name' => $user->display_name, 'email' => $user->email, - ]); - + ])); $poniverse->shouldReceive('setAccessToken'); - $poniverse - ->shouldReceive('getAccessTokenInfo') + $accessTokenService = Mockery::mock('overload:Poniverse\Lib\Service\Poniverse\AccessTokenInfo'); + $accessTokenService + ->shouldReceive('introspect') ->andReturn($accessTokenInfo); $this->callUploadWithParameters(['access_token' => $accessTokenInfo->getToken()]); diff --git a/tests/TestCase.php b/tests/TestCase.php index a795f7ef..d969a936 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -123,7 +123,7 @@ class TestCase extends Illuminate\Foundation\Testing\TestCase Storage::disk('local')->makeDirectory('testing-datastore/tmp'); Storage::disk('local')->copy("test-files/${filename}", "testing-datastore/tmp/${filename}"); - return new \Symfony\Component\HttpFoundation\File\UploadedFile(storage_path("app/testing-datastore/tmp/${filename}"), $filename, null, null, null, true); + return new \Illuminate\Http\UploadedFile(storage_path("app/testing-datastore/tmp/${filename}"), $filename, null, null, null, true); } /**