diff --git a/app/config/poniverse.php b/app/config/poniverse.php new file mode 100644 index 00000000..09a5b33a --- /dev/null +++ b/app/config/poniverse.php @@ -0,0 +1,11 @@ + 1, + 'urls' => [ + 'api' => '', + 'auth' => '', + 'token' => '' + ], + 'client_id' => 0, + 'secret' => '' + ]; \ No newline at end of file diff --git a/app/controllers/Api/Web/AuthController.php b/app/controllers/Api/Web/AuthController.php index e2249578..80d2de07 100644 --- a/app/controllers/Api/Web/AuthController.php +++ b/app/controllers/Api/Web/AuthController.php @@ -5,26 +5,7 @@ use Commands\RegisterUserCommand; class AuthController extends \Controller { - public function postLogin() { - if (!\Auth::attempt(array('email' => \Input::get('email'), 'password' => \Input::get('password')), \Input::get('remember'))) - return \Response::json(['messages' => ['username' => 'Invalid username or password']], 400); - - return \Response::json(['user' => \Auth::user()]); - } - public function postLogout() { \Auth::logout(); } - - public function postRegister() { - $command = new RegisterUserCommand(); - if (!$command->authorize()) - return \Response::json([], 403); - - $errors = $command->validate(); - if ($errors->fails()) - return \Response::json([], 400); - - return \Response::json($command->execute()); - } } \ No newline at end of file diff --git a/app/controllers/Api/Web/DashboardController.php b/app/controllers/Api/Web/DashboardController.php index 4a9936e4..e444ee61 100644 --- a/app/controllers/Api/Web/DashboardController.php +++ b/app/controllers/Api/Web/DashboardController.php @@ -20,7 +20,7 @@ ->explicitFilter() ->published() ->orderBy('published_at', 'desc') - ->take(30); + ->take(20); $recentTracks = []; diff --git a/app/controllers/AuthController.php b/app/controllers/AuthController.php new file mode 100644 index 00000000..f0b96bf8 --- /dev/null +++ b/app/controllers/AuthController.php @@ -0,0 +1,93 @@ +poniverse = new Poniverse(Config::get('poniverse.client_id'), Config::get('poniverse.secret')); + } + + public function getLogin() { + if (Auth::guest()) + return Redirect::to($this->poniverse->getAuthenticationUrl('login')); + + return Redirect::to('/'); + } + + public function postLogout() { + Auth::logout(); + return Redirect::to('/'); + } + + public function getOAuth() { + $code = $this->poniverse->getClient()->getAccessToken( + Config::get('poniverse.urls')['token'], + 'authorization_code', + [ + 'code' => Input::query('code'), + 'redirect_uri' => URL::to('/auth/oauth') + ]); + + 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')); + } + + return Redirect::to('/')->with('message', 'Unfortunately we are having problems attempting to log you in at the moment. Please try again at a later time.' ); + } + + $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(); + + $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'], + ]; + + if(isset($code['result']['refresh_token']) && !empty($code['result']['refresh_token'])) { + $setData['refresh_token'] = $code['result']['refresh_token']; + } + + 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 email to see if they already have an account + $localMember = User::where('email', '=', $poniverseUser['email'])->first(); + + if ($localMember) { + return $this->loginRedirect($localMember); + } + + $user = new User; + + $user->username = $poniverseUser['username']; + $user->display_name = $poniverseUser['display_name']; + $user->email = $poniverseUser['email']; + $user->created_at = gmdate("Y-m-d H:i:s", time()); + + $user->save(); + $user->roles()->attach(4); + + //We need to insert a new token row :O + + $setData['user_id'] = $user->id; + $setData['external_user_id'] = $poniverseUser['id']; + $setData['service'] = 'poniverse'; + + DB::table('oauth2_tokens')->insert($setData); + + return $this->loginRedirect($user); + } + + protected function loginRedirect($user, $rememberMe = true) { + Auth::login($user, $rememberMe); + return Redirect::to('/'); + } + } \ No newline at end of file diff --git a/app/database/migrations/2013_09_01_025031_oauth.php b/app/database/migrations/2013_09_01_025031_oauth.php new file mode 100644 index 00000000..0606d77c --- /dev/null +++ b/app/database/migrations/2013_09_01_025031_oauth.php @@ -0,0 +1,22 @@ +increments('id'); + $table->integer('user_id'); + $table->integer('external_user_id'); + $table->text('access_token'); + $table->timestamp('expires'); + $table->text('refresh_token'); + $table->string('type'); + $table->string('service'); + }); + } + + public function down() { + Schema::drop('oauth2_tokens'); + } +} \ No newline at end of file diff --git a/app/library/PFMAuth.php b/app/library/PFMAuth.php index 277a65a0..3e68067e 100644 --- a/app/library/PFMAuth.php +++ b/app/library/PFMAuth.php @@ -1,15 +1,21 @@ hasher->check($plain, $user->getAuthPassword(), ['salt' => $user->password_salt]); + parent::__construct(new NullHasher(), 'Entities\User'); } } \ No newline at end of file diff --git a/app/library/Poniverse/Poniverse.php b/app/library/Poniverse/Poniverse.php new file mode 100644 index 00000000..3ad250cf --- /dev/null +++ b/app/library/Poniverse/Poniverse.php @@ -0,0 +1,95 @@ +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); + } +} \ No newline at end of file diff --git a/app/library/Poniverse/autoloader.php b/app/library/Poniverse/autoloader.php new file mode 100644 index 00000000..54a20935 --- /dev/null +++ b/app/library/Poniverse/autoloader.php @@ -0,0 +1,137 @@ +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(array($this, 'loadClass')); + } + + /** + * Uninstalls this class loader from the SPL autoloader stack. + */ + public function unregister() + { + spl_autoload_unregister(array($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; + } + } +} \ No newline at end of file diff --git a/app/library/Poniverse/httpful/.gitignore b/app/library/Poniverse/httpful/.gitignore new file mode 100644 index 00000000..d1584ef4 --- /dev/null +++ b/app/library/Poniverse/httpful/.gitignore @@ -0,0 +1,4 @@ +.DS_Store +composer.lock +vendor +downloads diff --git a/app/library/Poniverse/httpful/.travis.yml b/app/library/Poniverse/httpful/.travis.yml new file mode 100644 index 00000000..ba03761e --- /dev/null +++ b/app/library/Poniverse/httpful/.travis.yml @@ -0,0 +1,5 @@ +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 new file mode 100644 index 00000000..90892706 --- /dev/null +++ b/app/library/Poniverse/httpful/LICENSE.txt @@ -0,0 +1,7 @@ +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 new file mode 100644 index 00000000..f816015a --- /dev/null +++ b/app/library/Poniverse/httpful/README.md @@ -0,0 +1,150 @@ +# 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 new file mode 100644 index 00000000..10f2a7cf --- /dev/null +++ b/app/library/Poniverse/httpful/bootstrap.php @@ -0,0 +1,4 @@ +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 new file mode 100644 index 00000000..6d61e6e7 --- /dev/null +++ b/app/library/Poniverse/httpful/composer.json @@ -0,0 +1,27 @@ +{ + "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 new file mode 100644 index 00000000..bb3b528f --- /dev/null +++ b/app/library/Poniverse/httpful/examples/freebase.php @@ -0,0 +1,12 @@ +expectsJson() + ->sendIt(); + +echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n"; \ No newline at end of file diff --git a/app/library/Poniverse/httpful/examples/github.php b/app/library/Poniverse/httpful/examples/github.php new file mode 100644 index 00000000..8eb3f3ba --- /dev/null +++ b/app/library/Poniverse/httpful/examples/github.php @@ -0,0 +1,9 @@ +send(); + +echo "{$request->body->name} joined GitHub on " . date('M jS', strtotime($request->body->{'created-at'})) ."\n"; \ No newline at end of file diff --git a/app/library/Poniverse/httpful/examples/override.php b/app/library/Poniverse/httpful/examples/override.php new file mode 100644 index 00000000..2c3bdd5c --- /dev/null +++ b/app/library/Poniverse/httpful/examples/override.php @@ -0,0 +1,44 @@ + '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()); \ No newline at end of file diff --git a/app/library/Poniverse/httpful/examples/showclix.php b/app/library/Poniverse/httpful/examples/showclix.php new file mode 100644 index 00000000..9c50bf5f --- /dev/null +++ b/app/library/Poniverse/httpful/examples/showclix.php @@ -0,0 +1,24 @@ +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(array('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"; \ No newline at end of file diff --git a/app/library/Poniverse/httpful/src/Httpful/Bootstrap.php b/app/library/Poniverse/httpful/src/Httpful/Bootstrap.php new file mode 100644 index 00000000..3bf62ae6 --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Bootstrap.php @@ -0,0 +1,97 @@ + + */ +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(array('\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(array('\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 = array( + \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 new file mode 100644 index 00000000..bba73a69 --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Exception/ConnectionErrorException.php @@ -0,0 +1,7 @@ + + */ + +namespace Httpful\Handlers; + +class CsvHandler extends MimeHandlerAdapter +{ + /** + * @param string $body + * @return mixed + */ + public function parse($body) + { + if (empty($body)) + return null; + + $parsed = array(); + $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 new file mode 100644 index 00000000..fea1c37c --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Handlers/FormHandler.php @@ -0,0 +1,30 @@ + + */ + +namespace Httpful\Handlers; + +class FormHandler extends MimeHandlerAdapter +{ + /** + * @param string $body + * @return mixed + */ + public function parse($body) + { + $parsed = array(); + parse_str($body, $parsed); + return $parsed; + } + + /** + * @param mixed $payload + * @return string + */ + public function serialize($payload) + { + return http_build_query($payload, null, '&'); + } +} \ No newline at end of file diff --git a/app/library/Poniverse/httpful/src/Httpful/Handlers/JsonHandler.php b/app/library/Poniverse/httpful/src/Httpful/Handlers/JsonHandler.php new file mode 100644 index 00000000..6520d933 --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Handlers/JsonHandler.php @@ -0,0 +1,40 @@ + + */ + +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); + } +} \ No newline at end of file diff --git a/app/library/Poniverse/httpful/src/Httpful/Handlers/MimeHandlerAdapter.php b/app/library/Poniverse/httpful/src/Httpful/Handlers/MimeHandlerAdapter.php new file mode 100644 index 00000000..dd15c04c --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Handlers/MimeHandlerAdapter.php @@ -0,0 +1,43 @@ +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; + } +} \ No newline at end of file diff --git a/app/library/Poniverse/httpful/src/Httpful/Handlers/README.md b/app/library/Poniverse/httpful/src/Httpful/Handlers/README.md new file mode 100644 index 00000000..5542d406 --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Handlers/README.md @@ -0,0 +1,44 @@ +# 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 +} \ No newline at end of file diff --git a/app/library/Poniverse/httpful/src/Httpful/Handlers/XmlHandler.php b/app/library/Poniverse/httpful/src/Httpful/Handlers/XmlHandler.php new file mode 100644 index 00000000..4b11659b --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Handlers/XmlHandler.php @@ -0,0 +1,120 @@ + + * @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 = array()) + { + $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 array($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 array($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 array($parent, $dom); + } +} \ No newline at end of file diff --git a/app/library/Poniverse/httpful/src/Httpful/Http.php b/app/library/Poniverse/httpful/src/Httpful/Http.php new file mode 100644 index 00000000..59374e93 --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Http.php @@ -0,0 +1,86 @@ + + */ +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 array(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 array(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 array(self::POST, self::PUT, self::PATCH, self::OPTIONS); + } + +} \ No newline at end of file diff --git a/app/library/Poniverse/httpful/src/Httpful/Httpful.php b/app/library/Poniverse/httpful/src/Httpful/Httpful.php new file mode 100644 index 00000000..98cd75a9 --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Httpful.php @@ -0,0 +1,46 @@ + + */ +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 = array( + '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 new file mode 100644 index 00000000..63b92ecb --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Request.php @@ -0,0 +1,1023 @@ + + */ +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 = array(), + $raw_headers = '', + $strict_ssl = false, + $content_type, + $expected_type, + $additional_curl_opts = array(), + $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 = array(); + + // 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, array(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(array('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 = array(); + // 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 new file mode 100644 index 00000000..c5199d3e --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Response.php @@ -0,0 +1,189 @@ + + */ +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 = array(); + 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 new file mode 100644 index 00000000..7abc57dd --- /dev/null +++ b/app/library/Poniverse/httpful/src/Httpful/Response/Headers.php @@ -0,0 +1,58 @@ +headers = $headers; + } + + public static function fromString($string) + { + $lines = preg_split("/(\r|\n)+/", $string, -1, PREG_SPLIT_NO_EMPTY); + array_shift($lines); // HTTP HEADER + $headers = array(); + 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; + } + +} \ No newline at end of file diff --git a/app/library/Poniverse/httpful/tests/Httpful/HttpfulTest.php b/app/library/Poniverse/httpful/tests/Httpful/HttpfulTest.php new file mode 100644 index 00000000..ac2ab546 --- /dev/null +++ b/app/library/Poniverse/httpful/tests/Httpful/HttpfulTest.php @@ -0,0 +1,458 @@ + + */ +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 = array('get', 'post', 'delete', 'put', 'options', 'head'); + $url = 'http://example.com/'; + foreach ($valid_methods as $method) { + $r = call_user_func(array('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 = array('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 new file mode 100644 index 00000000..8f62e80a --- /dev/null +++ b/app/library/Poniverse/httpful/tests/phpunit.xml @@ -0,0 +1,9 @@ + + + . + + + + + + diff --git a/app/library/Poniverse/oauth2/Client.php b/app/library/Poniverse/oauth2/Client.php new file mode 100644 index 00000000..698739fc --- /dev/null +++ b/app/library/Poniverse/oauth2/Client.php @@ -0,0 +1,515 @@ + + * @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 = array(); + + /** + * 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 = array()) + { + $parameters = array_merge(array( + '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) + */ + 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 = array(); + 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 = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = array(), $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 = array(), $http_method = self::HTTP_METHOD_GET, array $http_headers = null, $form_content_type = self::HTTP_FORM_CONTENT_TYPE_MULTIPART) + { + $curl_options = array( + 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 = array(); + 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 array( + '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 new file mode 100644 index 00000000..f3436e4c --- /dev/null +++ b/app/library/Poniverse/oauth2/GrantType/AuthorizationCode.php @@ -0,0 +1,41 @@ +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 new file mode 100644 index 00000000..2e052a52 --- /dev/null +++ b/app/library/Poniverse/oauth2/composer.json @@ -0,0 +1,19 @@ +{ + "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/routes.php b/app/routes.php index bdbe18c0..0a0ae864 100644 --- a/app/routes.php +++ b/app/routes.php @@ -34,8 +34,8 @@ Route::get('artists', 'ArtistsController@getIndex'); Route::get('playlists', 'PlaylistsController@getIndex'); - Route::get('/login', function() { return View::make('auth.login'); }); - Route::get('/register', function() { return View::make('auth.register'); }); + Route::get('/login', 'AuthController@getLogin'); + Route::get('/auth/oauth', 'AuthController@getOAuth'); Route::get('/about', function() { return View::make('pages.about'); }); Route::get('/faq', function() { return View::make('pages.faq'); }); @@ -114,7 +114,6 @@ }); Route::group(['before' => 'csrf'], function(){ - Route::post('/auth/login', 'Api\Web\AuthController@postLogin'); Route::post('/auth/logout', 'Api\Web\AuthController@postLogout'); }); }); diff --git a/app/start/global.php b/app/start/global.php index d132a255..b507135b 100644 --- a/app/start/global.php +++ b/app/start/global.php @@ -20,6 +20,7 @@ app_path().'/models', app_path().'/library', app_path().'/database/seeds', + app_path().'/library/Poniverse', )); diff --git a/app/views/shared/_app_layout.blade.php b/app/views/shared/_app_layout.blade.php index aa7ceb2a..cc97f4b5 100644 --- a/app/views/shared/_app_layout.blade.php +++ b/app/views/shared/_app_layout.blade.php @@ -74,6 +74,8 @@ + @else +
  • Login
  • @endif diff --git a/vendor/autoload.php b/vendor/autoload.php index 5e1b54cb..8da77fca 100644 --- a/vendor/autoload.php +++ b/vendor/autoload.php @@ -4,4 +4,4 @@ require_once __DIR__ . '/composer' . '/autoload_real.php'; -return ComposerAutoloaderInitf5e8b08f8d3ef98cfbf31c8bbf4b6225::getLoader(); +return ComposerAutoloaderInit97c5c8042cf61f3c9c7ef80776c5c224::getLoader(); diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php index 079b2c6f..2604e666 100644 --- a/vendor/composer/autoload_classmap.php +++ b/vendor/composer/autoload_classmap.php @@ -18,6 +18,7 @@ return array( 'Api\\Web\\CommentsController' => $baseDir . '/app/controllers/Api/Web/CommentsController.php', 'Api\\Web\\DashboardController' => $baseDir . '/app/controllers/Api/Web/DashboardController.php', 'Api\\Web\\FavouritesController' => $baseDir . '/app/controllers/Api/Web/FavouritesController.php', + 'Api\\Web\\FollowController' => $baseDir . '/app/controllers/Api/Web/FollowController.php', 'Api\\Web\\ImagesController' => $baseDir . '/app/controllers/Api/Web/ImagesController.php', 'Api\\Web\\PlaylistsController' => $baseDir . '/app/controllers/Api/Web/PlaylistsController.php', 'Api\\Web\\ProfilerController' => $baseDir . '/app/controllers/Api/Web/ProfilerController.php', @@ -121,6 +122,7 @@ return array( 'Assetic\\Util\\TraversableString' => $vendorDir . '/kriswallsmith/assetic/src/Assetic/Util/TraversableString.php', 'Assetic\\Util\\VarUtils' => $vendorDir . '/kriswallsmith/assetic/src/Assetic/Util/VarUtils.php', 'Assetic\\ValueSupplierInterface' => $vendorDir . '/kriswallsmith/assetic/src/Assetic/ValueSupplierInterface.php', + 'AuthController' => $baseDir . '/app/controllers/AuthController.php', 'Carbon\\Carbon' => $vendorDir . '/nesbot/carbon/Carbon/Carbon.php', 'Carbon\\Tests\\TestFixture' => $vendorDir . '/nesbot/carbon/Carbon/Tests/TestFixture.php', 'ClassPreloader\\Application' => $vendorDir . '/classpreloader/classpreloader/src/ClassPreloader/Application.php', @@ -147,6 +149,7 @@ return array( 'Commands\\EditTrackCommand' => $baseDir . '/app/models/Commands/EditTrackCommand.php', 'Commands\\SaveAccountSettingsCommand' => $baseDir . '/app/models/Commands/SaveAccountSettingsCommand.php', 'Commands\\ToggleFavouriteCommand' => $baseDir . '/app/models/Commands/ToggleFavouriteCommand.php', + 'Commands\\ToggleFollowingCommand' => $baseDir . '/app/models/Commands/ToggleFollowingCommand.php', 'Commands\\UploadTrackCommand' => $baseDir . '/app/models/Commands/UploadTrackCommand.php', 'ContentController' => $baseDir . '/app/controllers/ContentController.php', 'CreateAlbums' => $baseDir . '/app/database/migrations/2013_07_28_060804_create_albums.php', @@ -428,6 +431,7 @@ return array( 'Entities\\Album' => $baseDir . '/app/models/Entities/Album.php', 'Entities\\Comment' => $baseDir . '/app/models/Entities/Comment.php', 'Entities\\Favourite' => $baseDir . '/app/models/Entities/Favourite.php', + 'Entities\\Follower' => $baseDir . '/app/models/Entities/Follower.php', 'Entities\\Genre' => $baseDir . '/app/models/Entities/Genre.php', 'Entities\\Image' => $baseDir . '/app/models/Entities/Image.php', 'Entities\\License' => $baseDir . '/app/models/Entities/License.php', @@ -879,6 +883,7 @@ return array( 'Monolog\\Processor\\UidProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/UidProcessor.php', 'Monolog\\Processor\\WebProcessor' => $vendorDir . '/monolog/monolog/src/Monolog/Processor/WebProcessor.php', 'Normalizer' => $vendorDir . '/patchwork/utf8/class/Normalizer.php', + 'Oauth' => $baseDir . '/app/database/migrations/2013_09_01_025031_oauth.php', 'OutputProvider' => $vendorDir . '/codescale/ffmpeg-php/provider/OutputProvider.php', 'PHPParser_Autoloader' => $vendorDir . '/nikic/php-parser/lib/PHPParser/Autoloader.php', 'PHPParser_Builder' => $vendorDir . '/nikic/php-parser/lib/PHPParser/Builder.php', @@ -1863,6 +1868,7 @@ return array( 'TestCase' => $baseDir . '/app/tests/TestCase.php', 'TracksController' => $baseDir . '/app/controllers/TracksController.php', 'Traits\\SlugTrait' => $baseDir . '/app/models/Traits/SlugTrait.php', + 'UploaderController' => $baseDir . '/app/controllers/UploaderController.php', 'UsersController' => $baseDir . '/app/controllers/UsersController.php', 'Whoops\\Exception\\ErrorException' => $vendorDir . '/filp/whoops/src/Whoops/Exception/ErrorException.php', 'Whoops\\Exception\\Frame' => $vendorDir . '/filp/whoops/src/Whoops/Exception/Frame.php', diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php index 2284954b..ba76e071 100644 --- a/vendor/composer/autoload_real.php +++ b/vendor/composer/autoload_real.php @@ -2,7 +2,7 @@ // autoload_real.php generated by Composer -class ComposerAutoloaderInitf5e8b08f8d3ef98cfbf31c8bbf4b6225 +class ComposerAutoloaderInit97c5c8042cf61f3c9c7ef80776c5c224 { private static $loader; @@ -19,9 +19,9 @@ class ComposerAutoloaderInitf5e8b08f8d3ef98cfbf31c8bbf4b6225 return self::$loader; } - spl_autoload_register(array('ComposerAutoloaderInitf5e8b08f8d3ef98cfbf31c8bbf4b6225', 'loadClassLoader'), true, true); + spl_autoload_register(array('ComposerAutoloaderInit97c5c8042cf61f3c9c7ef80776c5c224', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); - spl_autoload_unregister(array('ComposerAutoloaderInitf5e8b08f8d3ef98cfbf31c8bbf4b6225', 'loadClassLoader')); + spl_autoload_unregister(array('ComposerAutoloaderInit97c5c8042cf61f3c9c7ef80776c5c224', 'loadClassLoader')); $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir);