diff --git a/composer.lock b/composer.lock index 278d103..ac268c8 100644 --- a/composer.lock +++ b/composer.lock @@ -4,58 +4,8 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "bf0772b9501ce6231c06bfbcdb671d1d", - "content-hash": "49b3f5550e60b62ffeb5306a75a87d97", + "content-hash": "ccdcfdb56ed68253e2388261fbb6d1b3", "packages": [ - { - "name": "bshaffer/oauth2-server-php", - "version": "v1.8.0", - "source": { - "type": "git", - "url": "https://github.com/bshaffer/oauth2-server-php.git", - "reference": "058c98f73209f9c49495e1799d32c035196fe8b8" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/bshaffer/oauth2-server-php/zipball/058c98f73209f9c49495e1799d32c035196fe8b8", - "reference": "058c98f73209f9c49495e1799d32c035196fe8b8", - "shasum": "" - }, - "require": { - "php": ">=5.3.9" - }, - "suggest": { - "aws/aws-sdk-php": "~2.8 is required to use the DynamoDB storage engine", - "firebase/php-jwt": "~2.2 is required to use JWT features", - "predis/predis": "Required to use the Redis storage engine", - "thobbs/phpcassa": "Required to use the Cassandra storage engine" - }, - "type": "library", - "autoload": { - "psr-0": { - "OAuth2": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Brent Shaffer", - "email": "bshafs@gmail.com", - "homepage": "http://brentertainment.com" - } - ], - "description": "OAuth2 Server for PHP", - "homepage": "http://github.com/bshaffer/oauth2-server-php", - "keywords": [ - "auth", - "oauth", - "oauth2" - ], - "time": "2015-09-18 18:05:10" - }, { "name": "codeguy/upload", "version": "1.3.2", @@ -101,7 +51,7 @@ "upload", "validation" ], - "time": "2013-07-07 17:01:41" + "time": "2013-07-07T17:01:41+00:00" }, { "name": "container-interop/container-interop", @@ -128,22 +78,25 @@ "MIT" ], "description": "Promoting the interoperability of container objects (DIC, SL, etc.)", - "time": "2014-12-30 15:22:37" + "time": "2014-12-30T15:22:37+00:00" }, { "name": "erusev/parsedown", - "version": "1.6.0", + "version": "1.6.1", "source": { "type": "git", "url": "https://github.com/erusev/parsedown.git", - "reference": "3ebbd730b5c2cf5ce78bc1bf64071407fc6674b7" + "reference": "20ff8bbb57205368b4b42d094642a3e52dac85fb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/erusev/parsedown/zipball/3ebbd730b5c2cf5ce78bc1bf64071407fc6674b7", - "reference": "3ebbd730b5c2cf5ce78bc1bf64071407fc6674b7", + "url": "https://api.github.com/repos/erusev/parsedown/zipball/20ff8bbb57205368b4b42d094642a3e52dac85fb", + "reference": "20ff8bbb57205368b4b42d094642a3e52dac85fb", "shasum": "" }, + "require": { + "php": ">=5.3.0" + }, "type": "library", "autoload": { "psr-0": { @@ -167,20 +120,20 @@ "markdown", "parser" ], - "time": "2015-10-04 16:44:32" + "time": "2016-11-02T15:56:58+00:00" }, { "name": "fguillot/picofeed", - "version": "v0.1.23", + "version": "v0.1.28", "source": { "type": "git", "url": "https://github.com/fguillot/picoFeed.git", - "reference": "a7c3d420c239fe9ffc39b0d06b6e57db39ce3797" + "reference": "9da506c308bcb40b6fc630f9123466028c03170b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/fguillot/picoFeed/zipball/a7c3d420c239fe9ffc39b0d06b6e57db39ce3797", - "reference": "a7c3d420c239fe9ffc39b0d06b6e57db39ce3797", + "url": "https://api.github.com/repos/fguillot/picoFeed/zipball/9da506c308bcb40b6fc630f9123466028c03170b", + "reference": "9da506c308bcb40b6fc630f9123466028c03170b", "shasum": "" }, "require": { @@ -192,6 +145,11 @@ "php": ">=5.3.0", "zendframework/zendxml": "^1.0" }, + "require-dev": { + "phpdocumentor/reflection-docblock": "2.0.4", + "phpunit/phpunit": "4.8.26", + "symfony/yaml": "2.8.7" + }, "suggest": { "ext-curl": "PicoFeed will use cURL if present" }, @@ -215,20 +173,20 @@ ], "description": "Modern library to handle RSS/Atom feeds", "homepage": "https://github.com/fguillot/picoFeed", - "time": "2016-04-17 22:31:55" + "time": "2016-12-29T00:06:41+00:00" }, { "name": "nikic/fast-route", - "version": "v0.6.0", + "version": "v1.1.0", "source": { "type": "git", "url": "https://github.com/nikic/FastRoute.git", - "reference": "31fa86924556b80735f98b294a7ffdfb26789f22" + "reference": "f3dcf5130e634b6123d40727d612ec6aa4f61fb3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/FastRoute/zipball/31fa86924556b80735f98b294a7ffdfb26789f22", - "reference": "31fa86924556b80735f98b294a7ffdfb26789f22", + "url": "https://api.github.com/repos/nikic/FastRoute/zipball/f3dcf5130e634b6123d40727d612ec6aa4f61fb3", + "reference": "f3dcf5130e634b6123d40727d612ec6aa4f61fb3", "shasum": "" }, "require": { @@ -258,7 +216,7 @@ "router", "routing" ], - "time": "2015-06-18 19:15:47" + "time": "2016-10-20T17:36:47+00:00" }, { "name": "pimple/pimple", @@ -304,20 +262,20 @@ "container", "dependency injection" ], - "time": "2015-09-11 15:10:35" + "time": "2015-09-11T15:10:35+00:00" }, { "name": "psr/http-message", - "version": "1.0", + "version": "1.0.1", "source": { "type": "git", "url": "https://github.com/php-fig/http-message.git", - "reference": "85d63699f0dbedb190bbd4b0d2b9dc707ea4c298" + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/http-message/zipball/85d63699f0dbedb190bbd4b0d2b9dc707ea4c298", - "reference": "85d63699f0dbedb190bbd4b0d2b9dc707ea4c298", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", "shasum": "" }, "require": { @@ -345,6 +303,7 @@ } ], "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", "keywords": [ "http", "http-message", @@ -353,29 +312,32 @@ "request", "response" ], - "time": "2015-05-04 20:22:00" + "time": "2016-08-06T14:39:51+00:00" }, { "name": "slim/slim", - "version": "3.3.0", + "version": "3.7.0", "source": { "type": "git", "url": "https://github.com/slimphp/Slim.git", - "reference": "939f2e85d57508de9cff241d10091cd972f221c3" + "reference": "4254e40d81559e35cdf856bcbaca5f3af468b7ef" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/slimphp/Slim/zipball/939f2e85d57508de9cff241d10091cd972f221c3", - "reference": "939f2e85d57508de9cff241d10091cd972f221c3", + "url": "https://api.github.com/repos/slimphp/Slim/zipball/4254e40d81559e35cdf856bcbaca5f3af468b7ef", + "reference": "4254e40d81559e35cdf856bcbaca5f3af468b7ef", "shasum": "" }, "require": { "container-interop/container-interop": "^1.1", - "nikic/fast-route": "^0.6", + "nikic/fast-route": "^1.0", "php": ">=5.5.0", "pimple/pimple": "^3.0", "psr/http-message": "^1.0" }, + "provide": { + "psr/http-message-implementation": "1.0" + }, "require-dev": { "phpunit/phpunit": "^4.0", "squizlabs/php_codesniffer": "^2.5" @@ -413,36 +375,42 @@ } ], "description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs", - "homepage": "http://slimframework.com", + "homepage": "https://slimframework.com", "keywords": [ "api", "framework", "micro", "router" ], - "time": "2016-03-10 21:37:40" + "time": "2016-12-20T20:30:47+00:00" }, { "name": "symfony/yaml", - "version": "v3.0.4", + "version": "v3.2.1", "source": { "type": "git", "url": "https://github.com/symfony/yaml.git", - "reference": "0047c8366744a16de7516622c5b7355336afae96" + "reference": "a7095af4b97a0955f85c8989106c249fa649011f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/yaml/zipball/0047c8366744a16de7516622c5b7355336afae96", - "reference": "0047c8366744a16de7516622c5b7355336afae96", + "url": "https://api.github.com/repos/symfony/yaml/zipball/a7095af4b97a0955f85c8989106c249fa649011f", + "reference": "a7095af4b97a0955f85c8989106c249fa649011f", "shasum": "" }, "require": { "php": ">=5.5.9" }, + "require-dev": { + "symfony/console": "~2.8|~3.0" + }, + "suggest": { + "symfony/console": "For validating YAML files using the lint command" + }, "type": "library", "extra": { "branch-alias": { - "dev-master": "3.0-dev" + "dev-master": "3.2-dev" } }, "autoload": { @@ -469,7 +437,7 @@ ], "description": "Symfony Yaml Component", "homepage": "https://symfony.com", - "time": "2016-03-04 07:55:57" + "time": "2016-12-10T10:07:06+00:00" }, { "name": "zendframework/zendxml", @@ -514,7 +482,7 @@ "xml", "zf2" ], - "time": "2016-02-04 21:02:08" + "time": "2016-02-04T21:02:08+00:00" } ], "packages-dev": [], diff --git a/vendor/autoload.php b/vendor/autoload.php index b1be175..3974cf1 100644 --- a/vendor/autoload.php +++ b/vendor/autoload.php @@ -2,6 +2,6 @@ // autoload.php @generated by Composer -require_once __DIR__ . '/composer' . '/autoload_real.php'; +require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInitd1db2574a85c0ba6f142743249ba228f::getLoader(); diff --git a/vendor/bshaffer/oauth2-server-php/.gitignore b/vendor/bshaffer/oauth2-server-php/.gitignore deleted file mode 100644 index c43a667..0000000 --- a/vendor/bshaffer/oauth2-server-php/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -# Test Files # -test/config/test.sqlite -vendor -composer.lock -.idea diff --git a/vendor/bshaffer/oauth2-server-php/.travis.yml b/vendor/bshaffer/oauth2-server-php/.travis.yml deleted file mode 100644 index f297d3f..0000000 --- a/vendor/bshaffer/oauth2-server-php/.travis.yml +++ /dev/null @@ -1,25 +0,0 @@ -language: php -sudo: false -php: -- 5.3 -- 5.4 -- 5.5 -- 5.6 -- hhvm -env: - global: - - SKIP_MONGO_TESTS=1 - - secure: Bc5ZqvZ1YYpoPZNNuU2eCB8DS6vBYrAdfBtTenBs5NSxzb+Vjven4kWakbzaMvZjb/Ib7Uph7DGuOtJXpmxnvBXPLd707LZ89oFWN/yqQlZKCcm8iErvJCB5XL+/ONHj2iPdR242HJweMcat6bMCwbVWoNDidjtWMH0U2mYFy3M= - - secure: R3bXlymyFiY2k2jf7+fv/J8i34wtXTkmD4mCr5Ps/U+vn9axm2VtvR2Nj+r7LbRjn61gzFE/xIVjYft/wOyBOYwysrfriydrnRVS0owh6y+7EyOyQWbRX11vVQMf8o31QCQE5BY58V5AJZW3MjoOL0FVlTgySJiJvdw6Pv18v+E= -services: -- mongodb -- redis-server -- cassandra -before_script: -- psql -c 'create database oauth2_server_php;' -U postgres -- composer require predis/predis:dev-master -- composer require thobbs/phpcassa:dev-master -- composer require 'aws/aws-sdk-php:~2.8' -- composer require 'firebase/php-jwt:~2.2' -after_script: -- php test/cleanup.php diff --git a/vendor/bshaffer/oauth2-server-php/CHANGELOG.md b/vendor/bshaffer/oauth2-server-php/CHANGELOG.md deleted file mode 100644 index 48773d2..0000000 --- a/vendor/bshaffer/oauth2-server-php/CHANGELOG.md +++ /dev/null @@ -1,165 +0,0 @@ -CHANGELOG for 1.x -================= - -This changelog references the relevant changes (bug and security fixes) done -in 1.x minor versions. - -To see the files changed for a given bug, go to https://github.com/bshaffer/oauth2-server-php/issues/### where ### is the bug number -To get the diff between two versions, go to https://github.com/bshaffer/oauth2-server-php/compare/v1.0...v1.1 -To get the diff for a specific change, go to https://github.com/bshaffer/oauth2-server-php/commit/XXX where XXX is the change hash - -* 1.8.0 (2015-09-18) - - PR: https://github.com/bshaffer/oauth2-server-php/pull/643 - - * bug #594 - adds jti - * bug #598 - fixes lifetime configurations for JWTs - * bug #634 - fixes travis builds, upgrade to containers - * bug #586 - support for revoking tokens - * bug #636 - Adds FirebaseJWT bridge - * bug #639 - Mongo HHVM compatibility - -* 1.7.0 (2015-04-23) - - PR: https://github.com/bshaffer/oauth2-server-php/pull/572 - - * bug #500 - PDO fetch mode changed from FETCH_BOTH to FETCH_ASSOC - * bug #508 - Case insensitive for Bearer token header name ba716d4 - * bug #512 - validateRedirectUri is now public - * bug #530 - Add PublicKeyInterface, UserClaimsInterface to Cassandra Storage - * bug #505 - DynamoDB storage fixes - * bug #556 - adds "code id_token" return type to openid connect - * bug #563 - Include "issuer" config key for JwtAccessToken - * bug #564 - Fixes JWT vulnerability - * bug #571 - Added unset_refresh_token_after_use option - -* 1.6 (2015-01-16) - - PR: https://github.com/bshaffer/oauth2-server-php/pull/496 - - * bug 437 - renames CryptoToken to JwtAccessToken / use_crypto_tokens to use_jwt_access_tokens - * bug 447 - Adds a Couchbase storage implementation - * bug 460 - Rename JWT claims to match spec - * bug 470 - order does not matter for multi-valued response types - * bug 471 - Make validateAuthorizeRequest available for POST in addition to GET - * bug 475 - Adds JTI table definitiion - * bug 481 - better randomness for generating access tokens - * bug 480 - Use hash_equals() for signature verification (prevents remote timing attacks) - * bugs 489, 491, 498 - misc other fixes - -* 1.5 (2014-08-27) - - PR: https://github.com/bshaffer/oauth2-server-php/pull/446 - - * bug #399 - Add DynamoDB Support - * bug #404 - renamed error name for malformed/expired tokens - * bug #412 - Openid connect: fixes for claims with more than one scope / Add support for the prompt parameter ('consent' and 'none') - * bug #411 - fixes xml output - * bug #413 - fixes invalid format error - * bug #401 - fixes code standards / whitespace - * bug #354 - bundles PDO SQL with the library - * [BC] bug #397 - refresh tokens should not be encrypted - * bug #423 - makes "scope" optional for refresh token storage - -* 1.4 (2014-06-12) - - PR: https://github.com/bshaffer/oauth2-server-php/pull/392 - - * bug #189 Storage\PDO - allows DSN string in constructor - * bug #233 Bearer Tokens - allows token in request body for PUT requests - * bug #346 Fixes open_basedir warning - * bug #351 Adds OpenID Connect support - * bug #355 Adds php 5.6 and HHVM to travis.ci testing - * [BC] bug #358 Adds `getQuerystringIdentifier()` to the GrantType interface - * bug #363 Encryption\JWT - Allows for subclassing JWT Headers - * bug #349 Bearer Tokens - adds requestHasToken method for when access tokens are optional - * bug #301 Encryption\JWT - fixes urlSafeB64Encode(): ensures newlines are replaced as expected - * bug #323 ResourceController - client_id is no longer required to be returned when calling getAccessToken - * bug #367 Storage\PDO - adds Postgres support - * bug #368 Access Tokens - use mcrypt_create_iv or openssl_random_pseudo_bytes to create token string - * bug #376 Request - allows case insensitive headers - * bug #384 Storage\PDO - can pass in PDO options in constructor of PDO storage - * misc fixes #361, #292, #373, #374, #379, #396 -* 1.3 (2014-02-27) - - PR: https://github.com/bshaffer/oauth2-server-php/pull/325 - - * bug #311 adds cassandra storage - * bug #298 fixes response code for user credentials grant type - * bug #318 adds 'use_crypto_tokens' config to Server class for better DX - * [BC] bug #320 pass client_id to getDefaultScope - * bug #324 better feedback when running tests - * bug #335 adds support for non-expiring refresh tokens - * bug #333 fixes Pdo storage for getClientKey - * bug #336 fixes Redis storage for expireAuthorizationCode - -* 1.3 (2014-02-27) - - PR: https://github.com/bshaffer/oauth2-server-php/pull/325 - - * bug #311 adds cassandra storage - * bug #298 fixes response code for user credentials grant type - * bug #318 adds 'use_crypto_tokens' config to Server class for better DX - * bug #320 pass client_id to getDefaultScope - * bug #324 better feedback when running tests - * bug #335 adds support for non-expiring refresh tokens - * bug #333 fixes Pdo storage for getClientKey - * bug #336 fixes Redis storage for expireAuthorizationCode - -* 1.2 (2014-01-03) - - PR: https://github.com/bshaffer/oauth2-server-php/pull/288 - - * bug #285 changed response header from 200 to 401 when empty token received - * bug #286 adds documentation and links to spec for not including error messages when no token is supplied - * bug #280 ensures PHP warnings do not get thrown as a result of an invalid argument to $jwt->decode() - * bug #279 predis wrong number of arguments - * bug #277 Securing JS WebApp client secret w/ password grant type - -* 1.1 (2013-12-17) - - PR: https://github.com/bshaffer/oauth2-server-php/pull/276 - - * bug #278 adds refresh token configuration to Server class - * bug #274 Supplying a null client_id and client_secret grants API access - * bug #244 [MongoStorage] More detailed implementation info - * bug #268 Implement jti for JWT Bearer tokens to prevent replay attacks. - * bug #266 Removing unused argument to getAccessTokenData - * bug #247 Make Bearer token type consistent - * bug #253 Fixing CryptoToken refresh token lifetime - * bug #246 refactors public key logic to be more intuitive - * bug #245 adds support for JSON crypto tokens - * bug #230 Remove unused columns in oauth_clients - * bug #215 makes Redis Scope Storage obey the same paradigm as PDO - * bug #228 removes scope group - * bug #227 squelches open basedir restriction error - * bug #223 Updated docblocks for RefreshTokenInterface.php - * bug #224 Adds protected properties - * bug #217 Implement ScopeInterface for PDO, Redis - -* 1.0 (2013-08-12) - - * bug #203 Add redirect\_status_code config param for AuthorizeController - * bug #205 ensures unnecessary ? is not set when ** bug - * bug #204 Fixed call to LogicException - * bug #202 Add explode to checkRestrictedGrant in PDO Storage - * bug #197 adds support for 'false' default scope ** bug - * bug #192 reference errors and adds tests - * bug #194 makes some appropriate properties ** bug - * bug #191 passes config to HttpBasic - * bug #190 validates client credentials before ** bug - * bug #171 Fix wrong redirect following authorization step - * bug #187 client_id is now passed to getDefaultScope(). - * bug #176 Require refresh_token in getRefreshToken response - * bug #174 make user\_id not required for refresh_token grant - * bug #173 Duplication in JwtBearer Grant - * bug #168 user\_id not required for authorization_code grant - * bug #133 hardens default security for user object - * bug #163 allows redirect\_uri on authorization_code to be NULL in docs example - * bug #162 adds getToken on ResourceController for convenience - * bug #161 fixes fatal error - * bug #163 Invalid redirect_uri handling - * bug #156 user\_id in OAuth2\_Storage_AuthorizationCodeInterface::getAuthorizationCode() response - * bug #157 Fix for extending access and refresh tokens - * bug #154 ResponseInterface: getParameter method is used in the library but not defined in the interface - * bug #148 Add more detail to examples in Readme.md diff --git a/vendor/bshaffer/oauth2-server-php/LICENSE b/vendor/bshaffer/oauth2-server-php/LICENSE deleted file mode 100644 index d7ece84..0000000 --- a/vendor/bshaffer/oauth2-server-php/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License - -Copyright (c) 2014 Brent Shaffer - -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. diff --git a/vendor/bshaffer/oauth2-server-php/README.md b/vendor/bshaffer/oauth2-server-php/README.md deleted file mode 100644 index 4ceda6c..0000000 --- a/vendor/bshaffer/oauth2-server-php/README.md +++ /dev/null @@ -1,8 +0,0 @@ -oauth2-server-php -================= - -[![Build Status](https://travis-ci.org/bshaffer/oauth2-server-php.svg?branch=develop)](https://travis-ci.org/bshaffer/oauth2-server-php) - -[![Total Downloads](https://poser.pugx.org/bshaffer/oauth2-server-php/downloads.png)](https://packagist.org/packages/bshaffer/oauth2-server-php) - -View the [complete documentation](http://bshaffer.github.io/oauth2-server-php-docs/) \ No newline at end of file diff --git a/vendor/bshaffer/oauth2-server-php/composer.json b/vendor/bshaffer/oauth2-server-php/composer.json deleted file mode 100644 index 853c041..0000000 --- a/vendor/bshaffer/oauth2-server-php/composer.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "bshaffer/oauth2-server-php", - "description":"OAuth2 Server for PHP", - "keywords":["oauth","oauth2","auth"], - "type":"library", - "license":"MIT", - "authors":[ - { - "name":"Brent Shaffer", - "email": "bshafs@gmail.com", - "homepage":"http://brentertainment.com" - } - ], - "homepage": "http://github.com/bshaffer/oauth2-server-php", - "require":{ - "php":">=5.3.9" - }, - "autoload": { - "psr-0": { "OAuth2": "src/" } - }, - "suggest": { - "predis/predis": "Required to use the Redis storage engine", - "thobbs/phpcassa": "Required to use the Cassandra storage engine", - "aws/aws-sdk-php": "~2.8 is required to use the DynamoDB storage engine", - "firebase/php-jwt": "~2.2 is required to use JWT features" - } -} diff --git a/vendor/bshaffer/oauth2-server-php/phpunit.xml b/vendor/bshaffer/oauth2-server-php/phpunit.xml deleted file mode 100644 index e36403f..0000000 --- a/vendor/bshaffer/oauth2-server-php/phpunit.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - ./test/OAuth2/ - - - - - - ./src/OAuth2/ - - - diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Autoloader.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Autoloader.php deleted file mode 100644 index ecfb6ba..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Autoloader.php +++ /dev/null @@ -1,48 +0,0 @@ - - * @license MIT License - */ -class Autoloader -{ - private $dir; - - public function __construct($dir = null) - { - if (is_null($dir)) { - $dir = dirname(__FILE__).'/..'; - } - $this->dir = $dir; - } - /** - * Registers OAuth2\Autoloader as an SPL autoloader. - */ - public static function register($dir = null) - { - ini_set('unserialize_callback_func', 'spl_autoload_call'); - spl_autoload_register(array(new self($dir), 'autoload')); - } - - /** - * Handles autoloading of classes. - * - * @param string $class A class name. - * - * @return boolean Returns true if the class has been loaded - */ - public function autoload($class) - { - if (0 !== strpos($class, 'OAuth2')) { - return; - } - - if (file_exists($file = $this->dir.'/'.str_replace('\\', '/', $class).'.php')) { - require $file; - } - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ClientAssertionType/ClientAssertionTypeInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/ClientAssertionType/ClientAssertionTypeInterface.php deleted file mode 100644 index 29c7171..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ClientAssertionType/ClientAssertionTypeInterface.php +++ /dev/null @@ -1,15 +0,0 @@ - - */ -class HttpBasic implements ClientAssertionTypeInterface -{ - private $clientData; - - protected $storage; - protected $config; - - /** - * @param OAuth2\Storage\ClientCredentialsInterface $clientStorage REQUIRED Storage class for retrieving client credentials information - * @param array $config OPTIONAL Configuration options for the server - * - * $config = array( - * 'allow_credentials_in_request_body' => true, // whether to look for credentials in the POST body in addition to the Authorize HTTP Header - * 'allow_public_clients' => true // if true, "public clients" (clients without a secret) may be authenticated - * ); - * - */ - public function __construct(ClientCredentialsInterface $storage, array $config = array()) - { - $this->storage = $storage; - $this->config = array_merge(array( - 'allow_credentials_in_request_body' => true, - 'allow_public_clients' => true, - ), $config); - } - - public function validateRequest(RequestInterface $request, ResponseInterface $response) - { - if (!$clientData = $this->getClientCredentials($request, $response)) { - return false; - } - - if (!isset($clientData['client_id'])) { - throw new \LogicException('the clientData array must have "client_id" set'); - } - - if (!isset($clientData['client_secret']) || $clientData['client_secret'] == '') { - if (!$this->config['allow_public_clients']) { - $response->setError(400, 'invalid_client', 'client credentials are required'); - - return false; - } - - if (!$this->storage->isPublicClient($clientData['client_id'])) { - $response->setError(400, 'invalid_client', 'This client is invalid or must authenticate using a client secret'); - - return false; - } - } elseif ($this->storage->checkClientCredentials($clientData['client_id'], $clientData['client_secret']) === false) { - $response->setError(400, 'invalid_client', 'The client credentials are invalid'); - - return false; - } - - $this->clientData = $clientData; - - return true; - } - - public function getClientId() - { - return $this->clientData['client_id']; - } - - /** - * Internal function used to get the client credentials from HTTP basic - * auth or POST data. - * - * According to the spec (draft 20), the client_id can be provided in - * the Basic Authorization header (recommended) or via GET/POST. - * - * @return - * A list containing the client identifier and password, for example - * @code - * return array( - * "client_id" => CLIENT_ID, // REQUIRED the client id - * "client_secret" => CLIENT_SECRET, // OPTIONAL the client secret (may be omitted for public clients) - * ); - * @endcode - * - * @see http://tools.ietf.org/html/rfc6749#section-2.3.1 - * - * @ingroup oauth2_section_2 - */ - public function getClientCredentials(RequestInterface $request, ResponseInterface $response = null) - { - if (!is_null($request->headers('PHP_AUTH_USER')) && !is_null($request->headers('PHP_AUTH_PW'))) { - return array('client_id' => $request->headers('PHP_AUTH_USER'), 'client_secret' => $request->headers('PHP_AUTH_PW')); - } - - if ($this->config['allow_credentials_in_request_body']) { - // Using POST for HttpBasic authorization is not recommended, but is supported by specification - if (!is_null($request->request('client_id'))) { - /** - * client_secret can be null if the client's password is an empty string - * @see http://tools.ietf.org/html/rfc6749#section-2.3.1 - */ - - return array('client_id' => $request->request('client_id'), 'client_secret' => $request->request('client_secret')); - } - } - - if ($response) { - $message = $this->config['allow_credentials_in_request_body'] ? ' or body' : ''; - $response->setError(400, 'invalid_client', 'Client credentials were not found in the headers'.$message); - } - - return null; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/AuthorizeController.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/AuthorizeController.php deleted file mode 100644 index 91c275c..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/AuthorizeController.php +++ /dev/null @@ -1,383 +0,0 @@ - - * $config = array( - * 'allow_implicit' => false, // if the controller should allow the "implicit" grant type - * 'enforce_state' => true // if the controller should require the "state" parameter - * 'require_exact_redirect_uri' => true, // if the controller should require an exact match on the "redirect_uri" parameter - * 'redirect_status_code' => 302, // HTTP status code to use for redirect responses - * ); - * - * @param OAuth2\ScopeInterface $scopeUtil OPTIONAL Instance of OAuth2\ScopeInterface to validate the requested scope - */ - public function __construct(ClientInterface $clientStorage, array $responseTypes = array(), array $config = array(), ScopeInterface $scopeUtil = null) - { - $this->clientStorage = $clientStorage; - $this->responseTypes = $responseTypes; - $this->config = array_merge(array( - 'allow_implicit' => false, - 'enforce_state' => true, - 'require_exact_redirect_uri' => true, - 'redirect_status_code' => 302, - ), $config); - - if (is_null($scopeUtil)) { - $scopeUtil = new Scope(); - } - $this->scopeUtil = $scopeUtil; - } - - public function handleAuthorizeRequest(RequestInterface $request, ResponseInterface $response, $is_authorized, $user_id = null) - { - if (!is_bool($is_authorized)) { - throw new \InvalidArgumentException('Argument "is_authorized" must be a boolean. This method must know if the user has granted access to the client.'); - } - - // We repeat this, because we need to re-validate. The request could be POSTed - // by a 3rd-party (because we are not internally enforcing NONCEs, etc) - if (!$this->validateAuthorizeRequest($request, $response)) { - return; - } - - // If no redirect_uri is passed in the request, use client's registered one - if (empty($this->redirect_uri)) { - $clientData = $this->clientStorage->getClientDetails($this->client_id); - $registered_redirect_uri = $clientData['redirect_uri']; - } - - // the user declined access to the client's application - if ($is_authorized === false) { - $redirect_uri = $this->redirect_uri ?: $registered_redirect_uri; - $this->setNotAuthorizedResponse($request, $response, $redirect_uri, $user_id); - - return; - } - - // build the parameters to set in the redirect URI - if (!$params = $this->buildAuthorizeParameters($request, $response, $user_id)) { - return; - } - - $authResult = $this->responseTypes[$this->response_type]->getAuthorizeResponse($params, $user_id); - - list($redirect_uri, $uri_params) = $authResult; - - if (empty($redirect_uri) && !empty($registered_redirect_uri)) { - $redirect_uri = $registered_redirect_uri; - } - - $uri = $this->buildUri($redirect_uri, $uri_params); - - // return redirect response - $response->setRedirect($this->config['redirect_status_code'], $uri); - } - - protected function setNotAuthorizedResponse(RequestInterface $request, ResponseInterface $response, $redirect_uri, $user_id = null) - { - $error = 'access_denied'; - $error_message = 'The user denied access to your application'; - $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $this->state, $error, $error_message); - } - - /* - * We have made this protected so this class can be extended to add/modify - * these parameters - */ - protected function buildAuthorizeParameters($request, $response, $user_id) - { - // @TODO: we should be explicit with this in the future - $params = array( - 'scope' => $this->scope, - 'state' => $this->state, - 'client_id' => $this->client_id, - 'redirect_uri' => $this->redirect_uri, - 'response_type' => $this->response_type, - ); - - return $params; - } - - public function validateAuthorizeRequest(RequestInterface $request, ResponseInterface $response) - { - // Make sure a valid client id was supplied (we can not redirect because we were unable to verify the URI) - if (!$client_id = $request->query('client_id', $request->request('client_id'))) { - // We don't have a good URI to use - $response->setError(400, 'invalid_client', "No client id supplied"); - - return false; - } - - // Get client details - if (!$clientData = $this->clientStorage->getClientDetails($client_id)) { - $response->setError(400, 'invalid_client', 'The client id supplied is invalid'); - - return false; - } - - $registered_redirect_uri = isset($clientData['redirect_uri']) ? $clientData['redirect_uri'] : ''; - - // Make sure a valid redirect_uri was supplied. If specified, it must match the clientData URI. - // @see http://tools.ietf.org/html/rfc6749#section-3.1.2 - // @see http://tools.ietf.org/html/rfc6749#section-4.1.2.1 - // @see http://tools.ietf.org/html/rfc6749#section-4.2.2.1 - if ($supplied_redirect_uri = $request->query('redirect_uri', $request->request('redirect_uri'))) { - // validate there is no fragment supplied - $parts = parse_url($supplied_redirect_uri); - if (isset($parts['fragment']) && $parts['fragment']) { - $response->setError(400, 'invalid_uri', 'The redirect URI must not contain a fragment'); - - return false; - } - - // validate against the registered redirect uri(s) if available - if ($registered_redirect_uri && !$this->validateRedirectUri($supplied_redirect_uri, $registered_redirect_uri)) { - $response->setError(400, 'redirect_uri_mismatch', 'The redirect URI provided is missing or does not match', '#section-3.1.2'); - - return false; - } - $redirect_uri = $supplied_redirect_uri; - } else { - // use the registered redirect_uri if none has been supplied, if possible - if (!$registered_redirect_uri) { - $response->setError(400, 'invalid_uri', 'No redirect URI was supplied or stored'); - - return false; - } - - if (count(explode(' ', $registered_redirect_uri)) > 1) { - $response->setError(400, 'invalid_uri', 'A redirect URI must be supplied when multiple redirect URIs are registered', '#section-3.1.2.3'); - - return false; - } - $redirect_uri = $registered_redirect_uri; - } - - // Select the redirect URI - $response_type = $request->query('response_type', $request->request('response_type')); - - // for multiple-valued response types - make them alphabetical - if (false !== strpos($response_type, ' ')) { - $types = explode(' ', $response_type); - sort($types); - $response_type = ltrim(implode(' ', $types)); - } - - $state = $request->query('state', $request->request('state')); - - // type and client_id are required - if (!$response_type || !in_array($response_type, $this->getValidResponseTypes())) { - $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'invalid_request', 'Invalid or missing response type', null); - - return false; - } - - if ($response_type == self::RESPONSE_TYPE_AUTHORIZATION_CODE) { - if (!isset($this->responseTypes['code'])) { - $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unsupported_response_type', 'authorization code grant type not supported', null); - - return false; - } - if (!$this->clientStorage->checkRestrictedGrantType($client_id, 'authorization_code')) { - $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unauthorized_client', 'The grant type is unauthorized for this client_id', null); - - return false; - } - if ($this->responseTypes['code']->enforceRedirect() && !$redirect_uri) { - $response->setError(400, 'redirect_uri_mismatch', 'The redirect URI is mandatory and was not supplied'); - - return false; - } - } else { - if (!$this->config['allow_implicit']) { - $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unsupported_response_type', 'implicit grant type not supported', null); - - return false; - } - if (!$this->clientStorage->checkRestrictedGrantType($client_id, 'implicit')) { - $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'unauthorized_client', 'The grant type is unauthorized for this client_id', null); - - return false; - } - } - - // validate requested scope if it exists - $requestedScope = $this->scopeUtil->getScopeFromRequest($request); - - if ($requestedScope) { - // restrict scope by client specific scope if applicable, - // otherwise verify the scope exists - $clientScope = $this->clientStorage->getClientScope($client_id); - if ((is_null($clientScope) && !$this->scopeUtil->scopeExists($requestedScope)) - || ($clientScope && !$this->scopeUtil->checkScope($requestedScope, $clientScope))) { - $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'invalid_scope', 'An unsupported scope was requested', null); - - return false; - } - } else { - // use a globally-defined default scope - $defaultScope = $this->scopeUtil->getDefaultScope($client_id); - - if (false === $defaultScope) { - $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $state, 'invalid_client', 'This application requires you specify a scope parameter', null); - - return false; - } - - $requestedScope = $defaultScope; - } - - // Validate state parameter exists (if configured to enforce this) - if ($this->config['enforce_state'] && !$state) { - $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, null, 'invalid_request', 'The state parameter is required'); - - return false; - } - - // save the input data and return true - $this->scope = $requestedScope; - $this->state = $state; - $this->client_id = $client_id; - // Only save the SUPPLIED redirect URI (@see http://tools.ietf.org/html/rfc6749#section-4.1.3) - $this->redirect_uri = $supplied_redirect_uri; - $this->response_type = $response_type; - - return true; - } - - /** - * Build the absolute URI based on supplied URI and parameters. - * - * @param $uri An absolute URI. - * @param $params Parameters to be append as GET. - * - * @return - * An absolute URI with supplied parameters. - * - * @ingroup oauth2_section_4 - */ - private function buildUri($uri, $params) - { - $parse_url = parse_url($uri); - - // Add our params to the parsed uri - foreach ($params as $k => $v) { - if (isset($parse_url[$k])) { - $parse_url[$k] .= "&" . http_build_query($v, '', '&'); - } else { - $parse_url[$k] = http_build_query($v, '', '&'); - } - } - - // Put humpty dumpty back together - return - ((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "") - . ((isset($parse_url["user"])) ? $parse_url["user"] - . ((isset($parse_url["pass"])) ? ":" . $parse_url["pass"] : "") . "@" : "") - . ((isset($parse_url["host"])) ? $parse_url["host"] : "") - . ((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "") - . ((isset($parse_url["path"])) ? $parse_url["path"] : "") - . ((isset($parse_url["query"]) && !empty($parse_url['query'])) ? "?" . $parse_url["query"] : "") - . ((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : "") - ; - } - - protected function getValidResponseTypes() - { - return array( - self::RESPONSE_TYPE_ACCESS_TOKEN, - self::RESPONSE_TYPE_AUTHORIZATION_CODE, - ); - } - - /** - * Internal method for validating redirect URI supplied - * - * @param string $inputUri The submitted URI to be validated - * @param string $registeredUriString The allowed URI(s) to validate against. Can be a space-delimited string of URIs to - * allow for multiple URIs - * - * @see http://tools.ietf.org/html/rfc6749#section-3.1.2 - */ - protected function validateRedirectUri($inputUri, $registeredUriString) - { - if (!$inputUri || !$registeredUriString) { - return false; // if either one is missing, assume INVALID - } - - $registered_uris = preg_split('/\s+/', $registeredUriString); - foreach ($registered_uris as $registered_uri) { - if ($this->config['require_exact_redirect_uri']) { - // the input uri is validated against the registered uri using exact match - if (strcmp($inputUri, $registered_uri) === 0) { - return true; - } - } else { - // the input uri is validated against the registered uri using case-insensitive match of the initial string - // i.e. additional query parameters may be applied - if (strcasecmp(substr($inputUri, 0, strlen($registered_uri)), $registered_uri) === 0) { - return true; - } - } - } - - return false; - } - - /** - * Convenience methods to access the parameters derived from the validated request - */ - - public function getScope() - { - return $this->scope; - } - - public function getState() - { - return $this->state; - } - - public function getClientId() - { - return $this->client_id; - } - - public function getRedirectUri() - { - return $this->redirect_uri; - } - - public function getResponseType() - { - return $this->response_type; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/AuthorizeControllerInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/AuthorizeControllerInterface.php deleted file mode 100644 index fa07ae8..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/AuthorizeControllerInterface.php +++ /dev/null @@ -1,43 +0,0 @@ - $user_id = $this->somehowDetermineUserId(); - * > $is_authorized = $this->somehowDetermineUserAuthorization(); - * > $response = new OAuth2\Response(); - * > $authorizeController->handleAuthorizeRequest( - * > OAuth2\Request::createFromGlobals(), - * > $response, - * > $is_authorized, - * > $user_id); - * > $response->send(); - * - */ -interface AuthorizeControllerInterface -{ - /** - * List of possible authentication response types. - * The "authorization_code" mechanism exclusively supports 'code' - * and the "implicit" mechanism exclusively supports 'token'. - * - * @var string - * @see http://tools.ietf.org/html/rfc6749#section-4.1.1 - * @see http://tools.ietf.org/html/rfc6749#section-4.2.1 - */ - const RESPONSE_TYPE_AUTHORIZATION_CODE = 'code'; - const RESPONSE_TYPE_ACCESS_TOKEN = 'token'; - - public function handleAuthorizeRequest(RequestInterface $request, ResponseInterface $response, $is_authorized, $user_id = null); - - public function validateAuthorizeRequest(RequestInterface $request, ResponseInterface $response); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/ResourceController.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/ResourceController.php deleted file mode 100644 index e858818..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/ResourceController.php +++ /dev/null @@ -1,111 +0,0 @@ -tokenType = $tokenType; - $this->tokenStorage = $tokenStorage; - - $this->config = array_merge(array( - 'www_realm' => 'Service', - ), $config); - - if (is_null($scopeUtil)) { - $scopeUtil = new Scope(); - } - $this->scopeUtil = $scopeUtil; - } - - public function verifyResourceRequest(RequestInterface $request, ResponseInterface $response, $scope = null) - { - $token = $this->getAccessTokenData($request, $response); - - // Check if we have token data - if (is_null($token)) { - return false; - } - - /** - * Check scope, if provided - * If token doesn't have a scope, it's null/empty, or it's insufficient, then throw 403 - * @see http://tools.ietf.org/html/rfc6750#section-3.1 - */ - if ($scope && (!isset($token["scope"]) || !$token["scope"] || !$this->scopeUtil->checkScope($scope, $token["scope"]))) { - $response->setError(403, 'insufficient_scope', 'The request requires higher privileges than provided by the access token'); - $response->addHttpHeaders(array( - 'WWW-Authenticate' => sprintf('%s realm="%s", scope="%s", error="%s", error_description="%s"', - $this->tokenType->getTokenType(), - $this->config['www_realm'], - $scope, - $response->getParameter('error'), - $response->getParameter('error_description') - ) - )); - - return false; - } - - // allow retrieval of the token - $this->token = $token; - - return (bool) $token; - } - - public function getAccessTokenData(RequestInterface $request, ResponseInterface $response) - { - // Get the token parameter - if ($token_param = $this->tokenType->getAccessTokenParameter($request, $response)) { - // Get the stored token data (from the implementing subclass) - // Check we have a well formed token - // Check token expiration (expires is a mandatory paramter) - if (!$token = $this->tokenStorage->getAccessToken($token_param)) { - $response->setError(401, 'invalid_token', 'The access token provided is invalid'); - } elseif (!isset($token["expires"]) || !isset($token["client_id"])) { - $response->setError(401, 'malformed_token', 'Malformed token (missing "expires")'); - } elseif (time() > $token["expires"]) { - $response->setError(401, 'expired_token', 'The access token provided has expired'); - } else { - return $token; - } - } - - $authHeader = sprintf('%s realm="%s"', $this->tokenType->getTokenType(), $this->config['www_realm']); - - if ($error = $response->getParameter('error')) { - $authHeader = sprintf('%s, error="%s"', $authHeader, $error); - if ($error_description = $response->getParameter('error_description')) { - $authHeader = sprintf('%s, error_description="%s"', $authHeader, $error_description); - } - } - - $response->addHttpHeaders(array('WWW-Authenticate' => $authHeader)); - - return null; - } - - // convenience method to allow retrieval of the token - public function getToken() - { - return $this->token; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/ResourceControllerInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/ResourceControllerInterface.php deleted file mode 100644 index 6114219..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/ResourceControllerInterface.php +++ /dev/null @@ -1,26 +0,0 @@ - if (!$resourceController->verifyResourceRequest(OAuth2\Request::createFromGlobals(), $response = new OAuth2\Response())) { - * > $response->send(); // authorization failed - * > die(); - * > } - * > return json_encode($resource); // valid token! Send the stuff! - * - */ -interface ResourceControllerInterface -{ - public function verifyResourceRequest(RequestInterface $request, ResponseInterface $response, $scope = null); - - public function getAccessTokenData(RequestInterface $request, ResponseInterface $response); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/TokenController.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/TokenController.php deleted file mode 100644 index 2e0750f..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/TokenController.php +++ /dev/null @@ -1,274 +0,0 @@ -clientAssertionType = $clientAssertionType; - $this->accessToken = $accessToken; - $this->clientStorage = $clientStorage; - foreach ($grantTypes as $grantType) { - $this->addGrantType($grantType); - } - - if (is_null($scopeUtil)) { - $scopeUtil = new Scope(); - } - $this->scopeUtil = $scopeUtil; - } - - public function handleTokenRequest(RequestInterface $request, ResponseInterface $response) - { - if ($token = $this->grantAccessToken($request, $response)) { - // @see http://tools.ietf.org/html/rfc6749#section-5.1 - // server MUST disable caching in headers when tokens are involved - $response->setStatusCode(200); - $response->addParameters($token); - $response->addHttpHeaders(array('Cache-Control' => 'no-store', 'Pragma' => 'no-cache')); - } - } - - /** - * Grant or deny a requested access token. - * This would be called from the "/token" endpoint as defined in the spec. - * You can call your endpoint whatever you want. - * - * @param $request - RequestInterface - * Request object to grant access token - * - * @throws InvalidArgumentException - * @throws LogicException - * - * @see http://tools.ietf.org/html/rfc6749#section-4 - * @see http://tools.ietf.org/html/rfc6749#section-10.6 - * @see http://tools.ietf.org/html/rfc6749#section-4.1.3 - * - * @ingroup oauth2_section_4 - */ - public function grantAccessToken(RequestInterface $request, ResponseInterface $response) - { - if (strtolower($request->server('REQUEST_METHOD')) != 'post') { - $response->setError(405, 'invalid_request', 'The request method must be POST when requesting an access token', '#section-3.2'); - $response->addHttpHeaders(array('Allow' => 'POST')); - - return null; - } - - /** - * Determine grant type from request - * and validate the request for that grant type - */ - if (!$grantTypeIdentifier = $request->request('grant_type')) { - $response->setError(400, 'invalid_request', 'The grant type was not specified in the request'); - - return null; - } - - if (!isset($this->grantTypes[$grantTypeIdentifier])) { - /* TODO: If this is an OAuth2 supported grant type that we have chosen not to implement, throw a 501 Not Implemented instead */ - $response->setError(400, 'unsupported_grant_type', sprintf('Grant type "%s" not supported', $grantTypeIdentifier)); - - return null; - } - - $grantType = $this->grantTypes[$grantTypeIdentifier]; - - /** - * Retrieve the client information from the request - * ClientAssertionTypes allow for grant types which also assert the client data - * in which case ClientAssertion is handled in the validateRequest method - * - * @see OAuth2\GrantType\JWTBearer - * @see OAuth2\GrantType\ClientCredentials - */ - if (!$grantType instanceof ClientAssertionTypeInterface) { - if (!$this->clientAssertionType->validateRequest($request, $response)) { - return null; - } - $clientId = $this->clientAssertionType->getClientId(); - } - - /** - * Retrieve the grant type information from the request - * The GrantTypeInterface object handles all validation - * If the object is an instance of ClientAssertionTypeInterface, - * That logic is handled here as well - */ - if (!$grantType->validateRequest($request, $response)) { - return null; - } - - if ($grantType instanceof ClientAssertionTypeInterface) { - $clientId = $grantType->getClientId(); - } else { - // validate the Client ID (if applicable) - if (!is_null($storedClientId = $grantType->getClientId()) && $storedClientId != $clientId) { - $response->setError(400, 'invalid_grant', sprintf('%s doesn\'t exist or is invalid for the client', $grantTypeIdentifier)); - - return null; - } - } - - /** - * Validate the client can use the requested grant type - */ - if (!$this->clientStorage->checkRestrictedGrantType($clientId, $grantTypeIdentifier)) { - $response->setError(400, 'unauthorized_client', 'The grant type is unauthorized for this client_id'); - - return false; - } - - /** - * Validate the scope of the token - * - * requestedScope - the scope specified in the token request - * availableScope - the scope associated with the grant type - * ex: in the case of the "Authorization Code" grant type, - * the scope is specified in the authorize request - * - * @see http://tools.ietf.org/html/rfc6749#section-3.3 - */ - - $requestedScope = $this->scopeUtil->getScopeFromRequest($request); - $availableScope = $grantType->getScope(); - - if ($requestedScope) { - // validate the requested scope - if ($availableScope) { - if (!$this->scopeUtil->checkScope($requestedScope, $availableScope)) { - $response->setError(400, 'invalid_scope', 'The scope requested is invalid for this request'); - - return null; - } - } else { - // validate the client has access to this scope - if ($clientScope = $this->clientStorage->getClientScope($clientId)) { - if (!$this->scopeUtil->checkScope($requestedScope, $clientScope)) { - $response->setError(400, 'invalid_scope', 'The scope requested is invalid for this client'); - - return false; - } - } elseif (!$this->scopeUtil->scopeExists($requestedScope)) { - $response->setError(400, 'invalid_scope', 'An unsupported scope was requested'); - - return null; - } - } - } elseif ($availableScope) { - // use the scope associated with this grant type - $requestedScope = $availableScope; - } else { - // use a globally-defined default scope - $defaultScope = $this->scopeUtil->getDefaultScope($clientId); - - // "false" means default scopes are not allowed - if (false === $defaultScope) { - $response->setError(400, 'invalid_scope', 'This application requires you specify a scope parameter'); - - return null; - } - - $requestedScope = $defaultScope; - } - - return $grantType->createAccessToken($this->accessToken, $clientId, $grantType->getUserId(), $requestedScope); - } - - /** - * addGrantType - * - * @param grantType - OAuth2\GrantTypeInterface - * the grant type to add for the specified identifier - * @param identifier - string - * a string passed in as "grant_type" in the response that will call this grantType - */ - public function addGrantType(GrantTypeInterface $grantType, $identifier = null) - { - if (is_null($identifier) || is_numeric($identifier)) { - $identifier = $grantType->getQuerystringIdentifier(); - } - - $this->grantTypes[$identifier] = $grantType; - } - - public function handleRevokeRequest(RequestInterface $request, ResponseInterface $response) - { - if ($this->revokeToken($request, $response)) { - $response->setStatusCode(200); - $response->addParameters(array('revoked' => true)); - } - } - - /** - * Revoke a refresh or access token. Returns true on success and when tokens are invalid - * - * Note: invalid tokens do not cause an error response since the client - * cannot handle such an error in a reasonable way. Moreover, the - * purpose of the revocation request, invalidating the particular token, - * is already achieved. - * - * @param RequestInterface $request - * @param ResponseInterface $response - * @return bool|null - */ - public function revokeToken(RequestInterface $request, ResponseInterface $response) - { - if (strtolower($request->server('REQUEST_METHOD')) != 'post') { - $response->setError(405, 'invalid_request', 'The request method must be POST when revoking an access token', '#section-3.2'); - $response->addHttpHeaders(array('Allow' => 'POST')); - - return null; - } - - $token_type_hint = $request->request('token_type_hint'); - if (!in_array($token_type_hint, array(null, 'access_token', 'refresh_token'), true)) { - $response->setError(400, 'invalid_request', 'Token type hint must be either \'access_token\' or \'refresh_token\''); - - return null; - } - - $token = $request->request('token'); - if ($token === null) { - $response->setError(400, 'invalid_request', 'Missing token parameter to revoke'); - - return null; - } - - // @todo remove this check for v2.0 - if (!method_exists($this->accessToken, 'revokeToken')) { - $class = get_class($this->accessToken); - throw new \RuntimeException("AccessToken {$class} does not implement required revokeToken method"); - } - - $this->accessToken->revokeToken($token, $token_type_hint); - - return true; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/TokenControllerInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/TokenControllerInterface.php deleted file mode 100644 index 72d7257..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Controller/TokenControllerInterface.php +++ /dev/null @@ -1,32 +0,0 @@ - $tokenController->handleTokenRequest(OAuth2\Request::createFromGlobals(), $response = new OAuth2\Response()); - * > $response->send(); - * - */ -interface TokenControllerInterface -{ - /** - * handleTokenRequest - * - * @param $request - * OAuth2\RequestInterface - The current http request - * @param $response - * OAuth2\ResponseInterface - An instance of OAuth2\ResponseInterface to contain the response data - * - */ - public function handleTokenRequest(RequestInterface $request, ResponseInterface $response); - - public function grantAccessToken(RequestInterface $request, ResponseInterface $response); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Encryption/EncryptionInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Encryption/EncryptionInterface.php deleted file mode 100644 index 2d336c6..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Encryption/EncryptionInterface.php +++ /dev/null @@ -1,11 +0,0 @@ - - */ -class FirebaseJwt implements EncryptionInterface -{ - public function __construct() - { - if (!class_exists('\JWT')) { - throw new \ErrorException('firebase/php-jwt must be installed to use this feature. You can do this by running "composer require firebase/php-jwt"'); - } - } - - public function encode($payload, $key, $alg = 'HS256', $keyId = null) - { - return \JWT::encode($payload, $key, $alg, $keyId); - } - - public function decode($jwt, $key = null, $allowedAlgorithms = null) - { - try { - - //Maintain BC: Do not verify if no algorithms are passed in. - if (!$allowedAlgorithms) { - $key = null; - } - - return (array)\JWT::decode($jwt, $key, $allowedAlgorithms); - } catch (\Exception $e) { - return false; - } - } - - public function urlSafeB64Encode($data) - { - return \JWT::urlsafeB64Encode($data); - } - - public function urlSafeB64Decode($b64) - { - return \JWT::urlsafeB64Decode($b64); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Encryption/Jwt.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Encryption/Jwt.php deleted file mode 100644 index ee576e6..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Encryption/Jwt.php +++ /dev/null @@ -1,173 +0,0 @@ -generateJwtHeader($payload, $algo); - - $segments = array( - $this->urlSafeB64Encode(json_encode($header)), - $this->urlSafeB64Encode(json_encode($payload)) - ); - - $signing_input = implode('.', $segments); - - $signature = $this->sign($signing_input, $key, $algo); - $segments[] = $this->urlsafeB64Encode($signature); - - return implode('.', $segments); - } - - public function decode($jwt, $key = null, $allowedAlgorithms = true) - { - if (!strpos($jwt, '.')) { - return false; - } - - $tks = explode('.', $jwt); - - if (count($tks) != 3) { - return false; - } - - list($headb64, $payloadb64, $cryptob64) = $tks; - - if (null === ($header = json_decode($this->urlSafeB64Decode($headb64), true))) { - return false; - } - - if (null === $payload = json_decode($this->urlSafeB64Decode($payloadb64), true)) { - return false; - } - - $sig = $this->urlSafeB64Decode($cryptob64); - - if ((bool) $allowedAlgorithms) { - if (!isset($header['alg'])) { - return false; - } - - // check if bool arg supplied here to maintain BC - if (is_array($allowedAlgorithms) && !in_array($header['alg'], $allowedAlgorithms)) { - return false; - } - - if (!$this->verifySignature($sig, "$headb64.$payloadb64", $key, $header['alg'])) { - return false; - } - } - - return $payload; - } - - private function verifySignature($signature, $input, $key, $algo = 'HS256') - { - // use constants when possible, for HipHop support - switch ($algo) { - case'HS256': - case'HS384': - case'HS512': - return $this->hash_equals( - $this->sign($input, $key, $algo), - $signature - ); - - case 'RS256': - return openssl_verify($input, $signature, $key, defined('OPENSSL_ALGO_SHA256') ? OPENSSL_ALGO_SHA256 : 'sha256') === 1; - - case 'RS384': - return @openssl_verify($input, $signature, $key, defined('OPENSSL_ALGO_SHA384') ? OPENSSL_ALGO_SHA384 : 'sha384') === 1; - - case 'RS512': - return @openssl_verify($input, $signature, $key, defined('OPENSSL_ALGO_SHA512') ? OPENSSL_ALGO_SHA512 : 'sha512') === 1; - - default: - throw new \InvalidArgumentException("Unsupported or invalid signing algorithm."); - } - } - - private function sign($input, $key, $algo = 'HS256') - { - switch ($algo) { - case 'HS256': - return hash_hmac('sha256', $input, $key, true); - - case 'HS384': - return hash_hmac('sha384', $input, $key, true); - - case 'HS512': - return hash_hmac('sha512', $input, $key, true); - - case 'RS256': - return $this->generateRSASignature($input, $key, defined('OPENSSL_ALGO_SHA256') ? OPENSSL_ALGO_SHA256 : 'sha256'); - - case 'RS384': - return $this->generateRSASignature($input, $key, defined('OPENSSL_ALGO_SHA384') ? OPENSSL_ALGO_SHA384 : 'sha384'); - - case 'RS512': - return $this->generateRSASignature($input, $key, defined('OPENSSL_ALGO_SHA512') ? OPENSSL_ALGO_SHA512 : 'sha512'); - - default: - throw new \Exception("Unsupported or invalid signing algorithm."); - } - } - - private function generateRSASignature($input, $key, $algo) - { - if (!openssl_sign($input, $signature, $key, $algo)) { - throw new \Exception("Unable to sign data."); - } - - return $signature; - } - - public function urlSafeB64Encode($data) - { - $b64 = base64_encode($data); - $b64 = str_replace(array('+', '/', "\r", "\n", '='), - array('-', '_'), - $b64); - - return $b64; - } - - public function urlSafeB64Decode($b64) - { - $b64 = str_replace(array('-', '_'), - array('+', '/'), - $b64); - - return base64_decode($b64); - } - - /** - * Override to create a custom header - */ - protected function generateJwtHeader($payload, $algorithm) - { - return array( - 'typ' => 'JWT', - 'alg' => $algorithm, - ); - } - - protected function hash_equals($a, $b) - { - if (function_exists('hash_equals')) { - return hash_equals($a, $b); - } - $diff = strlen($a) ^ strlen($b); - for ($i = 0; $i < strlen($a) && $i < strlen($b); $i++) { - $diff |= ord($a[$i]) ^ ord($b[$i]); - } - - return $diff === 0; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/AuthorizationCode.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/AuthorizationCode.php deleted file mode 100644 index e899520..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/AuthorizationCode.php +++ /dev/null @@ -1,100 +0,0 @@ - - */ -class AuthorizationCode implements GrantTypeInterface -{ - protected $storage; - protected $authCode; - - /** - * @param OAuth2\Storage\AuthorizationCodeInterface $storage REQUIRED Storage class for retrieving authorization code information - */ - public function __construct(AuthorizationCodeInterface $storage) - { - $this->storage = $storage; - } - - public function getQuerystringIdentifier() - { - return 'authorization_code'; - } - - public function validateRequest(RequestInterface $request, ResponseInterface $response) - { - if (!$request->request('code')) { - $response->setError(400, 'invalid_request', 'Missing parameter: "code" is required'); - - return false; - } - - $code = $request->request('code'); - if (!$authCode = $this->storage->getAuthorizationCode($code)) { - $response->setError(400, 'invalid_grant', 'Authorization code doesn\'t exist or is invalid for the client'); - - return false; - } - - /* - * 4.1.3 - ensure that the "redirect_uri" parameter is present if the "redirect_uri" parameter was included in the initial authorization request - * @uri - http://tools.ietf.org/html/rfc6749#section-4.1.3 - */ - if (isset($authCode['redirect_uri']) && $authCode['redirect_uri']) { - if (!$request->request('redirect_uri') || urldecode($request->request('redirect_uri')) != $authCode['redirect_uri']) { - $response->setError(400, 'redirect_uri_mismatch', "The redirect URI is missing or do not match", "#section-4.1.3"); - - return false; - } - } - - if (!isset($authCode['expires'])) { - throw new \Exception('Storage must return authcode with a value for "expires"'); - } - - if ($authCode["expires"] < time()) { - $response->setError(400, 'invalid_grant', "The authorization code has expired"); - - return false; - } - - if (!isset($authCode['code'])) { - $authCode['code'] = $code; // used to expire the code after the access token is granted - } - - $this->authCode = $authCode; - - return true; - } - - public function getClientId() - { - return $this->authCode['client_id']; - } - - public function getScope() - { - return isset($this->authCode['scope']) ? $this->authCode['scope'] : null; - } - - public function getUserId() - { - return isset($this->authCode['user_id']) ? $this->authCode['user_id'] : null; - } - - public function createAccessToken(AccessTokenInterface $accessToken, $client_id, $user_id, $scope) - { - $token = $accessToken->createAccessToken($client_id, $user_id, $scope); - $this->storage->expireAuthorizationCode($this->authCode['code']); - - return $token; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/ClientCredentials.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/ClientCredentials.php deleted file mode 100644 index f953e4e..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/ClientCredentials.php +++ /dev/null @@ -1,67 +0,0 @@ - - * - * @see OAuth2\ClientAssertionType_HttpBasic - */ -class ClientCredentials extends HttpBasic implements GrantTypeInterface -{ - private $clientData; - - public function __construct(ClientCredentialsInterface $storage, array $config = array()) - { - /** - * The client credentials grant type MUST only be used by confidential clients - * - * @see http://tools.ietf.org/html/rfc6749#section-4.4 - */ - $config['allow_public_clients'] = false; - - parent::__construct($storage, $config); - } - - public function getQuerystringIdentifier() - { - return 'client_credentials'; - } - - public function getScope() - { - $this->loadClientData(); - - return isset($this->clientData['scope']) ? $this->clientData['scope'] : null; - } - - public function getUserId() - { - $this->loadClientData(); - - return isset($this->clientData['user_id']) ? $this->clientData['user_id'] : null; - } - - public function createAccessToken(AccessTokenInterface $accessToken, $client_id, $user_id, $scope) - { - /** - * Client Credentials Grant does NOT include a refresh token - * - * @see http://tools.ietf.org/html/rfc6749#section-4.4.3 - */ - $includeRefreshToken = false; - - return $accessToken->createAccessToken($client_id, $user_id, $scope, $includeRefreshToken); - } - - private function loadClientData() - { - if (!$this->clientData) { - $this->clientData = $this->storage->getClientDetails($this->getClientId()); - } - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/GrantTypeInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/GrantTypeInterface.php deleted file mode 100644 index 98489e9..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/GrantTypeInterface.php +++ /dev/null @@ -1,20 +0,0 @@ - - */ -class JwtBearer implements GrantTypeInterface, ClientAssertionTypeInterface -{ - private $jwt; - - protected $storage; - protected $audience; - protected $jwtUtil; - protected $allowedAlgorithms; - - /** - * Creates an instance of the JWT bearer grant type. - * - * @param OAuth2\Storage\JWTBearerInterface|JwtBearerInterface $storage A valid storage interface that implements storage hooks for the JWT bearer grant type. - * @param string $audience The audience to validate the token against. This is usually the full URI of the OAuth token requests endpoint. - * @param EncryptionInterface|OAuth2\Encryption\JWT $jwtUtil OPTONAL The class used to decode, encode and verify JWTs. - * @param array $config - */ - public function __construct(JwtBearerInterface $storage, $audience, EncryptionInterface $jwtUtil = null, array $config = array()) - { - $this->storage = $storage; - $this->audience = $audience; - - if (is_null($jwtUtil)) { - $jwtUtil = new Jwt(); - } - - $this->config = array_merge(array( - 'allowed_algorithms' => array('RS256', 'RS384', 'RS512') - ), $config); - - $this->jwtUtil = $jwtUtil; - - $this->allowedAlgorithms = $this->config['allowed_algorithms']; - } - - /** - * Returns the grant_type get parameter to identify the grant type request as JWT bearer authorization grant. - * - * @return - * The string identifier for grant_type. - * - * @see OAuth2\GrantType\GrantTypeInterface::getQuerystringIdentifier() - */ - public function getQuerystringIdentifier() - { - return 'urn:ietf:params:oauth:grant-type:jwt-bearer'; - } - - /** - * Validates the data from the decoded JWT. - * - * @return - * TRUE if the JWT request is valid and can be decoded. Otherwise, FALSE is returned. - * - * @see OAuth2\GrantType\GrantTypeInterface::getTokenData() - */ - public function validateRequest(RequestInterface $request, ResponseInterface $response) - { - if (!$request->request("assertion")) { - $response->setError(400, 'invalid_request', 'Missing parameters: "assertion" required'); - - return null; - } - - // Store the undecoded JWT for later use - $undecodedJWT = $request->request('assertion'); - - // Decode the JWT - $jwt = $this->jwtUtil->decode($request->request('assertion'), null, false); - - if (!$jwt) { - $response->setError(400, 'invalid_request', "JWT is malformed"); - - return null; - } - - // ensure these properties contain a value - // @todo: throw malformed error for missing properties - $jwt = array_merge(array( - 'scope' => null, - 'iss' => null, - 'sub' => null, - 'aud' => null, - 'exp' => null, - 'nbf' => null, - 'iat' => null, - 'jti' => null, - 'typ' => null, - ), $jwt); - - if (!isset($jwt['iss'])) { - $response->setError(400, 'invalid_grant', "Invalid issuer (iss) provided"); - - return null; - } - - if (!isset($jwt['sub'])) { - $response->setError(400, 'invalid_grant', "Invalid subject (sub) provided"); - - return null; - } - - if (!isset($jwt['exp'])) { - $response->setError(400, 'invalid_grant', "Expiration (exp) time must be present"); - - return null; - } - - // Check expiration - if (ctype_digit($jwt['exp'])) { - if ($jwt['exp'] <= time()) { - $response->setError(400, 'invalid_grant', "JWT has expired"); - - return null; - } - } else { - $response->setError(400, 'invalid_grant', "Expiration (exp) time must be a unix time stamp"); - - return null; - } - - // Check the not before time - if ($notBefore = $jwt['nbf']) { - if (ctype_digit($notBefore)) { - if ($notBefore > time()) { - $response->setError(400, 'invalid_grant', "JWT cannot be used before the Not Before (nbf) time"); - - return null; - } - } else { - $response->setError(400, 'invalid_grant', "Not Before (nbf) time must be a unix time stamp"); - - return null; - } - } - - // Check the audience if required to match - if (!isset($jwt['aud']) || ($jwt['aud'] != $this->audience)) { - $response->setError(400, 'invalid_grant', "Invalid audience (aud)"); - - return null; - } - - // Check the jti (nonce) - // @see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-13#section-4.1.7 - if (isset($jwt['jti'])) { - $jti = $this->storage->getJti($jwt['iss'], $jwt['sub'], $jwt['aud'], $jwt['exp'], $jwt['jti']); - - //Reject if jti is used and jwt is still valid (exp parameter has not expired). - if ($jti && $jti['expires'] > time()) { - $response->setError(400, 'invalid_grant', "JSON Token Identifier (jti) has already been used"); - - return null; - } else { - $this->storage->setJti($jwt['iss'], $jwt['sub'], $jwt['aud'], $jwt['exp'], $jwt['jti']); - } - } - - // Get the iss's public key - // @see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06#section-4.1.1 - if (!$key = $this->storage->getClientKey($jwt['iss'], $jwt['sub'])) { - $response->setError(400, 'invalid_grant', "Invalid issuer (iss) or subject (sub) provided"); - - return null; - } - - // Verify the JWT - if (!$this->jwtUtil->decode($undecodedJWT, $key, $this->allowedAlgorithms)) { - $response->setError(400, 'invalid_grant', "JWT failed signature verification"); - - return null; - } - - $this->jwt = $jwt; - - return true; - } - - public function getClientId() - { - return $this->jwt['iss']; - } - - public function getUserId() - { - return $this->jwt['sub']; - } - - public function getScope() - { - return null; - } - - /** - * Creates an access token that is NOT associated with a refresh token. - * If a subject (sub) the name of the user/account we are accessing data on behalf of. - * - * @see OAuth2\GrantType\GrantTypeInterface::createAccessToken() - */ - public function createAccessToken(AccessTokenInterface $accessToken, $client_id, $user_id, $scope) - { - $includeRefreshToken = false; - - return $accessToken->createAccessToken($client_id, $user_id, $scope, $includeRefreshToken); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/RefreshToken.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/RefreshToken.php deleted file mode 100644 index e553852..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/RefreshToken.php +++ /dev/null @@ -1,111 +0,0 @@ - - */ -class RefreshToken implements GrantTypeInterface -{ - private $refreshToken; - - protected $storage; - protected $config; - - /** - * @param OAuth2\Storage\RefreshTokenInterface $storage REQUIRED Storage class for retrieving refresh token information - * @param array $config OPTIONAL Configuration options for the server - * - * $config = array( - * 'always_issue_new_refresh_token' => true, // whether to issue a new refresh token upon successful token request - * 'unset_refresh_token_after_use' => true // whether to unset the refresh token after after using - * ); - * - */ - public function __construct(RefreshTokenInterface $storage, $config = array()) - { - $this->config = array_merge(array( - 'always_issue_new_refresh_token' => false, - 'unset_refresh_token_after_use' => true - ), $config); - - // to preserve B.C. with v1.6 - // @see https://github.com/bshaffer/oauth2-server-php/pull/580 - // @todo - remove in v2.0 - if (isset($config['always_issue_new_refresh_token']) && !isset($config['unset_refresh_token_after_use'])) { - $this->config['unset_refresh_token_after_use'] = $config['always_issue_new_refresh_token']; - } - - $this->storage = $storage; - } - - public function getQuerystringIdentifier() - { - return 'refresh_token'; - } - - public function validateRequest(RequestInterface $request, ResponseInterface $response) - { - if (!$request->request("refresh_token")) { - $response->setError(400, 'invalid_request', 'Missing parameter: "refresh_token" is required'); - - return null; - } - - if (!$refreshToken = $this->storage->getRefreshToken($request->request("refresh_token"))) { - $response->setError(400, 'invalid_grant', 'Invalid refresh token'); - - return null; - } - - if ($refreshToken['expires'] > 0 && $refreshToken["expires"] < time()) { - $response->setError(400, 'invalid_grant', 'Refresh token has expired'); - - return null; - } - - // store the refresh token locally so we can delete it when a new refresh token is generated - $this->refreshToken = $refreshToken; - - return true; - } - - public function getClientId() - { - return $this->refreshToken['client_id']; - } - - public function getUserId() - { - return isset($this->refreshToken['user_id']) ? $this->refreshToken['user_id'] : null; - } - - public function getScope() - { - return isset($this->refreshToken['scope']) ? $this->refreshToken['scope'] : null; - } - - public function createAccessToken(AccessTokenInterface $accessToken, $client_id, $user_id, $scope) - { - /* - * It is optional to force a new refresh token when a refresh token is used. - * However, if a new refresh token is issued, the old one MUST be expired - * @see http://tools.ietf.org/html/rfc6749#section-6 - */ - $issueNewRefreshToken = $this->config['always_issue_new_refresh_token']; - $unsetRefreshToken = $this->config['unset_refresh_token_after_use']; - $token = $accessToken->createAccessToken($client_id, $user_id, $scope, $issueNewRefreshToken); - - if ($unsetRefreshToken) { - $this->storage->unsetRefreshToken($this->refreshToken['refresh_token']); - } - - return $token; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/UserCredentials.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/UserCredentials.php deleted file mode 100644 index f165538..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/GrantType/UserCredentials.php +++ /dev/null @@ -1,83 +0,0 @@ - - */ -class UserCredentials implements GrantTypeInterface -{ - private $userInfo; - - protected $storage; - - /** - * @param OAuth2\Storage\UserCredentialsInterface $storage REQUIRED Storage class for retrieving user credentials information - */ - public function __construct(UserCredentialsInterface $storage) - { - $this->storage = $storage; - } - - public function getQuerystringIdentifier() - { - return 'password'; - } - - public function validateRequest(RequestInterface $request, ResponseInterface $response) - { - if (!$request->request("password") || !$request->request("username")) { - $response->setError(400, 'invalid_request', 'Missing parameters: "username" and "password" required'); - - return null; - } - - if (!$this->storage->checkUserCredentials($request->request("username"), $request->request("password"))) { - $response->setError(401, 'invalid_grant', 'Invalid username and password combination'); - - return null; - } - - $userInfo = $this->storage->getUserDetails($request->request("username")); - - if (empty($userInfo)) { - $response->setError(400, 'invalid_grant', 'Unable to retrieve user information'); - - return null; - } - - if (!isset($userInfo['user_id'])) { - throw new \LogicException("you must set the user_id on the array returned by getUserDetails"); - } - - $this->userInfo = $userInfo; - - return true; - } - - public function getClientId() - { - return null; - } - - public function getUserId() - { - return $this->userInfo['user_id']; - } - - public function getScope() - { - return isset($this->userInfo['scope']) ? $this->userInfo['scope'] : null; - } - - public function createAccessToken(AccessTokenInterface $accessToken, $client_id, $user_id, $scope) - { - return $accessToken->createAccessToken($client_id, $user_id, $scope); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Controller/AuthorizeController.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Controller/AuthorizeController.php deleted file mode 100644 index c9b5c6a..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Controller/AuthorizeController.php +++ /dev/null @@ -1,106 +0,0 @@ -query('prompt', 'consent'); - if ($prompt == 'none') { - if (is_null($user_id)) { - $error = 'login_required'; - $error_message = 'The user must log in'; - } else { - $error = 'interaction_required'; - $error_message = 'The user must grant access to your application'; - } - } else { - $error = 'consent_required'; - $error_message = 'The user denied access to your application'; - } - - $response->setRedirect($this->config['redirect_status_code'], $redirect_uri, $this->getState(), $error, $error_message); - } - - protected function buildAuthorizeParameters($request, $response, $user_id) - { - if (!$params = parent::buildAuthorizeParameters($request, $response, $user_id)) { - return; - } - - // Generate an id token if needed. - if ($this->needsIdToken($this->getScope()) && $this->getResponseType() == self::RESPONSE_TYPE_AUTHORIZATION_CODE) { - $params['id_token'] = $this->responseTypes['id_token']->createIdToken($this->getClientId(), $user_id, $this->nonce); - } - - // add the nonce to return with the redirect URI - $params['nonce'] = $this->nonce; - - return $params; - } - - public function validateAuthorizeRequest(RequestInterface $request, ResponseInterface $response) - { - if (!parent::validateAuthorizeRequest($request, $response)) { - return false; - } - - $nonce = $request->query('nonce'); - - // Validate required nonce for "id_token" and "id_token token" - if (!$nonce && in_array($this->getResponseType(), array(self::RESPONSE_TYPE_ID_TOKEN, self::RESPONSE_TYPE_ID_TOKEN_TOKEN))) { - $response->setError(400, 'invalid_nonce', 'This application requires you specify a nonce parameter'); - - return false; - } - - $this->nonce = $nonce; - - return true; - } - - protected function getValidResponseTypes() - { - return array( - self::RESPONSE_TYPE_ACCESS_TOKEN, - self::RESPONSE_TYPE_AUTHORIZATION_CODE, - self::RESPONSE_TYPE_ID_TOKEN, - self::RESPONSE_TYPE_ID_TOKEN_TOKEN, - self::RESPONSE_TYPE_CODE_ID_TOKEN, - ); - } - - /** - * Returns whether the current request needs to generate an id token. - * - * ID Tokens are a part of the OpenID Connect specification, so this - * method checks whether OpenID Connect is enabled in the server settings - * and whether the openid scope was requested. - * - * @param $request_scope - * A space-separated string of scopes. - * - * @return - * TRUE if an id token is needed, FALSE otherwise. - */ - public function needsIdToken($request_scope) - { - // see if the "openid" scope exists in the requested scope - return $this->scopeUtil->checkScope('openid', $request_scope); - } - - public function getNonce() - { - return $this->nonce; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Controller/AuthorizeControllerInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Controller/AuthorizeControllerInterface.php deleted file mode 100644 index 1e231d8..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Controller/AuthorizeControllerInterface.php +++ /dev/null @@ -1,10 +0,0 @@ -tokenType = $tokenType; - $this->tokenStorage = $tokenStorage; - $this->userClaimsStorage = $userClaimsStorage; - - $this->config = array_merge(array( - 'www_realm' => 'Service', - ), $config); - - if (is_null($scopeUtil)) { - $scopeUtil = new Scope(); - } - $this->scopeUtil = $scopeUtil; - } - - public function handleUserInfoRequest(RequestInterface $request, ResponseInterface $response) - { - if (!$this->verifyResourceRequest($request, $response, 'openid')) { - return; - } - - $token = $this->getToken(); - $claims = $this->userClaimsStorage->getUserClaims($token['user_id'], $token['scope']); - // The sub Claim MUST always be returned in the UserInfo Response. - // http://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse - $claims += array( - 'sub' => $token['user_id'], - ); - $response->addParameters($claims); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Controller/UserInfoControllerInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Controller/UserInfoControllerInterface.php deleted file mode 100644 index a89049d..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Controller/UserInfoControllerInterface.php +++ /dev/null @@ -1,23 +0,0 @@ - $response = new OAuth2\Response(); - * > $userInfoController->handleUserInfoRequest( - * > OAuth2\Request::createFromGlobals(), - * > $response; - * > $response->send(); - * - */ -interface UserInfoControllerInterface -{ - public function handleUserInfoRequest(RequestInterface $request, ResponseInterface $response); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/GrantType/AuthorizationCode.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/GrantType/AuthorizationCode.php deleted file mode 100644 index 8ed1edc..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/GrantType/AuthorizationCode.php +++ /dev/null @@ -1,33 +0,0 @@ - - */ -class AuthorizationCode extends BaseAuthorizationCode -{ - public function createAccessToken(AccessTokenInterface $accessToken, $client_id, $user_id, $scope) - { - $includeRefreshToken = true; - if (isset($this->authCode['id_token'])) { - // OpenID Connect requests include the refresh token only if the - // offline_access scope has been requested and granted. - $scopes = explode(' ', trim($scope)); - $includeRefreshToken = in_array('offline_access', $scopes); - } - - $token = $accessToken->createAccessToken($client_id, $user_id, $scope, $includeRefreshToken); - if (isset($this->authCode['id_token'])) { - $token['id_token'] = $this->authCode['id_token']; - } - - $this->storage->expireAuthorizationCode($this->authCode['code']); - - return $token; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/AuthorizationCode.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/AuthorizationCode.php deleted file mode 100644 index 8971954..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/AuthorizationCode.php +++ /dev/null @@ -1,60 +0,0 @@ - - */ -class AuthorizationCode extends BaseAuthorizationCode implements AuthorizationCodeInterface -{ - public function __construct(AuthorizationCodeStorageInterface $storage, array $config = array()) - { - parent::__construct($storage, $config); - } - - public function getAuthorizeResponse($params, $user_id = null) - { - // build the URL to redirect to - $result = array('query' => array()); - - $params += array('scope' => null, 'state' => null, 'id_token' => null); - - $result['query']['code'] = $this->createAuthorizationCode($params['client_id'], $user_id, $params['redirect_uri'], $params['scope'], $params['id_token']); - - if (isset($params['state'])) { - $result['query']['state'] = $params['state']; - } - - return array($params['redirect_uri'], $result); - } - - /** - * Handle the creation of the authorization code. - * - * @param $client_id - * Client identifier related to the authorization code - * @param $user_id - * User ID associated with the authorization code - * @param $redirect_uri - * An absolute URI to which the authorization server will redirect the - * user-agent to when the end-user authorization step is completed. - * @param $scope - * (optional) Scopes to be stored in space-separated string. - * @param $id_token - * (optional) The OpenID Connect id_token. - * - * @see http://tools.ietf.org/html/rfc6749#section-4 - * @ingroup oauth2_section_4 - */ - public function createAuthorizationCode($client_id, $user_id, $redirect_uri, $scope = null, $id_token = null) - { - $code = $this->generateAuthorizationCode(); - $this->storage->setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, time() + $this->config['auth_code_lifetime'], $scope, $id_token); - - return $code; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/AuthorizationCodeInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/AuthorizationCodeInterface.php deleted file mode 100644 index ea47792..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/AuthorizationCodeInterface.php +++ /dev/null @@ -1,27 +0,0 @@ - - */ -interface AuthorizationCodeInterface extends BaseAuthorizationCodeInterface -{ - /** - * Handle the creation of the authorization code. - * - * @param $client_id Client identifier related to the authorization code - * @param $user_id User ID associated with the authorization code - * @param $redirect_uri An absolute URI to which the authorization server will redirect the - * user-agent to when the end-user authorization step is completed. - * @param $scope OPTIONAL Scopes to be stored in space-separated string. - * @param $id_token OPTIONAL The OpenID Connect id_token. - * - * @see http://tools.ietf.org/html/rfc6749#section-4 - * @ingroup oauth2_section_4 - */ - public function createAuthorizationCode($client_id, $user_id, $redirect_uri, $scope = null, $id_token = null); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/CodeIdToken.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/CodeIdToken.php deleted file mode 100644 index 9bc3322..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/CodeIdToken.php +++ /dev/null @@ -1,24 +0,0 @@ -authCode = $authCode; - $this->idToken = $idToken; - } - - public function getAuthorizeResponse($params, $user_id = null) - { - $result = $this->authCode->getAuthorizeResponse($params, $user_id); - $id_token = $this->idToken->createIdToken($params['client_id'], $user_id, $params['nonce']); - $result[1]['query']['id_token'] = $id_token; - - return $result; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/CodeIdTokenInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/CodeIdTokenInterface.php deleted file mode 100644 index 629adcc..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/CodeIdTokenInterface.php +++ /dev/null @@ -1,9 +0,0 @@ -userClaimsStorage = $userClaimsStorage; - $this->publicKeyStorage = $publicKeyStorage; - if (is_null($encryptionUtil)) { - $encryptionUtil = new Jwt(); - } - $this->encryptionUtil = $encryptionUtil; - - if (!isset($config['issuer'])) { - throw new \LogicException('config parameter "issuer" must be set'); - } - $this->config = array_merge(array( - 'id_lifetime' => 3600, - ), $config); - } - - public function getAuthorizeResponse($params, $userInfo = null) - { - // build the URL to redirect to - $result = array('query' => array()); - $params += array('scope' => null, 'state' => null, 'nonce' => null); - - // create the id token. - list($user_id, $auth_time) = $this->getUserIdAndAuthTime($userInfo); - $userClaims = $this->userClaimsStorage->getUserClaims($user_id, $params['scope']); - - $id_token = $this->createIdToken($params['client_id'], $userInfo, $params['nonce'], $userClaims, null); - $result["fragment"] = array('id_token' => $id_token); - if (isset($params['state'])) { - $result["fragment"]["state"] = $params['state']; - } - - return array($params['redirect_uri'], $result); - } - - public function createIdToken($client_id, $userInfo, $nonce = null, $userClaims = null, $access_token = null) - { - // pull auth_time from user info if supplied - list($user_id, $auth_time) = $this->getUserIdAndAuthTime($userInfo); - - $token = array( - 'iss' => $this->config['issuer'], - 'sub' => $user_id, - 'aud' => $client_id, - 'iat' => time(), - 'exp' => time() + $this->config['id_lifetime'], - 'auth_time' => $auth_time, - ); - - if ($nonce) { - $token['nonce'] = $nonce; - } - - if ($userClaims) { - $token += $userClaims; - } - - if ($access_token) { - $token['at_hash'] = $this->createAtHash($access_token, $client_id); - } - - return $this->encodeToken($token, $client_id); - } - - protected function createAtHash($access_token, $client_id = null) - { - // maps HS256 and RS256 to sha256, etc. - $algorithm = $this->publicKeyStorage->getEncryptionAlgorithm($client_id); - $hash_algorithm = 'sha' . substr($algorithm, 2); - $hash = hash($hash_algorithm, $access_token); - $at_hash = substr($hash, 0, strlen($hash) / 2); - - return $this->encryptionUtil->urlSafeB64Encode($at_hash); - } - - protected function encodeToken(array $token, $client_id = null) - { - $private_key = $this->publicKeyStorage->getPrivateKey($client_id); - $algorithm = $this->publicKeyStorage->getEncryptionAlgorithm($client_id); - - return $this->encryptionUtil->encode($token, $private_key, $algorithm); - } - - private function getUserIdAndAuthTime($userInfo) - { - $auth_time = null; - - // support an array for user_id / auth_time - if (is_array($userInfo)) { - if (!isset($userInfo['user_id'])) { - throw new \LogicException('if $user_id argument is an array, user_id index must be set'); - } - - $auth_time = isset($userInfo['auth_time']) ? $userInfo['auth_time'] : null; - $user_id = $userInfo['user_id']; - } else { - $user_id = $userInfo; - } - - if (is_null($auth_time)) { - $auth_time = time(); - } - - // userInfo is a scalar, and so this is the $user_id. Auth Time is null - return array($user_id, $auth_time); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/IdTokenInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/IdTokenInterface.php deleted file mode 100644 index 0bd2f83..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/IdTokenInterface.php +++ /dev/null @@ -1,29 +0,0 @@ -accessToken = $accessToken; - $this->idToken = $idToken; - } - - public function getAuthorizeResponse($params, $user_id = null) - { - $result = $this->accessToken->getAuthorizeResponse($params, $user_id); - $access_token = $result[1]['fragment']['access_token']; - $id_token = $this->idToken->createIdToken($params['client_id'], $user_id, $params['nonce'], null, $access_token); - $result[1]['fragment']['id_token'] = $id_token; - - return $result; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/IdTokenTokenInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/IdTokenTokenInterface.php deleted file mode 100644 index ac13e20..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/ResponseType/IdTokenTokenInterface.php +++ /dev/null @@ -1,9 +0,0 @@ - - */ -interface AuthorizationCodeInterface extends BaseAuthorizationCodeInterface -{ - /** - * Take the provided authorization code values and store them somewhere. - * - * This function should be the storage counterpart to getAuthCode(). - * - * If storage fails for some reason, we're not currently checking for - * any sort of success/failure, so you should bail out of the script - * and provide a descriptive fail message. - * - * Required for OAuth2::GRANT_TYPE_AUTH_CODE. - * - * @param $code authorization code to be stored. - * @param $client_id client identifier to be stored. - * @param $user_id user identifier to be stored. - * @param string $redirect_uri redirect URI(s) to be stored in a space-separated string. - * @param int $expires expiration to be stored as a Unix timestamp. - * @param string $scope OPTIONAL scopes to be stored in space-separated string. - * @param string $id_token OPTIONAL the OpenID Connect id_token. - * - * @ingroup oauth2_section_4 - */ - public function setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Storage/UserClaimsInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Storage/UserClaimsInterface.php deleted file mode 100644 index f230bef..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/OpenID/Storage/UserClaimsInterface.php +++ /dev/null @@ -1,38 +0,0 @@ - value format. - * - * @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims - */ - public function getUserClaims($user_id, $scope); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Request.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Request.php deleted file mode 100644 index c92cee8..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Request.php +++ /dev/null @@ -1,213 +0,0 @@ -initialize($query, $request, $attributes, $cookies, $files, $server, $content, $headers); - } - - /** - * Sets the parameters for this request. - * - * This method also re-initializes all properties. - * - * @param array $query The GET parameters - * @param array $request The POST parameters - * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) - * @param array $cookies The COOKIE parameters - * @param array $files The FILES parameters - * @param array $server The SERVER parameters - * @param string $content The raw body data - * - * @api - */ - public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null, array $headers = null) - { - $this->request = $request; - $this->query = $query; - $this->attributes = $attributes; - $this->cookies = $cookies; - $this->files = $files; - $this->server = $server; - $this->content = $content; - $this->headers = is_null($headers) ? $this->getHeadersFromServer($this->server) : $headers; - } - - public function query($name, $default = null) - { - return isset($this->query[$name]) ? $this->query[$name] : $default; - } - - public function request($name, $default = null) - { - return isset($this->request[$name]) ? $this->request[$name] : $default; - } - - public function server($name, $default = null) - { - return isset($this->server[$name]) ? $this->server[$name] : $default; - } - - public function headers($name, $default = null) - { - $headers = array_change_key_case($this->headers); - $name = strtolower($name); - - return isset($headers[$name]) ? $headers[$name] : $default; - } - - public function getAllQueryParameters() - { - return $this->query; - } - - /** - * Returns the request body content. - * - * @param Boolean $asResource If true, a resource will be returned - * - * @return string|resource The request body content or a resource to read the body stream. - */ - public function getContent($asResource = false) - { - if (false === $this->content || (true === $asResource && null !== $this->content)) { - throw new \LogicException('getContent() can only be called once when using the resource return type.'); - } - - if (true === $asResource) { - $this->content = false; - - return fopen('php://input', 'rb'); - } - - if (null === $this->content) { - $this->content = file_get_contents('php://input'); - } - - return $this->content; - } - - private function getHeadersFromServer($server) - { - $headers = array(); - foreach ($server as $key => $value) { - if (0 === strpos($key, 'HTTP_')) { - $headers[substr($key, 5)] = $value; - } - // CONTENT_* are not prefixed with HTTP_ - elseif (in_array($key, array('CONTENT_LENGTH', 'CONTENT_MD5', 'CONTENT_TYPE'))) { - $headers[$key] = $value; - } - } - - if (isset($server['PHP_AUTH_USER'])) { - $headers['PHP_AUTH_USER'] = $server['PHP_AUTH_USER']; - $headers['PHP_AUTH_PW'] = isset($server['PHP_AUTH_PW']) ? $server['PHP_AUTH_PW'] : ''; - } else { - /* - * php-cgi under Apache does not pass HTTP Basic user/pass to PHP by default - * For this workaround to work, add this line to your .htaccess file: - * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] - * - * A sample .htaccess file: - * RewriteEngine On - * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] - * RewriteCond %{REQUEST_FILENAME} !-f - * RewriteRule ^(.*)$ app.php [QSA,L] - */ - - $authorizationHeader = null; - if (isset($server['HTTP_AUTHORIZATION'])) { - $authorizationHeader = $server['HTTP_AUTHORIZATION']; - } elseif (isset($server['REDIRECT_HTTP_AUTHORIZATION'])) { - $authorizationHeader = $server['REDIRECT_HTTP_AUTHORIZATION']; - } elseif (function_exists('apache_request_headers')) { - $requestHeaders = (array) apache_request_headers(); - - // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization) - $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders)); - - if (isset($requestHeaders['Authorization'])) { - $authorizationHeader = trim($requestHeaders['Authorization']); - } - } - - if (null !== $authorizationHeader) { - $headers['AUTHORIZATION'] = $authorizationHeader; - // Decode AUTHORIZATION header into PHP_AUTH_USER and PHP_AUTH_PW when authorization header is basic - if (0 === stripos($authorizationHeader, 'basic')) { - $exploded = explode(':', base64_decode(substr($authorizationHeader, 6))); - if (count($exploded) == 2) { - list($headers['PHP_AUTH_USER'], $headers['PHP_AUTH_PW']) = $exploded; - } - } - } - } - - // PHP_AUTH_USER/PHP_AUTH_PW - if (isset($headers['PHP_AUTH_USER'])) { - $headers['AUTHORIZATION'] = 'Basic '.base64_encode($headers['PHP_AUTH_USER'].':'.$headers['PHP_AUTH_PW']); - } - - return $headers; - } - - /** - * Creates a new request with values from PHP's super globals. - * - * @return Request A new request - * - * @api - */ - public static function createFromGlobals() - { - $class = get_called_class(); - $request = new $class($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER); - - $contentType = $request->server('CONTENT_TYPE', ''); - $requestMethod = $request->server('REQUEST_METHOD', 'GET'); - if (0 === strpos($contentType, 'application/x-www-form-urlencoded') - && in_array(strtoupper($requestMethod), array('PUT', 'DELETE')) - ) { - parse_str($request->getContent(), $data); - $request->request = $data; - } elseif (0 === strpos($contentType, 'application/json') - && in_array(strtoupper($requestMethod), array('POST', 'PUT', 'DELETE')) - ) { - $data = json_decode($request->getContent(), true); - $request->request = $data; - } - - return $request; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/RequestInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/RequestInterface.php deleted file mode 100644 index 8a70d5f..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/RequestInterface.php +++ /dev/null @@ -1,16 +0,0 @@ - 'Continue', - 101 => 'Switching Protocols', - 200 => 'OK', - 201 => 'Created', - 202 => 'Accepted', - 203 => 'Non-Authoritative Information', - 204 => 'No Content', - 205 => 'Reset Content', - 206 => 'Partial Content', - 300 => 'Multiple Choices', - 301 => 'Moved Permanently', - 302 => 'Found', - 303 => 'See Other', - 304 => 'Not Modified', - 305 => 'Use Proxy', - 307 => 'Temporary Redirect', - 400 => 'Bad Request', - 401 => 'Unauthorized', - 402 => 'Payment Required', - 403 => 'Forbidden', - 404 => 'Not Found', - 405 => 'Method Not Allowed', - 406 => 'Not Acceptable', - 407 => 'Proxy Authentication Required', - 408 => 'Request Timeout', - 409 => 'Conflict', - 410 => 'Gone', - 411 => 'Length Required', - 412 => 'Precondition Failed', - 413 => 'Request Entity Too Large', - 414 => 'Request-URI Too Long', - 415 => 'Unsupported Media Type', - 416 => 'Requested Range Not Satisfiable', - 417 => 'Expectation Failed', - 418 => 'I\'m a teapot', - 500 => 'Internal Server Error', - 501 => 'Not Implemented', - 502 => 'Bad Gateway', - 503 => 'Service Unavailable', - 504 => 'Gateway Timeout', - 505 => 'HTTP Version Not Supported', - ); - - public function __construct($parameters = array(), $statusCode = 200, $headers = array()) - { - $this->setParameters($parameters); - $this->setStatusCode($statusCode); - $this->setHttpHeaders($headers); - $this->version = '1.1'; - } - - /** - * Converts the response object to string containing all headers and the response content. - * - * @return string The response with headers and content - */ - public function __toString() - { - $headers = array(); - foreach ($this->httpHeaders as $name => $value) { - $headers[$name] = (array) $value; - } - - return - sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n". - $this->getHttpHeadersAsString($headers)."\r\n". - $this->getResponseBody(); - } - - /** - * Returns the build header line. - * - * @param string $name The header name - * @param string $value The header value - * - * @return string The built header line - */ - protected function buildHeader($name, $value) - { - return sprintf("%s: %s\n", $name, $value); - } - - public function getStatusCode() - { - return $this->statusCode; - } - - public function setStatusCode($statusCode, $text = null) - { - $this->statusCode = (int) $statusCode; - if ($this->isInvalid()) { - throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $statusCode)); - } - - $this->statusText = false === $text ? '' : (null === $text ? self::$statusTexts[$this->statusCode] : $text); - } - - public function getStatusText() - { - return $this->statusText; - } - - public function getParameters() - { - return $this->parameters; - } - - public function setParameters(array $parameters) - { - $this->parameters = $parameters; - } - - public function addParameters(array $parameters) - { - $this->parameters = array_merge($this->parameters, $parameters); - } - - public function getParameter($name, $default = null) - { - return isset($this->parameters[$name]) ? $this->parameters[$name] : $default; - } - - public function setParameter($name, $value) - { - $this->parameters[$name] = $value; - } - - public function setHttpHeaders(array $httpHeaders) - { - $this->httpHeaders = $httpHeaders; - } - - public function setHttpHeader($name, $value) - { - $this->httpHeaders[$name] = $value; - } - - public function addHttpHeaders(array $httpHeaders) - { - $this->httpHeaders = array_merge($this->httpHeaders, $httpHeaders); - } - - public function getHttpHeaders() - { - return $this->httpHeaders; - } - - public function getHttpHeader($name, $default = null) - { - return isset($this->httpHeaders[$name]) ? $this->httpHeaders[$name] : $default; - } - - public function getResponseBody($format = 'json') - { - switch ($format) { - case 'json': - return json_encode($this->parameters); - case 'xml': - // this only works for single-level arrays - $xml = new \SimpleXMLElement(''); - foreach ($this->parameters as $key => $param) { - $xml->addChild($key, $param); - } - - return $xml->asXML(); - } - - throw new \InvalidArgumentException(sprintf('The format %s is not supported', $format)); - - } - - public function send($format = 'json') - { - // headers have already been sent by the developer - if (headers_sent()) { - return; - } - - switch ($format) { - case 'json': - $this->setHttpHeader('Content-Type', 'application/json'); - break; - case 'xml': - $this->setHttpHeader('Content-Type', 'text/xml'); - break; - } - // status - header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)); - - foreach ($this->getHttpHeaders() as $name => $header) { - header(sprintf('%s: %s', $name, $header)); - } - echo $this->getResponseBody($format); - } - - public function setError($statusCode, $error, $errorDescription = null, $errorUri = null) - { - $parameters = array( - 'error' => $error, - 'error_description' => $errorDescription, - ); - - if (!is_null($errorUri)) { - if (strlen($errorUri) > 0 && $errorUri[0] == '#') { - // we are referencing an oauth bookmark (for brevity) - $errorUri = 'http://tools.ietf.org/html/rfc6749' . $errorUri; - } - $parameters['error_uri'] = $errorUri; - } - - $httpHeaders = array( - 'Cache-Control' => 'no-store' - ); - - $this->setStatusCode($statusCode); - $this->addParameters($parameters); - $this->addHttpHeaders($httpHeaders); - - if (!$this->isClientError() && !$this->isServerError()) { - throw new \InvalidArgumentException(sprintf('The HTTP status code is not an error ("%s" given).', $statusCode)); - } - } - - public function setRedirect($statusCode, $url, $state = null, $error = null, $errorDescription = null, $errorUri = null) - { - if (empty($url)) { - throw new \InvalidArgumentException('Cannot redirect to an empty URL.'); - } - - $parameters = array(); - - if (!is_null($state)) { - $parameters['state'] = $state; - } - - if (!is_null($error)) { - $this->setError(400, $error, $errorDescription, $errorUri); - } - $this->setStatusCode($statusCode); - $this->addParameters($parameters); - - if (count($this->parameters) > 0) { - // add parameters to URL redirection - $parts = parse_url($url); - $sep = isset($parts['query']) && count($parts['query']) > 0 ? '&' : '?'; - $url .= $sep . http_build_query($this->parameters); - } - - $this->addHttpHeaders(array('Location' => $url)); - - if (!$this->isRedirection()) { - throw new \InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $statusCode)); - } - } - - // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html - /** - * @return Boolean - * - * @api - */ - public function isInvalid() - { - return $this->statusCode < 100 || $this->statusCode >= 600; - } - - /** - * @return Boolean - * - * @api - */ - public function isInformational() - { - return $this->statusCode >= 100 && $this->statusCode < 200; - } - - /** - * @return Boolean - * - * @api - */ - public function isSuccessful() - { - return $this->statusCode >= 200 && $this->statusCode < 300; - } - - /** - * @return Boolean - * - * @api - */ - public function isRedirection() - { - return $this->statusCode >= 300 && $this->statusCode < 400; - } - - /** - * @return Boolean - * - * @api - */ - public function isClientError() - { - return $this->statusCode >= 400 && $this->statusCode < 500; - } - - /** - * @return Boolean - * - * @api - */ - public function isServerError() - { - return $this->statusCode >= 500 && $this->statusCode < 600; - } - - /* - * Functions from Symfony2 HttpFoundation - output pretty header - */ - private function getHttpHeadersAsString($headers) - { - if (count($headers) == 0) { - return ''; - } - - $max = max(array_map('strlen', array_keys($headers))) + 1; - $content = ''; - ksort($headers); - foreach ($headers as $name => $values) { - foreach ($values as $value) { - $content .= sprintf("%-{$max}s %s\r\n", $this->beautifyHeaderName($name).':', $value); - } - } - - return $content; - } - - private function beautifyHeaderName($name) - { - return preg_replace_callback('/\-(.)/', array($this, 'beautifyCallback'), ucfirst($name)); - } - - private function beautifyCallback($match) - { - return '-'.strtoupper($match[1]); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseInterface.php deleted file mode 100644 index c99b5f7..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseInterface.php +++ /dev/null @@ -1,24 +0,0 @@ - - */ -class AccessToken implements AccessTokenInterface -{ - protected $tokenStorage; - protected $refreshStorage; - protected $config; - - /** - * @param OAuth2\Storage\AccessTokenInterface $tokenStorage REQUIRED Storage class for saving access token information - * @param OAuth2\Storage\RefreshTokenInterface $refreshStorage OPTIONAL Storage class for saving refresh token information - * @param array $config OPTIONAL Configuration options for the server - * - * $config = array( - * 'token_type' => 'bearer', // token type identifier - * 'access_lifetime' => 3600, // time before access token expires - * 'refresh_token_lifetime' => 1209600, // time before refresh token expires - * ); - * - */ - public function __construct(AccessTokenStorageInterface $tokenStorage, RefreshTokenInterface $refreshStorage = null, array $config = array()) - { - $this->tokenStorage = $tokenStorage; - $this->refreshStorage = $refreshStorage; - - $this->config = array_merge(array( - 'token_type' => 'bearer', - 'access_lifetime' => 3600, - 'refresh_token_lifetime' => 1209600, - ), $config); - } - - public function getAuthorizeResponse($params, $user_id = null) - { - // build the URL to redirect to - $result = array('query' => array()); - - $params += array('scope' => null, 'state' => null); - - /* - * a refresh token MUST NOT be included in the fragment - * - * @see http://tools.ietf.org/html/rfc6749#section-4.2.2 - */ - $includeRefreshToken = false; - $result["fragment"] = $this->createAccessToken($params['client_id'], $user_id, $params['scope'], $includeRefreshToken); - - if (isset($params['state'])) { - $result["fragment"]["state"] = $params['state']; - } - - return array($params['redirect_uri'], $result); - } - - /** - * Handle the creation of access token, also issue refresh token if supported / desirable. - * - * @param $client_id client identifier related to the access token. - * @param $user_id user ID associated with the access token - * @param $scope OPTIONAL scopes to be stored in space-separated string. - * @param bool $includeRefreshToken if true, a new refresh_token will be added to the response - * - * @see http://tools.ietf.org/html/rfc6749#section-5 - * @ingroup oauth2_section_5 - */ - public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true) - { - $token = array( - "access_token" => $this->generateAccessToken(), - "expires_in" => $this->config['access_lifetime'], - "token_type" => $this->config['token_type'], - "scope" => $scope - ); - - $this->tokenStorage->setAccessToken($token["access_token"], $client_id, $user_id, $this->config['access_lifetime'] ? time() + $this->config['access_lifetime'] : null, $scope); - - /* - * Issue a refresh token also, if we support them - * - * Refresh Tokens are considered supported if an instance of OAuth2\Storage\RefreshTokenInterface - * is supplied in the constructor - */ - if ($includeRefreshToken && $this->refreshStorage) { - $token["refresh_token"] = $this->generateRefreshToken(); - $expires = 0; - if ($this->config['refresh_token_lifetime'] > 0) { - $expires = time() + $this->config['refresh_token_lifetime']; - } - $this->refreshStorage->setRefreshToken($token['refresh_token'], $client_id, $user_id, $expires, $scope); - } - - return $token; - } - - /** - * Generates an unique access token. - * - * Implementing classes may want to override this function to implement - * other access token generation schemes. - * - * @return - * An unique access token. - * - * @ingroup oauth2_section_4 - */ - protected function generateAccessToken() - { - if (function_exists('mcrypt_create_iv')) { - $randomData = mcrypt_create_iv(20, MCRYPT_DEV_URANDOM); - if ($randomData !== false && strlen($randomData) === 20) { - return bin2hex($randomData); - } - } - if (function_exists('openssl_random_pseudo_bytes')) { - $randomData = openssl_random_pseudo_bytes(20); - if ($randomData !== false && strlen($randomData) === 20) { - return bin2hex($randomData); - } - } - if (@file_exists('/dev/urandom')) { // Get 100 bytes of random data - $randomData = file_get_contents('/dev/urandom', false, null, 0, 20); - if ($randomData !== false && strlen($randomData) === 20) { - return bin2hex($randomData); - } - } - // Last resort which you probably should just get rid of: - $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true); - - return substr(hash('sha512', $randomData), 0, 40); - } - - /** - * Generates an unique refresh token - * - * Implementing classes may want to override this function to implement - * other refresh token generation schemes. - * - * @return - * An unique refresh. - * - * @ingroup oauth2_section_4 - * @see OAuth2::generateAccessToken() - */ - protected function generateRefreshToken() - { - return $this->generateAccessToken(); // let's reuse the same scheme for token generation - } - - /** - * Handle the revoking of refresh tokens, and access tokens if supported / desirable - * RFC7009 specifies that "If the server is unable to locate the token using - * the given hint, it MUST extend its search across all of its supported token types" - * - * @param $token - * @param null $tokenTypeHint - * @return boolean - */ - public function revokeToken($token, $tokenTypeHint = null) - { - if ($tokenTypeHint == 'refresh_token') { - if ($this->refreshStorage && $revoked = $this->refreshStorage->unsetRefreshToken($token)) { - return true; - } - } - - /** @TODO remove in v2 */ - if (!method_exists($this->tokenStorage, 'unsetAccessToken')) { - throw new \RuntimeException( - sprintf('Token storage %s must implement unsetAccessToken method', get_class($this->tokenStorage) - )); - } - - $revoked = $this->tokenStorage->unsetAccessToken($token); - - // if a typehint is supplied and fails, try other storages - // @see https://tools.ietf.org/html/rfc7009#section-2.1 - if (!$revoked && $tokenTypeHint != 'refresh_token') { - if ($this->refreshStorage) { - $revoked = $this->refreshStorage->unsetRefreshToken($token); - } - } - - return $revoked; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/AccessTokenInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/AccessTokenInterface.php deleted file mode 100644 index 4bd3928..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/AccessTokenInterface.php +++ /dev/null @@ -1,34 +0,0 @@ - - */ -interface AccessTokenInterface extends ResponseTypeInterface -{ - /** - * Handle the creation of access token, also issue refresh token if supported / desirable. - * - * @param $client_id client identifier related to the access token. - * @param $user_id user ID associated with the access token - * @param $scope OPTONAL scopes to be stored in space-separated string. - * @param bool $includeRefreshToken if true, a new refresh_token will be added to the response - * - * @see http://tools.ietf.org/html/rfc6749#section-5 - * @ingroup oauth2_section_5 - */ - public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true); - - /** - * Handle the revoking of refresh tokens, and access tokens if supported / desirable - * - * @param $token - * @param $tokenTypeHint - * @return mixed - * - * @todo v2.0 include this method in interface. Omitted to maintain BC in v1.x - */ - //public function revokeToken($token, $tokenTypeHint); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/AuthorizationCode.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/AuthorizationCode.php deleted file mode 100644 index 6a305fd..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/AuthorizationCode.php +++ /dev/null @@ -1,100 +0,0 @@ - - */ -class AuthorizationCode implements AuthorizationCodeInterface -{ - protected $storage; - protected $config; - - public function __construct(AuthorizationCodeStorageInterface $storage, array $config = array()) - { - $this->storage = $storage; - $this->config = array_merge(array( - 'enforce_redirect' => false, - 'auth_code_lifetime' => 30, - ), $config); - } - - public function getAuthorizeResponse($params, $user_id = null) - { - // build the URL to redirect to - $result = array('query' => array()); - - $params += array('scope' => null, 'state' => null); - - $result['query']['code'] = $this->createAuthorizationCode($params['client_id'], $user_id, $params['redirect_uri'], $params['scope']); - - if (isset($params['state'])) { - $result['query']['state'] = $params['state']; - } - - return array($params['redirect_uri'], $result); - } - - /** - * Handle the creation of the authorization code. - * - * @param $client_id - * Client identifier related to the authorization code - * @param $user_id - * User ID associated with the authorization code - * @param $redirect_uri - * An absolute URI to which the authorization server will redirect the - * user-agent to when the end-user authorization step is completed. - * @param $scope - * (optional) Scopes to be stored in space-separated string. - * - * @see http://tools.ietf.org/html/rfc6749#section-4 - * @ingroup oauth2_section_4 - */ - public function createAuthorizationCode($client_id, $user_id, $redirect_uri, $scope = null) - { - $code = $this->generateAuthorizationCode(); - $this->storage->setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, time() + $this->config['auth_code_lifetime'], $scope); - - return $code; - } - - /** - * @return - * TRUE if the grant type requires a redirect_uri, FALSE if not - */ - public function enforceRedirect() - { - return $this->config['enforce_redirect']; - } - - /** - * Generates an unique auth code. - * - * Implementing classes may want to override this function to implement - * other auth code generation schemes. - * - * @return - * An unique auth code. - * - * @ingroup oauth2_section_4 - */ - protected function generateAuthorizationCode() - { - $tokenLen = 40; - if (function_exists('mcrypt_create_iv')) { - $randomData = mcrypt_create_iv(100, MCRYPT_DEV_URANDOM); - } elseif (function_exists('openssl_random_pseudo_bytes')) { - $randomData = openssl_random_pseudo_bytes(100); - } elseif (@file_exists('/dev/urandom')) { // Get 100 bytes of random data - $randomData = file_get_contents('/dev/urandom', false, null, 0, 100) . uniqid(mt_rand(), true); - } else { - $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true); - } - - return substr(hash('sha512', $randomData), 0, $tokenLen); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/AuthorizationCodeInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/AuthorizationCodeInterface.php deleted file mode 100644 index df777e2..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/AuthorizationCodeInterface.php +++ /dev/null @@ -1,30 +0,0 @@ - - */ -interface AuthorizationCodeInterface extends ResponseTypeInterface -{ - /** - * @return - * TRUE if the grant type requires a redirect_uri, FALSE if not - */ - public function enforceRedirect(); - - /** - * Handle the creation of the authorization code. - * - * @param $client_id client identifier related to the authorization code - * @param $user_id user id associated with the authorization code - * @param $redirect_uri an absolute URI to which the authorization server will redirect the - * user-agent to when the end-user authorization step is completed. - * @param $scope OPTIONAL scopes to be stored in space-separated string. - * - * @see http://tools.ietf.org/html/rfc6749#section-4 - * @ingroup oauth2_section_4 - */ - public function createAuthorizationCode($client_id, $user_id, $redirect_uri, $scope = null); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/JwtAccessToken.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/JwtAccessToken.php deleted file mode 100644 index 3942fe4..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/JwtAccessToken.php +++ /dev/null @@ -1,124 +0,0 @@ - - */ -class JwtAccessToken extends AccessToken -{ - protected $publicKeyStorage; - protected $encryptionUtil; - - /** - * @param $config - * - store_encrypted_token_string (bool true) - * whether the entire encrypted string is stored, - * or just the token ID is stored - */ - public function __construct(PublicKeyInterface $publicKeyStorage = null, AccessTokenStorageInterface $tokenStorage = null, RefreshTokenInterface $refreshStorage = null, array $config = array(), EncryptionInterface $encryptionUtil = null) - { - $this->publicKeyStorage = $publicKeyStorage; - $config = array_merge(array( - 'store_encrypted_token_string' => true, - 'issuer' => '' - ), $config); - if (is_null($tokenStorage)) { - // a pass-thru, so we can call the parent constructor - $tokenStorage = new Memory(); - } - if (is_null($encryptionUtil)) { - $encryptionUtil = new Jwt(); - } - $this->encryptionUtil = $encryptionUtil; - parent::__construct($tokenStorage, $refreshStorage, $config); - } - - /** - * Handle the creation of access token, also issue refresh token if supported / desirable. - * - * @param $client_id - * Client identifier related to the access token. - * @param $user_id - * User ID associated with the access token - * @param $scope - * (optional) Scopes to be stored in space-separated string. - * @param bool $includeRefreshToken - * If true, a new refresh_token will be added to the response - * - * @see http://tools.ietf.org/html/rfc6749#section-5 - * @ingroup oauth2_section_5 - */ - public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true) - { - // token to encrypt - $expires = time() + $this->config['access_lifetime']; - $id = $this->generateAccessToken(); - $jwtAccessToken = array( - 'id' => $id, // for BC (see #591) - 'jti' => $id, - 'iss' => $this->config['issuer'], - 'aud' => $client_id, - 'sub' => $user_id, - 'exp' => $expires, - 'iat' => time(), - 'token_type' => $this->config['token_type'], - 'scope' => $scope - ); - - /* - * Encode the token data into a single access_token string - */ - $access_token = $this->encodeToken($jwtAccessToken, $client_id); - - /* - * Save the token to a secondary storage. This is implemented on the - * OAuth2\Storage\JwtAccessToken side, and will not actually store anything, - * if no secondary storage has been supplied - */ - $token_to_store = $this->config['store_encrypted_token_string'] ? $access_token : $jwtAccessToken['id']; - $this->tokenStorage->setAccessToken($token_to_store, $client_id, $user_id, $this->config['access_lifetime'] ? time() + $this->config['access_lifetime'] : null, $scope); - - // token to return to the client - $token = array( - 'access_token' => $access_token, - 'expires_in' => $this->config['access_lifetime'], - 'token_type' => $this->config['token_type'], - 'scope' => $scope - ); - - /* - * Issue a refresh token also, if we support them - * - * Refresh Tokens are considered supported if an instance of OAuth2\Storage\RefreshTokenInterface - * is supplied in the constructor - */ - if ($includeRefreshToken && $this->refreshStorage) { - $refresh_token = $this->generateRefreshToken(); - $expires = 0; - if ($this->config['refresh_token_lifetime'] > 0) { - $expires = time() + $this->config['refresh_token_lifetime']; - } - $this->refreshStorage->setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope); - $token['refresh_token'] = $refresh_token; - } - - return $token; - } - - protected function encodeToken(array $token, $client_id = null) - { - $private_key = $this->publicKeyStorage->getPrivateKey($client_id); - $algorithm = $this->publicKeyStorage->getEncryptionAlgorithm($client_id); - - return $this->encryptionUtil->encode($token, $private_key, $algorithm); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/ResponseTypeInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/ResponseTypeInterface.php deleted file mode 100644 index f8e26a5..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ResponseType/ResponseTypeInterface.php +++ /dev/null @@ -1,8 +0,0 @@ -storage = $storage; - } - - /** - * Check if everything in required scope is contained in available scope. - * - * @param $required_scope - * A space-separated string of scopes. - * - * @return - * TRUE if everything in required scope is contained in available scope, - * and FALSE if it isn't. - * - * @see http://tools.ietf.org/html/rfc6749#section-7 - * - * @ingroup oauth2_section_7 - */ - public function checkScope($required_scope, $available_scope) - { - $required_scope = explode(' ', trim($required_scope)); - $available_scope = explode(' ', trim($available_scope)); - - return (count(array_diff($required_scope, $available_scope)) == 0); - } - - /** - * Check if the provided scope exists in storage. - * - * @param $scope - * A space-separated string of scopes. - * - * @return - * TRUE if it exists, FALSE otherwise. - */ - public function scopeExists($scope) - { - // Check reserved scopes first. - $scope = explode(' ', trim($scope)); - $reservedScope = $this->getReservedScopes(); - $nonReservedScopes = array_diff($scope, $reservedScope); - if (count($nonReservedScopes) == 0) { - return true; - } else { - // Check the storage for non-reserved scopes. - $nonReservedScopes = implode(' ', $nonReservedScopes); - - return $this->storage->scopeExists($nonReservedScopes); - } - } - - public function getScopeFromRequest(RequestInterface $request) - { - // "scope" is valid if passed in either POST or QUERY - return $request->request('scope', $request->query('scope')); - } - - public function getDefaultScope($client_id = null) - { - return $this->storage->getDefaultScope($client_id); - } - - /** - * Get reserved scopes needed by the server. - * - * In case OpenID Connect is used, these scopes must include: - * 'openid', offline_access'. - * - * @return - * An array of reserved scopes. - */ - public function getReservedScopes() - { - return array('openid', 'offline_access'); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ScopeInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/ScopeInterface.php deleted file mode 100644 index 5b60f9a..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/ScopeInterface.php +++ /dev/null @@ -1,40 +0,0 @@ - 'OAuth2\Storage\AccessTokenInterface', - 'authorization_code' => 'OAuth2\Storage\AuthorizationCodeInterface', - 'client_credentials' => 'OAuth2\Storage\ClientCredentialsInterface', - 'client' => 'OAuth2\Storage\ClientInterface', - 'refresh_token' => 'OAuth2\Storage\RefreshTokenInterface', - 'user_credentials' => 'OAuth2\Storage\UserCredentialsInterface', - 'user_claims' => 'OAuth2\OpenID\Storage\UserClaimsInterface', - 'public_key' => 'OAuth2\Storage\PublicKeyInterface', - 'jwt_bearer' => 'OAuth2\Storage\JWTBearerInterface', - 'scope' => 'OAuth2\Storage\ScopeInterface', - ); - - protected $responseTypeMap = array( - 'token' => 'OAuth2\ResponseType\AccessTokenInterface', - 'code' => 'OAuth2\ResponseType\AuthorizationCodeInterface', - 'id_token' => 'OAuth2\OpenID\ResponseType\IdTokenInterface', - 'id_token token' => 'OAuth2\OpenID\ResponseType\IdTokenTokenInterface', - 'code id_token' => 'OAuth2\OpenID\ResponseType\CodeIdTokenInterface', - ); - - /** - * @param mixed $storage (array or OAuth2\Storage) - single object or array of objects implementing the - * required storage types (ClientCredentialsInterface and AccessTokenInterface as a minimum) - * @param array $config specify a different token lifetime, token header name, etc - * @param array $grantTypes An array of OAuth2\GrantType\GrantTypeInterface to use for granting access tokens - * @param array $responseTypes Response types to use. array keys should be "code" and and "token" for - * Access Token and Authorization Code response types - * @param OAuth2\TokenType\TokenTypeInterface $tokenType The token type object to use. Valid token types are "bearer" and "mac" - * @param OAuth2\ScopeInterface $scopeUtil The scope utility class to use to validate scope - * @param OAuth2\ClientAssertionType\ClientAssertionTypeInterface $clientAssertionType The method in which to verify the client identity. Default is HttpBasic - * - * @ingroup oauth2_section_7 - */ - public function __construct($storage = array(), array $config = array(), array $grantTypes = array(), array $responseTypes = array(), TokenTypeInterface $tokenType = null, ScopeInterface $scopeUtil = null, ClientAssertionTypeInterface $clientAssertionType = null) - { - $storage = is_array($storage) ? $storage : array($storage); - $this->storages = array(); - foreach ($storage as $key => $service) { - $this->addStorage($service, $key); - } - - // merge all config values. These get passed to our controller objects - $this->config = array_merge(array( - 'use_jwt_access_tokens' => false, - 'store_encrypted_token_string' => true, - 'use_openid_connect' => false, - 'id_lifetime' => 3600, - 'access_lifetime' => 3600, - 'www_realm' => 'Service', - 'token_param_name' => 'access_token', - 'token_bearer_header_name' => 'Bearer', - 'enforce_state' => true, - 'require_exact_redirect_uri' => true, - 'allow_implicit' => false, - 'allow_credentials_in_request_body' => true, - 'allow_public_clients' => true, - 'always_issue_new_refresh_token' => false, - 'unset_refresh_token_after_use' => true, - ), $config); - - foreach ($grantTypes as $key => $grantType) { - $this->addGrantType($grantType, $key); - } - - foreach ($responseTypes as $key => $responseType) { - $this->addResponseType($responseType, $key); - } - - $this->tokenType = $tokenType; - $this->scopeUtil = $scopeUtil; - $this->clientAssertionType = $clientAssertionType; - - if ($this->config['use_openid_connect']) { - $this->validateOpenIdConnect(); - } - } - - public function getAuthorizeController() - { - if (is_null($this->authorizeController)) { - $this->authorizeController = $this->createDefaultAuthorizeController(); - } - - return $this->authorizeController; - } - - public function getTokenController() - { - if (is_null($this->tokenController)) { - $this->tokenController = $this->createDefaultTokenController(); - } - - return $this->tokenController; - } - - public function getResourceController() - { - if (is_null($this->resourceController)) { - $this->resourceController = $this->createDefaultResourceController(); - } - - return $this->resourceController; - } - - public function getUserInfoController() - { - if (is_null($this->userInfoController)) { - $this->userInfoController = $this->createDefaultUserInfoController(); - } - - return $this->userInfoController; - } - - /** - * every getter deserves a setter - */ - public function setAuthorizeController(AuthorizeControllerInterface $authorizeController) - { - $this->authorizeController = $authorizeController; - } - - /** - * every getter deserves a setter - */ - public function setTokenController(TokenControllerInterface $tokenController) - { - $this->tokenController = $tokenController; - } - - /** - * every getter deserves a setter - */ - public function setResourceController(ResourceControllerInterface $resourceController) - { - $this->resourceController = $resourceController; - } - - /** - * every getter deserves a setter - */ - public function setUserInfoController(UserInfoControllerInterface $userInfoController) - { - $this->userInfoController = $userInfoController; - } - - /** - * Return claims about the authenticated end-user. - * This would be called from the "/UserInfo" endpoint as defined in the spec. - * - * @param $request - OAuth2\RequestInterface - * Request object to grant access token - * - * @param $response - OAuth2\ResponseInterface - * Response object containing error messages (failure) or user claims (success) - * - * @throws InvalidArgumentException - * @throws LogicException - * - * @see http://openid.net/specs/openid-connect-core-1_0.html#UserInfo - */ - public function handleUserInfoRequest(RequestInterface $request, ResponseInterface $response = null) - { - $this->response = is_null($response) ? new Response() : $response; - $this->getUserInfoController()->handleUserInfoRequest($request, $this->response); - - return $this->response; - } - - /** - * Grant or deny a requested access token. - * This would be called from the "/token" endpoint as defined in the spec. - * Obviously, you can call your endpoint whatever you want. - * - * @param $request - OAuth2\RequestInterface - * Request object to grant access token - * - * @param $response - OAuth2\ResponseInterface - * Response object containing error messages (failure) or access token (success) - * - * @throws InvalidArgumentException - * @throws LogicException - * - * @see http://tools.ietf.org/html/rfc6749#section-4 - * @see http://tools.ietf.org/html/rfc6749#section-10.6 - * @see http://tools.ietf.org/html/rfc6749#section-4.1.3 - * - * @ingroup oauth2_section_4 - */ - public function handleTokenRequest(RequestInterface $request, ResponseInterface $response = null) - { - $this->response = is_null($response) ? new Response() : $response; - $this->getTokenController()->handleTokenRequest($request, $this->response); - - return $this->response; - } - - public function grantAccessToken(RequestInterface $request, ResponseInterface $response = null) - { - $this->response = is_null($response) ? new Response() : $response; - $value = $this->getTokenController()->grantAccessToken($request, $this->response); - - return $value; - } - - /** - * Handle a revoke token request - * This would be called from the "/revoke" endpoint as defined in the draft Token Revocation spec - * - * @see https://tools.ietf.org/html/rfc7009#section-2 - * - * @param RequestInterface $request - * @param ResponseInterface $response - * @return Response|ResponseInterface - */ - public function handleRevokeRequest(RequestInterface $request, ResponseInterface $response = null) - { - $this->response = is_null($response) ? new Response() : $response; - $this->getTokenController()->handleRevokeRequest($request, $this->response); - - return $this->response; - } - - /** - * Redirect the user appropriately after approval. - * - * After the user has approved or denied the resource request the - * authorization server should call this function to redirect the user - * appropriately. - * - * @param $request - * The request should have the follow parameters set in the querystring: - * - response_type: The requested response: an access token, an - * authorization code, or both. - * - client_id: The client identifier as described in Section 2. - * - redirect_uri: An absolute URI to which the authorization server - * will redirect the user-agent to when the end-user authorization - * step is completed. - * - scope: (optional) The scope of the resource request expressed as a - * list of space-delimited strings. - * - state: (optional) An opaque value used by the client to maintain - * state between the request and callback. - * @param $is_authorized - * TRUE or FALSE depending on whether the user authorized the access. - * @param $user_id - * Identifier of user who authorized the client - * - * @see http://tools.ietf.org/html/rfc6749#section-4 - * - * @ingroup oauth2_section_4 - */ - public function handleAuthorizeRequest(RequestInterface $request, ResponseInterface $response, $is_authorized, $user_id = null) - { - $this->response = $response; - $this->getAuthorizeController()->handleAuthorizeRequest($request, $this->response, $is_authorized, $user_id); - - return $this->response; - } - - /** - * Pull the authorization request data out of the HTTP request. - * - The redirect_uri is OPTIONAL as per draft 20. But your implementation can enforce it - * by setting $config['enforce_redirect'] to true. - * - The state is OPTIONAL but recommended to enforce CSRF. Draft 21 states, however, that - * CSRF protection is MANDATORY. You can enforce this by setting the $config['enforce_state'] to true. - * - * The draft specifies that the parameters should be retrieved from GET, override the Response - * object to change this - * - * @return - * The authorization parameters so the authorization server can prompt - * the user for approval if valid. - * - * @see http://tools.ietf.org/html/rfc6749#section-4.1.1 - * @see http://tools.ietf.org/html/rfc6749#section-10.12 - * - * @ingroup oauth2_section_3 - */ - public function validateAuthorizeRequest(RequestInterface $request, ResponseInterface $response = null) - { - $this->response = is_null($response) ? new Response() : $response; - $value = $this->getAuthorizeController()->validateAuthorizeRequest($request, $this->response); - - return $value; - } - - public function verifyResourceRequest(RequestInterface $request, ResponseInterface $response = null, $scope = null) - { - $this->response = is_null($response) ? new Response() : $response; - $value = $this->getResourceController()->verifyResourceRequest($request, $this->response, $scope); - - return $value; - } - - public function getAccessTokenData(RequestInterface $request, ResponseInterface $response = null) - { - $this->response = is_null($response) ? new Response() : $response; - $value = $this->getResourceController()->getAccessTokenData($request, $this->response); - - return $value; - } - - public function addGrantType(GrantTypeInterface $grantType, $identifier = null) - { - if (!is_string($identifier)) { - $identifier = $grantType->getQuerystringIdentifier(); - } - - $this->grantTypes[$identifier] = $grantType; - - // persist added grant type down to TokenController - if (!is_null($this->tokenController)) { - $this->getTokenController()->addGrantType($grantType, $identifier); - } - } - - /** - * Set a storage object for the server - * - * @param $storage - * An object implementing one of the Storage interfaces - * @param $key - * If null, the storage is set to the key of each storage interface it implements - * - * @see storageMap - */ - public function addStorage($storage, $key = null) - { - // if explicitly set to a valid key, do not "magically" set below - if (isset($this->storageMap[$key])) { - if (!is_null($storage) && !$storage instanceof $this->storageMap[$key]) { - throw new \InvalidArgumentException(sprintf('storage of type "%s" must implement interface "%s"', $key, $this->storageMap[$key])); - } - $this->storages[$key] = $storage; - - // special logic to handle "client" and "client_credentials" strangeness - if ($key === 'client' && !isset($this->storages['client_credentials'])) { - if ($storage instanceof \OAuth2\Storage\ClientCredentialsInterface) { - $this->storages['client_credentials'] = $storage; - } - } elseif ($key === 'client_credentials' && !isset($this->storages['client'])) { - if ($storage instanceof \OAuth2\Storage\ClientInterface) { - $this->storages['client'] = $storage; - } - } - } elseif (!is_null($key) && !is_numeric($key)) { - throw new \InvalidArgumentException(sprintf('unknown storage key "%s", must be one of [%s]', $key, implode(', ', array_keys($this->storageMap)))); - } else { - $set = false; - foreach ($this->storageMap as $type => $interface) { - if ($storage instanceof $interface) { - $this->storages[$type] = $storage; - $set = true; - } - } - - if (!$set) { - throw new \InvalidArgumentException(sprintf('storage of class "%s" must implement one of [%s]', get_class($storage), implode(', ', $this->storageMap))); - } - } - } - - public function addResponseType(ResponseTypeInterface $responseType, $key = null) - { - $key = $this->normalizeResponseType($key); - - if (isset($this->responseTypeMap[$key])) { - if (!$responseType instanceof $this->responseTypeMap[$key]) { - throw new \InvalidArgumentException(sprintf('responseType of type "%s" must implement interface "%s"', $key, $this->responseTypeMap[$key])); - } - $this->responseTypes[$key] = $responseType; - } elseif (!is_null($key) && !is_numeric($key)) { - throw new \InvalidArgumentException(sprintf('unknown responseType key "%s", must be one of [%s]', $key, implode(', ', array_keys($this->responseTypeMap)))); - } else { - $set = false; - foreach ($this->responseTypeMap as $type => $interface) { - if ($responseType instanceof $interface) { - $this->responseTypes[$type] = $responseType; - $set = true; - } - } - - if (!$set) { - throw new \InvalidArgumentException(sprintf('Unknown response type %s. Please implement one of [%s]', get_class($responseType), implode(', ', $this->responseTypeMap))); - } - } - } - - public function getScopeUtil() - { - if (!$this->scopeUtil) { - $storage = isset($this->storages['scope']) ? $this->storages['scope'] : null; - $this->scopeUtil = new Scope($storage); - } - - return $this->scopeUtil; - } - - /** - * every getter deserves a setter - */ - public function setScopeUtil($scopeUtil) - { - $this->scopeUtil = $scopeUtil; - } - - protected function createDefaultAuthorizeController() - { - if (!isset($this->storages['client'])) { - throw new \LogicException("You must supply a storage object implementing OAuth2\Storage\ClientInterface to use the authorize server"); - } - if (0 == count($this->responseTypes)) { - $this->responseTypes = $this->getDefaultResponseTypes(); - } - if ($this->config['use_openid_connect'] && !isset($this->responseTypes['id_token'])) { - $this->responseTypes['id_token'] = $this->createDefaultIdTokenResponseType(); - if ($this->config['allow_implicit']) { - $this->responseTypes['id_token token'] = $this->createDefaultIdTokenTokenResponseType(); - } - } - - $config = array_intersect_key($this->config, array_flip(explode(' ', 'allow_implicit enforce_state require_exact_redirect_uri'))); - - if ($this->config['use_openid_connect']) { - return new OpenIDAuthorizeController($this->storages['client'], $this->responseTypes, $config, $this->getScopeUtil()); - } - - return new AuthorizeController($this->storages['client'], $this->responseTypes, $config, $this->getScopeUtil()); - } - - protected function createDefaultTokenController() - { - if (0 == count($this->grantTypes)) { - $this->grantTypes = $this->getDefaultGrantTypes(); - } - - if (is_null($this->clientAssertionType)) { - // see if HttpBasic assertion type is requred. If so, then create it from storage classes. - foreach ($this->grantTypes as $grantType) { - if (!$grantType instanceof ClientAssertionTypeInterface) { - if (!isset($this->storages['client_credentials'])) { - throw new \LogicException("You must supply a storage object implementing OAuth2\Storage\ClientCredentialsInterface to use the token server"); - } - $config = array_intersect_key($this->config, array_flip(explode(' ', 'allow_credentials_in_request_body allow_public_clients'))); - $this->clientAssertionType = new HttpBasic($this->storages['client_credentials'], $config); - break; - } - } - } - - if (!isset($this->storages['client'])) { - throw new \LogicException("You must supply a storage object implementing OAuth2\Storage\ClientInterface to use the token server"); - } - - $accessTokenResponseType = $this->getAccessTokenResponseType(); - - return new TokenController($accessTokenResponseType, $this->storages['client'], $this->grantTypes, $this->clientAssertionType, $this->getScopeUtil()); - } - - protected function createDefaultResourceController() - { - if ($this->config['use_jwt_access_tokens']) { - // overwrites access token storage with crypto token storage if "use_jwt_access_tokens" is set - if (!isset($this->storages['access_token']) || !$this->storages['access_token'] instanceof JwtAccessTokenInterface) { - $this->storages['access_token'] = $this->createDefaultJwtAccessTokenStorage(); - } - } elseif (!isset($this->storages['access_token'])) { - throw new \LogicException("You must supply a storage object implementing OAuth2\Storage\AccessTokenInterface or use JwtAccessTokens to use the resource server"); - } - - if (!$this->tokenType) { - $this->tokenType = $this->getDefaultTokenType(); - } - - $config = array_intersect_key($this->config, array('www_realm' => '')); - - return new ResourceController($this->tokenType, $this->storages['access_token'], $config, $this->getScopeUtil()); - } - - protected function createDefaultUserInfoController() - { - if ($this->config['use_jwt_access_tokens']) { - // overwrites access token storage with crypto token storage if "use_jwt_access_tokens" is set - if (!isset($this->storages['access_token']) || !$this->storages['access_token'] instanceof JwtAccessTokenInterface) { - $this->storages['access_token'] = $this->createDefaultJwtAccessTokenStorage(); - } - } elseif (!isset($this->storages['access_token'])) { - throw new \LogicException("You must supply a storage object implementing OAuth2\Storage\AccessTokenInterface or use JwtAccessTokens to use the UserInfo server"); - } - - if (!isset($this->storages['user_claims'])) { - throw new \LogicException("You must supply a storage object implementing OAuth2\OpenID\Storage\UserClaimsInterface to use the UserInfo server"); - } - - if (!$this->tokenType) { - $this->tokenType = $this->getDefaultTokenType(); - } - - $config = array_intersect_key($this->config, array('www_realm' => '')); - - return new UserInfoController($this->tokenType, $this->storages['access_token'], $this->storages['user_claims'], $config, $this->getScopeUtil()); - } - - protected function getDefaultTokenType() - { - $config = array_intersect_key($this->config, array_flip(explode(' ', 'token_param_name token_bearer_header_name'))); - - return new Bearer($config); - } - - protected function getDefaultResponseTypes() - { - $responseTypes = array(); - - if ($this->config['allow_implicit']) { - $responseTypes['token'] = $this->getAccessTokenResponseType(); - } - - if ($this->config['use_openid_connect']) { - $responseTypes['id_token'] = $this->getIdTokenResponseType(); - if ($this->config['allow_implicit']) { - $responseTypes['id_token token'] = $this->getIdTokenTokenResponseType(); - } - } - - if (isset($this->storages['authorization_code'])) { - $config = array_intersect_key($this->config, array_flip(explode(' ', 'enforce_redirect auth_code_lifetime'))); - if ($this->config['use_openid_connect']) { - if (!$this->storages['authorization_code'] instanceof OpenIDAuthorizationCodeInterface) { - throw new \LogicException("Your authorization_code storage must implement OAuth2\OpenID\Storage\AuthorizationCodeInterface to work when 'use_openid_connect' is true"); - } - $responseTypes['code'] = new OpenIDAuthorizationCodeResponseType($this->storages['authorization_code'], $config); - $responseTypes['code id_token'] = new CodeIdToken($responseTypes['code'], $responseTypes['id_token']); - } else { - $responseTypes['code'] = new AuthorizationCodeResponseType($this->storages['authorization_code'], $config); - } - } - - if (count($responseTypes) == 0) { - throw new \LogicException("You must supply an array of response_types in the constructor or implement a OAuth2\Storage\AuthorizationCodeInterface storage object or set 'allow_implicit' to true and implement a OAuth2\Storage\AccessTokenInterface storage object"); - } - - return $responseTypes; - } - - protected function getDefaultGrantTypes() - { - $grantTypes = array(); - - if (isset($this->storages['user_credentials'])) { - $grantTypes['password'] = new UserCredentials($this->storages['user_credentials']); - } - - if (isset($this->storages['client_credentials'])) { - $config = array_intersect_key($this->config, array('allow_credentials_in_request_body' => '')); - $grantTypes['client_credentials'] = new ClientCredentials($this->storages['client_credentials'], $config); - } - - if (isset($this->storages['refresh_token'])) { - $config = array_intersect_key($this->config, array_flip(explode(' ', 'always_issue_new_refresh_token unset_refresh_token_after_use'))); - $grantTypes['refresh_token'] = new RefreshToken($this->storages['refresh_token'], $config); - } - - if (isset($this->storages['authorization_code'])) { - if ($this->config['use_openid_connect']) { - if (!$this->storages['authorization_code'] instanceof OpenIDAuthorizationCodeInterface) { - throw new \LogicException("Your authorization_code storage must implement OAuth2\OpenID\Storage\AuthorizationCodeInterface to work when 'use_openid_connect' is true"); - } - $grantTypes['authorization_code'] = new OpenIDAuthorizationCodeGrantType($this->storages['authorization_code']); - } else { - $grantTypes['authorization_code'] = new AuthorizationCode($this->storages['authorization_code']); - } - } - - if (count($grantTypes) == 0) { - throw new \LogicException("Unable to build default grant types - You must supply an array of grant_types in the constructor"); - } - - return $grantTypes; - } - - protected function getAccessTokenResponseType() - { - if (isset($this->responseTypes['token'])) { - return $this->responseTypes['token']; - } - - if ($this->config['use_jwt_access_tokens']) { - return $this->createDefaultJwtAccessTokenResponseType(); - } - - return $this->createDefaultAccessTokenResponseType(); - } - - protected function getIdTokenResponseType() - { - if (isset($this->responseTypes['id_token'])) { - return $this->responseTypes['id_token']; - } - - return $this->createDefaultIdTokenResponseType(); - } - - protected function getIdTokenTokenResponseType() - { - if (isset($this->responseTypes['id_token token'])) { - return $this->responseTypes['id_token token']; - } - - return $this->createDefaultIdTokenTokenResponseType(); - } - - /** - * For Resource Controller - */ - protected function createDefaultJwtAccessTokenStorage() - { - if (!isset($this->storages['public_key'])) { - throw new \LogicException("You must supply a storage object implementing OAuth2\Storage\PublicKeyInterface to use crypto tokens"); - } - $tokenStorage = null; - if (!empty($this->config['store_encrypted_token_string']) && isset($this->storages['access_token'])) { - $tokenStorage = $this->storages['access_token']; - } - // wrap the access token storage as required. - return new JwtAccessTokenStorage($this->storages['public_key'], $tokenStorage); - } - - /** - * For Authorize and Token Controllers - */ - protected function createDefaultJwtAccessTokenResponseType() - { - if (!isset($this->storages['public_key'])) { - throw new \LogicException("You must supply a storage object implementing OAuth2\Storage\PublicKeyInterface to use crypto tokens"); - } - - $tokenStorage = null; - if (isset($this->storages['access_token'])) { - $tokenStorage = $this->storages['access_token']; - } - - $refreshStorage = null; - if (isset($this->storages['refresh_token'])) { - $refreshStorage = $this->storages['refresh_token']; - } - - $config = array_intersect_key($this->config, array_flip(explode(' ', 'store_encrypted_token_string issuer access_lifetime refresh_token_lifetime'))); - - return new JwtAccessToken($this->storages['public_key'], $tokenStorage, $refreshStorage, $config); - } - - protected function createDefaultAccessTokenResponseType() - { - if (!isset($this->storages['access_token'])) { - throw new \LogicException("You must supply a response type implementing OAuth2\ResponseType\AccessTokenInterface, or a storage object implementing OAuth2\Storage\AccessTokenInterface to use the token server"); - } - - $refreshStorage = null; - if (isset($this->storages['refresh_token'])) { - $refreshStorage = $this->storages['refresh_token']; - } - - $config = array_intersect_key($this->config, array_flip(explode(' ', 'access_lifetime refresh_token_lifetime'))); - $config['token_type'] = $this->tokenType ? $this->tokenType->getTokenType() : $this->getDefaultTokenType()->getTokenType(); - - return new AccessToken($this->storages['access_token'], $refreshStorage, $config); - } - - protected function createDefaultIdTokenResponseType() - { - if (!isset($this->storages['user_claims'])) { - throw new \LogicException("You must supply a storage object implementing OAuth2\OpenID\Storage\UserClaimsInterface to use openid connect"); - } - if (!isset($this->storages['public_key'])) { - throw new \LogicException("You must supply a storage object implementing OAuth2\Storage\PublicKeyInterface to use openid connect"); - } - - $config = array_intersect_key($this->config, array_flip(explode(' ', 'issuer id_lifetime'))); - - return new IdToken($this->storages['user_claims'], $this->storages['public_key'], $config); - } - - protected function createDefaultIdTokenTokenResponseType() - { - return new IdTokenToken($this->getAccessTokenResponseType(), $this->getIdTokenResponseType()); - } - - protected function validateOpenIdConnect() - { - $authCodeGrant = $this->getGrantType('authorization_code'); - if (!empty($authCodeGrant) && !$authCodeGrant instanceof OpenIDAuthorizationCodeGrantType) { - throw new \InvalidArgumentException('You have enabled OpenID Connect, but supplied a grant type that does not support it.'); - } - } - - protected function normalizeResponseType($name) - { - // for multiple-valued response types - make them alphabetical - if (!empty($name) && false !== strpos($name, ' ')) { - $types = explode(' ', $name); - sort($types); - $name = implode(' ', $types); - } - - return $name; - } - - public function getResponse() - { - return $this->response; - } - - public function getStorages() - { - return $this->storages; - } - - public function getStorage($name) - { - return isset($this->storages[$name]) ? $this->storages[$name] : null; - } - - public function getGrantTypes() - { - return $this->grantTypes; - } - - public function getGrantType($name) - { - return isset($this->grantTypes[$name]) ? $this->grantTypes[$name] : null; - } - - public function getResponseTypes() - { - return $this->responseTypes; - } - - public function getResponseType($name) - { - // for multiple-valued response types - make them alphabetical - $name = $this->normalizeResponseType($name); - - return isset($this->responseTypes[$name]) ? $this->responseTypes[$name] : null; - } - - public function getTokenType() - { - return $this->tokenType; - } - - public function getClientAssertionType() - { - return $this->clientAssertionType; - } - - public function setConfig($name, $value) - { - $this->config[$name] = $value; - } - - public function getConfig($name, $default = null) - { - return isset($this->config[$name]) ? $this->config[$name] : $default; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/AccessTokenInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/AccessTokenInterface.php deleted file mode 100644 index ac081bb..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/AccessTokenInterface.php +++ /dev/null @@ -1,63 +0,0 @@ - - */ -interface AccessTokenInterface -{ - /** - * Look up the supplied oauth_token from storage. - * - * We need to retrieve access token data as we create and verify tokens. - * - * @param $oauth_token - * oauth_token to be check with. - * - * @return - * An associative array as below, and return NULL if the supplied oauth_token - * is invalid: - * - expires: Stored expiration in unix timestamp. - * - client_id: (optional) Stored client identifier. - * - user_id: (optional) Stored user identifier. - * - scope: (optional) Stored scope values in space-separated string. - * - id_token: (optional) Stored id_token (if "use_openid_connect" is true). - * - * @ingroup oauth2_section_7 - */ - public function getAccessToken($oauth_token); - - /** - * Store the supplied access token values to storage. - * - * We need to store access token data as we create and verify tokens. - * - * @param $oauth_token oauth_token to be stored. - * @param $client_id client identifier to be stored. - * @param $user_id user identifier to be stored. - * @param int $expires expiration to be stored as a Unix timestamp. - * @param string $scope OPTIONAL Scopes to be stored in space-separated string. - * - * @ingroup oauth2_section_4 - */ - public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null); - - /** - * Expire an access token. - * - * This is not explicitly required in the spec, but if defined in a draft RFC for token - * revoking (RFC 7009) https://tools.ietf.org/html/rfc7009 - * - * @param $access_token - * Access token to be expired. - * - * @ingroup oauth2_section_6 - * - * @todo v2.0 include this method in interface. Omitted to maintain BC in v1.x - */ - //public function unsetAccessToken($access_token); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/AuthorizationCodeInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/AuthorizationCodeInterface.php deleted file mode 100644 index 3beb0e4..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/AuthorizationCodeInterface.php +++ /dev/null @@ -1,86 +0,0 @@ - - */ -interface AuthorizationCodeInterface -{ - /** - * The Authorization Code grant type supports a response type of "code". - * - * @var string - * @see http://tools.ietf.org/html/rfc6749#section-1.4.1 - * @see http://tools.ietf.org/html/rfc6749#section-4.2 - */ - const RESPONSE_TYPE_CODE = "code"; - - /** - * Fetch authorization code data (probably the most common grant type). - * - * Retrieve the stored data for the given authorization code. - * - * Required for OAuth2::GRANT_TYPE_AUTH_CODE. - * - * @param $code - * Authorization code to be check with. - * - * @return - * An associative array as below, and NULL if the code is invalid - * @code - * return array( - * "client_id" => CLIENT_ID, // REQUIRED Stored client identifier - * "user_id" => USER_ID, // REQUIRED Stored user identifier - * "expires" => EXPIRES, // REQUIRED Stored expiration in unix timestamp - * "redirect_uri" => REDIRECT_URI, // REQUIRED Stored redirect URI - * "scope" => SCOPE, // OPTIONAL Stored scope values in space-separated string - * ); - * @endcode - * - * @see http://tools.ietf.org/html/rfc6749#section-4.1 - * - * @ingroup oauth2_section_4 - */ - public function getAuthorizationCode($code); - - /** - * Take the provided authorization code values and store them somewhere. - * - * This function should be the storage counterpart to getAuthCode(). - * - * If storage fails for some reason, we're not currently checking for - * any sort of success/failure, so you should bail out of the script - * and provide a descriptive fail message. - * - * Required for OAuth2::GRANT_TYPE_AUTH_CODE. - * - * @param string $code Authorization code to be stored. - * @param mixed $client_id Client identifier to be stored. - * @param mixed $user_id User identifier to be stored. - * @param string $redirect_uri Redirect URI(s) to be stored in a space-separated string. - * @param int $expires Expiration to be stored as a Unix timestamp. - * @param string $scope OPTIONAL Scopes to be stored in space-separated string. - * - * @ingroup oauth2_section_4 - */ - public function setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null); - - /** - * once an Authorization Code is used, it must be exipired - * - * @see http://tools.ietf.org/html/rfc6749#section-4.1.2 - * - * The client MUST NOT use the authorization code - * more than once. If an authorization code is used more than - * once, the authorization server MUST deny the request and SHOULD - * revoke (when possible) all tokens previously issued based on - * that authorization code - * - */ - public function expireAuthorizationCode($code); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Cassandra.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Cassandra.php deleted file mode 100644 index 4c661ed..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Cassandra.php +++ /dev/null @@ -1,469 +0,0 @@ - - * composer require thobbs/phpcassa:dev-master - * - * - * Once this is done, instantiate the - * - * $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_server', array('127.0.0.1:9160')); - * - * - * Then, register the storage client: - * - * $storage = new OAuth2\Storage\Cassandra($cassandra); - * $storage->setClientDetails($client_id, $client_secret, $redirect_uri); - * - * - * @see test/lib/OAuth2/Storage/Bootstrap::getCassandraStorage - */ -class Cassandra implements AuthorizationCodeInterface, - AccessTokenInterface, - ClientCredentialsInterface, - UserCredentialsInterface, - RefreshTokenInterface, - JwtBearerInterface, - ScopeInterface, - PublicKeyInterface, - UserClaimsInterface, - OpenIDAuthorizationCodeInterface -{ - - private $cache; - - /* The cassandra client */ - protected $cassandra; - - /* Configuration array */ - protected $config; - - /** - * Cassandra Storage! uses phpCassa - * - * @param \phpcassa\ConnectionPool $cassandra - * @param array $config - */ - public function __construct($connection = array(), array $config = array()) - { - if ($connection instanceof ConnectionPool) { - $this->cassandra = $connection; - } else { - if (!is_array($connection)) { - throw new \InvalidArgumentException('First argument to OAuth2\Storage\Cassandra must be an instance of phpcassa\Connection\ConnectionPool or a configuration array'); - } - $connection = array_merge(array( - 'keyspace' => 'oauth2', - 'servers' => null, - ), $connection); - - $this->cassandra = new ConnectionPool($connection['keyspace'], $connection['servers']); - } - - $this->config = array_merge(array( - // cassandra config - 'column_family' => 'auth', - - // key names - 'client_key' => 'oauth_clients:', - 'access_token_key' => 'oauth_access_tokens:', - 'refresh_token_key' => 'oauth_refresh_tokens:', - 'code_key' => 'oauth_authorization_codes:', - 'user_key' => 'oauth_users:', - 'jwt_key' => 'oauth_jwt:', - 'scope_key' => 'oauth_scopes:', - 'public_key_key' => 'oauth_public_keys:', - ), $config); - } - - protected function getValue($key) - { - if (isset($this->cache[$key])) { - return $this->cache[$key]; - } - $cf = new ColumnFamily($this->cassandra, $this->config['column_family']); - - try { - $value = $cf->get($key, new ColumnSlice("", "")); - $value = array_shift($value); - } catch (\cassandra\NotFoundException $e) { - return false; - } - - return json_decode($value, true); - } - - protected function setValue($key, $value, $expire = 0) - { - $this->cache[$key] = $value; - - $cf = new ColumnFamily($this->cassandra, $this->config['column_family']); - - $str = json_encode($value); - if ($expire > 0) { - try { - $seconds = $expire - time(); - // __data key set as C* requires a field, note: max TTL can only be 630720000 seconds - $cf->insert($key, array('__data' => $str), null, $seconds); - } catch (\Exception $e) { - return false; - } - } else { - try { - // __data key set as C* requires a field - $cf->insert($key, array('__data' => $str)); - } catch (\Exception $e) { - return false; - } - } - - return true; - } - - protected function expireValue($key) - { - unset($this->cache[$key]); - - $cf = new ColumnFamily($this->cassandra, $this->config['column_family']); - try { - // __data key set as C* requires a field - $cf->remove($key, array('__data')); - } catch (\Exception $e) { - return false; - } - - return true; - } - - /* AuthorizationCodeInterface */ - public function getAuthorizationCode($code) - { - return $this->getValue($this->config['code_key'] . $code); - } - - public function setAuthorizationCode($authorization_code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null) - { - return $this->setValue( - $this->config['code_key'] . $authorization_code, - compact('authorization_code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope', 'id_token'), - $expires - ); - } - - public function expireAuthorizationCode($code) - { - $key = $this->config['code_key'] . $code; - unset($this->cache[$key]); - - return $this->expireValue($key); - } - - /* UserCredentialsInterface */ - public function checkUserCredentials($username, $password) - { - if ($user = $this->getUser($username)) { - return $this->checkPassword($user, $password); - } - - return false; - } - - // plaintext passwords are bad! Override this for your application - protected function checkPassword($user, $password) - { - return $user['password'] == sha1($password); - } - - public function getUserDetails($username) - { - return $this->getUser($username); - } - - public function getUser($username) - { - if (!$userInfo = $this->getValue($this->config['user_key'] . $username)) { - return false; - } - - // the default behavior is to use "username" as the user_id - return array_merge(array( - 'user_id' => $username, - ), $userInfo); - } - - public function setUser($username, $password, $first_name = null, $last_name = null) - { - $password = sha1($password); - - return $this->setValue( - $this->config['user_key'] . $username, - compact('username', 'password', 'first_name', 'last_name') - ); - } - - /* ClientCredentialsInterface */ - public function checkClientCredentials($client_id, $client_secret = null) - { - if (!$client = $this->getClientDetails($client_id)) { - return false; - } - - return isset($client['client_secret']) - && $client['client_secret'] == $client_secret; - } - - public function isPublicClient($client_id) - { - if (!$client = $this->getClientDetails($client_id)) { - return false; - } - - return empty($result['client_secret']);; - } - - /* ClientInterface */ - public function getClientDetails($client_id) - { - return $this->getValue($this->config['client_key'] . $client_id); - } - - public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null) - { - return $this->setValue( - $this->config['client_key'] . $client_id, - compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id') - ); - } - - public function checkRestrictedGrantType($client_id, $grant_type) - { - $details = $this->getClientDetails($client_id); - if (isset($details['grant_types'])) { - $grant_types = explode(' ', $details['grant_types']); - - return in_array($grant_type, (array) $grant_types); - } - - // if grant_types are not defined, then none are restricted - return true; - } - - /* RefreshTokenInterface */ - public function getRefreshToken($refresh_token) - { - return $this->getValue($this->config['refresh_token_key'] . $refresh_token); - } - - public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null) - { - return $this->setValue( - $this->config['refresh_token_key'] . $refresh_token, - compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope'), - $expires - ); - } - - public function unsetRefreshToken($refresh_token) - { - return $this->expireValue($this->config['refresh_token_key'] . $refresh_token); - } - - /* AccessTokenInterface */ - public function getAccessToken($access_token) - { - return $this->getValue($this->config['access_token_key'].$access_token); - } - - public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null) - { - return $this->setValue( - $this->config['access_token_key'].$access_token, - compact('access_token', 'client_id', 'user_id', 'expires', 'scope'), - $expires - ); - } - - public function unsetAccessToken($access_token) - { - return $this->expireValue($this->config['access_token_key'] . $access_token); - } - - /* ScopeInterface */ - public function scopeExists($scope) - { - $scope = explode(' ', $scope); - - $result = $this->getValue($this->config['scope_key'].'supported:global'); - - $supportedScope = explode(' ', (string) $result); - - return (count(array_diff($scope, $supportedScope)) == 0); - } - - public function getDefaultScope($client_id = null) - { - if (is_null($client_id) || !$result = $this->getValue($this->config['scope_key'].'default:'.$client_id)) { - $result = $this->getValue($this->config['scope_key'].'default:global'); - } - - return $result; - } - - public function setScope($scope, $client_id = null, $type = 'supported') - { - if (!in_array($type, array('default', 'supported'))) { - throw new \InvalidArgumentException('"$type" must be one of "default", "supported"'); - } - - if (is_null($client_id)) { - $key = $this->config['scope_key'].$type.':global'; - } else { - $key = $this->config['scope_key'].$type.':'.$client_id; - } - - return $this->setValue($key, $scope); - } - - /*JWTBearerInterface */ - public function getClientKey($client_id, $subject) - { - if (!$jwt = $this->getValue($this->config['jwt_key'] . $client_id)) { - return false; - } - - if (isset($jwt['subject']) && $jwt['subject'] == $subject ) { - return $jwt['key']; - } - - return null; - } - - public function setClientKey($client_id, $key, $subject = null) - { - return $this->setValue($this->config['jwt_key'] . $client_id, array( - 'key' => $key, - 'subject' => $subject - )); - } - - /*ScopeInterface */ - public function getClientScope($client_id) - { - if (!$clientDetails = $this->getClientDetails($client_id)) { - return false; - } - - if (isset($clientDetails['scope'])) { - return $clientDetails['scope']; - } - - return null; - } - - public function getJti($client_id, $subject, $audience, $expiration, $jti) - { - //TODO: Needs cassandra implementation. - throw new \Exception('getJti() for the Cassandra driver is currently unimplemented.'); - } - - public function setJti($client_id, $subject, $audience, $expiration, $jti) - { - //TODO: Needs cassandra implementation. - throw new \Exception('setJti() for the Cassandra driver is currently unimplemented.'); - } - - /* PublicKeyInterface */ - public function getPublicKey($client_id = '') - { - $public_key = $this->getValue($this->config['public_key_key'] . $client_id); - if (is_array($public_key)) { - return $public_key['public_key']; - } - $public_key = $this->getValue($this->config['public_key_key']); - if (is_array($public_key)) { - return $public_key['public_key']; - } - } - - public function getPrivateKey($client_id = '') - { - $public_key = $this->getValue($this->config['public_key_key'] . $client_id); - if (is_array($public_key)) { - return $public_key['private_key']; - } - $public_key = $this->getValue($this->config['public_key_key']); - if (is_array($public_key)) { - return $public_key['private_key']; - } - } - - public function getEncryptionAlgorithm($client_id = null) - { - $public_key = $this->getValue($this->config['public_key_key'] . $client_id); - if (is_array($public_key)) { - return $public_key['encryption_algorithm']; - } - $public_key = $this->getValue($this->config['public_key_key']); - if (is_array($public_key)) { - return $public_key['encryption_algorithm']; - } - - return 'RS256'; - } - - /* UserClaimsInterface */ - public function getUserClaims($user_id, $claims) - { - $userDetails = $this->getUserDetails($user_id); - if (!is_array($userDetails)) { - return false; - } - - $claims = explode(' ', trim($claims)); - $userClaims = array(); - - // for each requested claim, if the user has the claim, set it in the response - $validClaims = explode(' ', self::VALID_CLAIMS); - foreach ($validClaims as $validClaim) { - if (in_array($validClaim, $claims)) { - if ($validClaim == 'address') { - // address is an object with subfields - $userClaims['address'] = $this->getUserClaim($validClaim, $userDetails['address'] ?: $userDetails); - } else { - $userClaims = array_merge($userClaims, $this->getUserClaim($validClaim, $userDetails)); - } - } - } - - return $userClaims; - } - - protected function getUserClaim($claim, $userDetails) - { - $userClaims = array(); - $claimValuesString = constant(sprintf('self::%s_CLAIM_VALUES', strtoupper($claim))); - $claimValues = explode(' ', $claimValuesString); - - foreach ($claimValues as $value) { - if ($value == 'email_verified') { - $userClaims[$value] = $userDetails[$value]=='true' ? true : false; - } else { - $userClaims[$value] = isset($userDetails[$value]) ? $userDetails[$value] : null; - } - } - - return $userClaims; - } - -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/ClientCredentialsInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/ClientCredentialsInterface.php deleted file mode 100644 index 3318c69..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/ClientCredentialsInterface.php +++ /dev/null @@ -1,49 +0,0 @@ - - */ -interface ClientCredentialsInterface extends ClientInterface -{ - - /** - * Make sure that the client credentials is valid. - * - * @param $client_id - * Client identifier to be check with. - * @param $client_secret - * (optional) If a secret is required, check that they've given the right one. - * - * @return - * TRUE if the client credentials are valid, and MUST return FALSE if it isn't. - * @endcode - * - * @see http://tools.ietf.org/html/rfc6749#section-3.1 - * - * @ingroup oauth2_section_3 - */ - public function checkClientCredentials($client_id, $client_secret = null); - - /** - * Determine if the client is a "public" client, and therefore - * does not require passing credentials for certain grant types - * - * @param $client_id - * Client identifier to be check with. - * - * @return - * TRUE if the client is public, and FALSE if it isn't. - * @endcode - * - * @see http://tools.ietf.org/html/rfc6749#section-2.3 - * @see https://github.com/bshaffer/oauth2-server-php/issues/257 - * - * @ingroup oauth2_section_2 - */ - public function isPublicClient($client_id); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/ClientInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/ClientInterface.php deleted file mode 100644 index 09a5bff..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/ClientInterface.php +++ /dev/null @@ -1,66 +0,0 @@ - - */ -interface ClientInterface -{ - /** - * Get client details corresponding client_id. - * - * OAuth says we should store request URIs for each registered client. - * Implement this function to grab the stored URI for a given client id. - * - * @param $client_id - * Client identifier to be check with. - * - * @return array - * Client details. The only mandatory key in the array is "redirect_uri". - * This function MUST return FALSE if the given client does not exist or is - * invalid. "redirect_uri" can be space-delimited to allow for multiple valid uris. - * - * return array( - * "redirect_uri" => REDIRECT_URI, // REQUIRED redirect_uri registered for the client - * "client_id" => CLIENT_ID, // OPTIONAL the client id - * "grant_types" => GRANT_TYPES, // OPTIONAL an array of restricted grant types - * "user_id" => USER_ID, // OPTIONAL the user identifier associated with this client - * "scope" => SCOPE, // OPTIONAL the scopes allowed for this client - * ); - * - * - * @ingroup oauth2_section_4 - */ - public function getClientDetails($client_id); - - /** - * Get the scope associated with this client - * - * @return - * STRING the space-delineated scope list for the specified client_id - */ - public function getClientScope($client_id); - - /** - * Check restricted grant types of corresponding client identifier. - * - * If you want to restrict clients to certain grant types, override this - * function. - * - * @param $client_id - * Client identifier to be check with. - * @param $grant_type - * Grant type to be check with - * - * @return - * TRUE if the grant type is supported by this client identifier, and - * FALSE if it isn't. - * - * @ingroup oauth2_section_4 - */ - public function checkRestrictedGrantType($client_id, $grant_type); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/CouchbaseDB.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/CouchbaseDB.php deleted file mode 100755 index 1eb55f0..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/CouchbaseDB.php +++ /dev/null @@ -1,331 +0,0 @@ - - */ -class CouchbaseDB implements AuthorizationCodeInterface, - AccessTokenInterface, - ClientCredentialsInterface, - UserCredentialsInterface, - RefreshTokenInterface, - JwtBearerInterface, - OpenIDAuthorizationCodeInterface -{ - protected $db; - protected $config; - - public function __construct($connection, $config = array()) - { - if ($connection instanceof \Couchbase) { - $this->db = $connection; - } else { - if (!is_array($connection) || !is_array($connection['servers'])) { - throw new \InvalidArgumentException('First argument to OAuth2\Storage\CouchbaseDB must be an instance of Couchbase or a configuration array containing a server array'); - } - - $this->db = new \Couchbase($connection['servers'], (!isset($connection['username'])) ? '' : $connection['username'], (!isset($connection['password'])) ? '' : $connection['password'], $connection['bucket'], false); - } - - $this->config = array_merge(array( - 'client_table' => 'oauth_clients', - 'access_token_table' => 'oauth_access_tokens', - 'refresh_token_table' => 'oauth_refresh_tokens', - 'code_table' => 'oauth_authorization_codes', - 'user_table' => 'oauth_users', - 'jwt_table' => 'oauth_jwt', - ), $config); - } - - // Helper function to access couchbase item by type: - protected function getObjectByType($name,$id) - { - return json_decode($this->db->get($this->config[$name].'-'.$id),true); - } - - // Helper function to set couchbase item by type: - protected function setObjectByType($name,$id,$array) - { - $array['type'] = $name; - - return $this->db->set($this->config[$name].'-'.$id,json_encode($array)); - } - - // Helper function to delete couchbase item by type, wait for persist to at least 1 node - protected function deleteObjectByType($name,$id) - { - $this->db->delete($this->config[$name].'-'.$id,"",1); - } - - /* ClientCredentialsInterface */ - public function checkClientCredentials($client_id, $client_secret = null) - { - if ($result = $this->getObjectByType('client_table',$client_id)) { - return $result['client_secret'] == $client_secret; - } - - return false; - } - - public function isPublicClient($client_id) - { - if (!$result = $this->getObjectByType('client_table',$client_id)) { - return false; - } - - return empty($result['client_secret']); - } - - /* ClientInterface */ - public function getClientDetails($client_id) - { - $result = $this->getObjectByType('client_table',$client_id); - - return is_null($result) ? false : $result; - } - - public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null) - { - if ($this->getClientDetails($client_id)) { - - $this->setObjectByType('client_table',$client_id, array( - 'client_id' => $client_id, - 'client_secret' => $client_secret, - 'redirect_uri' => $redirect_uri, - 'grant_types' => $grant_types, - 'scope' => $scope, - 'user_id' => $user_id, - )); - } else { - $this->setObjectByType('client_table',$client_id, array( - 'client_id' => $client_id, - 'client_secret' => $client_secret, - 'redirect_uri' => $redirect_uri, - 'grant_types' => $grant_types, - 'scope' => $scope, - 'user_id' => $user_id, - )); - } - - return true; - } - - public function checkRestrictedGrantType($client_id, $grant_type) - { - $details = $this->getClientDetails($client_id); - if (isset($details['grant_types'])) { - $grant_types = explode(' ', $details['grant_types']); - - return in_array($grant_type, $grant_types); - } - - // if grant_types are not defined, then none are restricted - return true; - } - - /* AccessTokenInterface */ - public function getAccessToken($access_token) - { - $token = $this->getObjectByType('access_token_table',$access_token); - - return is_null($token) ? false : $token; - } - - public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null) - { - // if it exists, update it. - if ($this->getAccessToken($access_token)) { - $this->setObjectByType('access_token_table',$access_token, array( - 'access_token' => $access_token, - 'client_id' => $client_id, - 'expires' => $expires, - 'user_id' => $user_id, - 'scope' => $scope - )); - } else { - $this->setObjectByType('access_token_table',$access_token, array( - 'access_token' => $access_token, - 'client_id' => $client_id, - 'expires' => $expires, - 'user_id' => $user_id, - 'scope' => $scope - )); - } - - return true; - } - - /* AuthorizationCodeInterface */ - public function getAuthorizationCode($code) - { - $code = $this->getObjectByType('code_table',$code); - - return is_null($code) ? false : $code; - } - - public function setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null) - { - // if it exists, update it. - if ($this->getAuthorizationCode($code)) { - $this->setObjectByType('code_table',$code, array( - 'authorization_code' => $code, - 'client_id' => $client_id, - 'user_id' => $user_id, - 'redirect_uri' => $redirect_uri, - 'expires' => $expires, - 'scope' => $scope, - 'id_token' => $id_token, - )); - } else { - $this->setObjectByType('code_table',$code,array( - 'authorization_code' => $code, - 'client_id' => $client_id, - 'user_id' => $user_id, - 'redirect_uri' => $redirect_uri, - 'expires' => $expires, - 'scope' => $scope, - 'id_token' => $id_token, - )); - } - - return true; - } - - public function expireAuthorizationCode($code) - { - $this->deleteObjectByType('code_table',$code); - - return true; - } - - /* UserCredentialsInterface */ - public function checkUserCredentials($username, $password) - { - if ($user = $this->getUser($username)) { - return $this->checkPassword($user, $password); - } - - return false; - } - - public function getUserDetails($username) - { - if ($user = $this->getUser($username)) { - $user['user_id'] = $user['username']; - } - - return $user; - } - - /* RefreshTokenInterface */ - public function getRefreshToken($refresh_token) - { - $token = $this->getObjectByType('refresh_token_table',$refresh_token); - - return is_null($token) ? false : $token; - } - - public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null) - { - $this->setObjectByType('refresh_token_table',$refresh_token, array( - 'refresh_token' => $refresh_token, - 'client_id' => $client_id, - 'user_id' => $user_id, - 'expires' => $expires, - 'scope' => $scope - )); - - return true; - } - - public function unsetRefreshToken($refresh_token) - { - $this->deleteObjectByType('refresh_token_table',$refresh_token); - - return true; - } - - // plaintext passwords are bad! Override this for your application - protected function checkPassword($user, $password) - { - return $user['password'] == $password; - } - - public function getUser($username) - { - $result = $this->getObjectByType('user_table',$username); - - return is_null($result) ? false : $result; - } - - public function setUser($username, $password, $firstName = null, $lastName = null) - { - if ($this->getUser($username)) { - $this->setObjectByType('user_table',$username, array( - 'username' => $username, - 'password' => $password, - 'first_name' => $firstName, - 'last_name' => $lastName - )); - - } else { - $this->setObjectByType('user_table',$username, array( - 'username' => $username, - 'password' => $password, - 'first_name' => $firstName, - 'last_name' => $lastName - )); - - } - - return true; - } - - public function getClientKey($client_id, $subject) - { - if (!$jwt = $this->getObjectByType('jwt_table',$client_id)) { - return false; - } - - if (isset($jwt['subject']) && $jwt['subject'] == $subject) { - return $jwt['key']; - } - - return false; - } - - public function getClientScope($client_id) - { - if (!$clientDetails = $this->getClientDetails($client_id)) { - return false; - } - - if (isset($clientDetails['scope'])) { - return $clientDetails['scope']; - } - - return null; - } - - public function getJti($client_id, $subject, $audience, $expiration, $jti) - { - //TODO: Needs couchbase implementation. - throw new \Exception('getJti() for the Couchbase driver is currently unimplemented.'); - } - - public function setJti($client_id, $subject, $audience, $expiration, $jti) - { - //TODO: Needs couchbase implementation. - throw new \Exception('setJti() for the Couchbase driver is currently unimplemented.'); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/DynamoDB.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/DynamoDB.php deleted file mode 100644 index 596a31a..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/DynamoDB.php +++ /dev/null @@ -1,528 +0,0 @@ - - * composer require aws/aws-sdk-php:dev-master - * - * - * Once this is done, instantiate the DynamoDB client - * - * $storage = new OAuth2\Storage\Dynamodb(array("key" => "YOURKEY", "secret" => "YOURSECRET", "region" => "YOURREGION")); - * - * - * Table : - * - oauth_access_tokens (primary hash key : access_token) - * - oauth_authorization_codes (primary hash key : authorization_code) - * - oauth_clients (primary hash key : client_id) - * - oauth_jwt (primary hash key : client_id, primary range key : subject) - * - oauth_public_keys (primary hash key : client_id) - * - oauth_refresh_tokens (primary hash key : refresh_token) - * - oauth_scopes (primary hash key : scope, secondary index : is_default-index hash key is_default) - * - oauth_users (primary hash key : username) - * - * @author Frederic AUGUSTE - */ -class DynamoDB implements - AuthorizationCodeInterface, - AccessTokenInterface, - ClientCredentialsInterface, - UserCredentialsInterface, - RefreshTokenInterface, - JwtBearerInterface, - ScopeInterface, - PublicKeyInterface, - UserClaimsInterface, - OpenIDAuthorizationCodeInterface -{ - protected $client; - protected $config; - - public function __construct($connection, $config = array()) - { - if (!($connection instanceof DynamoDbClient)) { - if (!is_array($connection)) { - throw new \InvalidArgumentException('First argument to OAuth2\Storage\Dynamodb must be an instance a configuration array containt key, secret, region'); - } - if (!array_key_exists("key",$connection) || !array_key_exists("secret",$connection) || !array_key_exists("region",$connection) ) { - throw new \InvalidArgumentException('First argument to OAuth2\Storage\Dynamodb must be an instance a configuration array containt key, secret, region'); - } - $this->client = DynamoDbClient::factory(array( - 'key' => $connection["key"], - 'secret' => $connection["secret"], - 'region' =>$connection["region"] - )); - } else { - $this->client = $connection; - } - - $this->config = array_merge(array( - 'client_table' => 'oauth_clients', - 'access_token_table' => 'oauth_access_tokens', - 'refresh_token_table' => 'oauth_refresh_tokens', - 'code_table' => 'oauth_authorization_codes', - 'user_table' => 'oauth_users', - 'jwt_table' => 'oauth_jwt', - 'scope_table' => 'oauth_scopes', - 'public_key_table' => 'oauth_public_keys', - ), $config); - } - - /* OAuth2\Storage\ClientCredentialsInterface */ - public function checkClientCredentials($client_id, $client_secret = null) - { - $result = $this->client->getItem(array( - "TableName"=> $this->config['client_table'], - "Key" => array('client_id' => array('S' => $client_id)) - )); - - return $result->count()==1 && $result["Item"]["client_secret"]["S"] == $client_secret; - } - - public function isPublicClient($client_id) - { - $result = $this->client->getItem(array( - "TableName"=> $this->config['client_table'], - "Key" => array('client_id' => array('S' => $client_id)) - )); - - if ($result->count()==0) { - return false ; - } - - return empty($result["Item"]["client_secret"]); - } - - /* OAuth2\Storage\ClientInterface */ - public function getClientDetails($client_id) - { - $result = $this->client->getItem(array( - "TableName"=> $this->config['client_table'], - "Key" => array('client_id' => array('S' => $client_id)) - )); - if ($result->count()==0) { - return false ; - } - $result = $this->dynamo2array($result); - foreach (array('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id') as $key => $val) { - if (!array_key_exists ($val, $result)) { - $result[$val] = null; - } - } - - return $result; - } - - public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null) - { - $clientData = compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id'); - $clientData = array_filter($clientData, function ($value) { return !is_null($value); }); - - $result = $this->client->putItem(array( - 'TableName' => $this->config['client_table'], - 'Item' => $this->client->formatAttributes($clientData) - )); - - return true; - } - - public function checkRestrictedGrantType($client_id, $grant_type) - { - $details = $this->getClientDetails($client_id); - if (isset($details['grant_types'])) { - $grant_types = explode(' ', $details['grant_types']); - - return in_array($grant_type, (array) $grant_types); - } - - // if grant_types are not defined, then none are restricted - return true; - } - - /* OAuth2\Storage\AccessTokenInterface */ - public function getAccessToken($access_token) - { - $result = $this->client->getItem(array( - "TableName"=> $this->config['access_token_table'], - "Key" => array('access_token' => array('S' => $access_token)) - )); - if ($result->count()==0) { - return false ; - } - $token = $this->dynamo2array($result); - if (array_key_exists ('expires', $token)) { - $token['expires'] = strtotime($token['expires']); - } - - return $token; - } - - public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null) - { - // convert expires to datestring - $expires = date('Y-m-d H:i:s', $expires); - - $clientData = compact('access_token', 'client_id', 'user_id', 'expires', 'scope'); - $clientData = array_filter($clientData, function ($value) { return !empty($value); }); - - $result = $this->client->putItem(array( - 'TableName' => $this->config['access_token_table'], - 'Item' => $this->client->formatAttributes($clientData) - )); - - return true; - - } - - public function unsetAccessToken($access_token) - { - $result = $this->client->deleteItem(array( - 'TableName' => $this->config['access_token_table'], - 'Key' => $this->client->formatAttributes(array("access_token" => $access_token)) - )); - - return true; - } - - /* OAuth2\Storage\AuthorizationCodeInterface */ - public function getAuthorizationCode($code) - { - $result = $this->client->getItem(array( - "TableName"=> $this->config['code_table'], - "Key" => array('authorization_code' => array('S' => $code)) - )); - if ($result->count()==0) { - return false ; - } - $token = $this->dynamo2array($result); - if (!array_key_exists("id_token", $token )) { - $token['id_token'] = null; - } - $token['expires'] = strtotime($token['expires']); - - return $token; - - } - - public function setAuthorizationCode($authorization_code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null) - { - // convert expires to datestring - $expires = date('Y-m-d H:i:s', $expires); - - $clientData = compact('authorization_code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'id_token', 'scope'); - $clientData = array_filter($clientData, function ($value) { return !empty($value); }); - - $result = $this->client->putItem(array( - 'TableName' => $this->config['code_table'], - 'Item' => $this->client->formatAttributes($clientData) - )); - - return true; - } - - public function expireAuthorizationCode($code) - { - - $result = $this->client->deleteItem(array( - 'TableName' => $this->config['code_table'], - 'Key' => $this->client->formatAttributes(array("authorization_code" => $code)) - )); - - return true; - } - - /* OAuth2\Storage\UserCredentialsInterface */ - public function checkUserCredentials($username, $password) - { - if ($user = $this->getUser($username)) { - return $this->checkPassword($user, $password); - } - - return false; - } - - public function getUserDetails($username) - { - return $this->getUser($username); - } - - /* UserClaimsInterface */ - public function getUserClaims($user_id, $claims) - { - if (!$userDetails = $this->getUserDetails($user_id)) { - return false; - } - - $claims = explode(' ', trim($claims)); - $userClaims = array(); - - // for each requested claim, if the user has the claim, set it in the response - $validClaims = explode(' ', self::VALID_CLAIMS); - foreach ($validClaims as $validClaim) { - if (in_array($validClaim, $claims)) { - if ($validClaim == 'address') { - // address is an object with subfields - $userClaims['address'] = $this->getUserClaim($validClaim, $userDetails['address'] ?: $userDetails); - } else { - $userClaims = array_merge($userClaims, $this->getUserClaim($validClaim, $userDetails)); - } - } - } - - return $userClaims; - } - - protected function getUserClaim($claim, $userDetails) - { - $userClaims = array(); - $claimValuesString = constant(sprintf('self::%s_CLAIM_VALUES', strtoupper($claim))); - $claimValues = explode(' ', $claimValuesString); - - foreach ($claimValues as $value) { - if ($value == 'email_verified') { - $userClaims[$value] = $userDetails[$value]=='true' ? true : false; - } else { - $userClaims[$value] = isset($userDetails[$value]) ? $userDetails[$value] : null; - } - } - - return $userClaims; - } - - /* OAuth2\Storage\RefreshTokenInterface */ - public function getRefreshToken($refresh_token) - { - $result = $this->client->getItem(array( - "TableName"=> $this->config['refresh_token_table'], - "Key" => array('refresh_token' => array('S' => $refresh_token)) - )); - if ($result->count()==0) { - return false ; - } - $token = $this->dynamo2array($result); - $token['expires'] = strtotime($token['expires']); - - return $token; - } - - public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null) - { - // convert expires to datestring - $expires = date('Y-m-d H:i:s', $expires); - - $clientData = compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope'); - $clientData = array_filter($clientData, function ($value) { return !empty($value); }); - - $result = $this->client->putItem(array( - 'TableName' => $this->config['refresh_token_table'], - 'Item' => $this->client->formatAttributes($clientData) - )); - - return true; - } - - public function unsetRefreshToken($refresh_token) - { - $result = $this->client->deleteItem(array( - 'TableName' => $this->config['refresh_token_table'], - 'Key' => $this->client->formatAttributes(array("refresh_token" => $refresh_token)) - )); - - return true; - } - - // plaintext passwords are bad! Override this for your application - protected function checkPassword($user, $password) - { - return $user['password'] == sha1($password); - } - - public function getUser($username) - { - $result = $this->client->getItem(array( - "TableName"=> $this->config['user_table'], - "Key" => array('username' => array('S' => $username)) - )); - if ($result->count()==0) { - return false ; - } - $token = $this->dynamo2array($result); - $token['user_id'] = $username; - - return $token; - } - - public function setUser($username, $password, $first_name = null, $last_name = null) - { - // do not store in plaintext - $password = sha1($password); - - $clientData = compact('username', 'password', 'first_name', 'last_name'); - $clientData = array_filter($clientData, function ($value) { return !is_null($value); }); - - $result = $this->client->putItem(array( - 'TableName' => $this->config['user_table'], - 'Item' => $this->client->formatAttributes($clientData) - )); - - return true; - - } - - /* ScopeInterface */ - public function scopeExists($scope) - { - $scope = explode(' ', $scope); - $scope_query = array(); - $count = 0; - foreach ($scope as $key => $val) { - $result = $this->client->query(array( - 'TableName' => $this->config['scope_table'], - 'Select' => 'COUNT', - 'KeyConditions' => array( - 'scope' => array( - 'AttributeValueList' => array(array('S' => $val)), - 'ComparisonOperator' => 'EQ' - ) - ) - )); - $count += $result['Count']; - } - - return $count == count($scope); - } - - public function getDefaultScope($client_id = null) - { - - $result = $this->client->query(array( - 'TableName' => $this->config['scope_table'], - 'IndexName' => 'is_default-index', - 'Select' => 'ALL_ATTRIBUTES', - 'KeyConditions' => array( - 'is_default' => array( - 'AttributeValueList' => array(array('S' => 'true')), - 'ComparisonOperator' => 'EQ', - ), - ) - )); - $defaultScope = array(); - if ($result->count() > 0) { - $array = $result->toArray(); - foreach ($array["Items"] as $item) { - $defaultScope[] = $item['scope']['S']; - } - - return empty($defaultScope) ? null : implode(' ', $defaultScope); - } - - return null; - } - - /* JWTBearerInterface */ - public function getClientKey($client_id, $subject) - { - $result = $this->client->getItem(array( - "TableName"=> $this->config['jwt_table'], - "Key" => array('client_id' => array('S' => $client_id), 'subject' => array('S' => $subject)) - )); - if ($result->count()==0) { - return false ; - } - $token = $this->dynamo2array($result); - - return $token['public_key']; - } - - public function getClientScope($client_id) - { - if (!$clientDetails = $this->getClientDetails($client_id)) { - return false; - } - - if (isset($clientDetails['scope'])) { - return $clientDetails['scope']; - } - - return null; - } - - public function getJti($client_id, $subject, $audience, $expires, $jti) - { - //TODO not use. - } - - public function setJti($client_id, $subject, $audience, $expires, $jti) - { - //TODO not use. - } - - /* PublicKeyInterface */ - public function getPublicKey($client_id = '0') - { - - $result = $this->client->getItem(array( - "TableName"=> $this->config['public_key_table'], - "Key" => array('client_id' => array('S' => $client_id)) - )); - if ($result->count()==0) { - return false ; - } - $token = $this->dynamo2array($result); - - return $token['public_key']; - - } - - public function getPrivateKey($client_id = '0') - { - $result = $this->client->getItem(array( - "TableName"=> $this->config['public_key_table'], - "Key" => array('client_id' => array('S' => $client_id)) - )); - if ($result->count()==0) { - return false ; - } - $token = $this->dynamo2array($result); - - return $token['private_key']; - } - - public function getEncryptionAlgorithm($client_id = null) - { - $result = $this->client->getItem(array( - "TableName"=> $this->config['public_key_table'], - "Key" => array('client_id' => array('S' => $client_id)) - )); - if ($result->count()==0) { - return 'RS256' ; - } - $token = $this->dynamo2array($result); - - return $token['encryption_algorithm']; - } - - /** - * Transform dynamodb resultset to an array. - * @param $dynamodbResult - * @return $array - */ - private function dynamo2array($dynamodbResult) - { - $result = array(); - foreach ($dynamodbResult["Item"] as $key => $val) { - $result[$key] = $val["S"]; - $result[] = $val["S"]; - } - - return $result; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/JwtAccessToken.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/JwtAccessToken.php deleted file mode 100644 index 75b49d3..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/JwtAccessToken.php +++ /dev/null @@ -1,88 +0,0 @@ - - */ -class JwtAccessToken implements JwtAccessTokenInterface -{ - protected $publicKeyStorage; - protected $tokenStorage; - protected $encryptionUtil; - - /** - * @param OAuth2\Encryption\PublicKeyInterface $publicKeyStorage the public key encryption to use - * @param OAuth2\Storage\AccessTokenInterface $tokenStorage OPTIONAL persist the access token to another storage. This is useful if - * you want to retain access token grant information somewhere, but - * is not necessary when using this grant type. - * @param OAuth2\Encryption\EncryptionInterface $encryptionUtil OPTIONAL class to use for "encode" and "decode" functions. - */ - public function __construct(PublicKeyInterface $publicKeyStorage, AccessTokenInterface $tokenStorage = null, EncryptionInterface $encryptionUtil = null) - { - $this->publicKeyStorage = $publicKeyStorage; - $this->tokenStorage = $tokenStorage; - if (is_null($encryptionUtil)) { - $encryptionUtil = new Jwt; - } - $this->encryptionUtil = $encryptionUtil; - } - - public function getAccessToken($oauth_token) - { - // just decode the token, don't verify - if (!$tokenData = $this->encryptionUtil->decode($oauth_token, null, false)) { - return false; - } - - $client_id = isset($tokenData['aud']) ? $tokenData['aud'] : null; - $public_key = $this->publicKeyStorage->getPublicKey($client_id); - $algorithm = $this->publicKeyStorage->getEncryptionAlgorithm($client_id); - - // now that we have the client_id, verify the token - if (false === $this->encryptionUtil->decode($oauth_token, $public_key, array($algorithm))) { - return false; - } - - // normalize the JWT claims to the format expected by other components in this library - return $this->convertJwtToOAuth2($tokenData); - } - - public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null) - { - if ($this->tokenStorage) { - return $this->tokenStorage->setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope); - } - } - - public function unsetAccessToken($access_token) - { - if ($this->tokenStorage) { - return $this->tokenStorage->unsetAccessToken($access_token); - } - } - - - // converts a JWT access token into an OAuth2-friendly format - protected function convertJwtToOAuth2($tokenData) - { - $keyMapping = array( - 'aud' => 'client_id', - 'exp' => 'expires', - 'sub' => 'user_id' - ); - - foreach ($keyMapping as $jwtKey => $oauth2Key) { - if (isset($tokenData[$jwtKey])) { - $tokenData[$oauth2Key] = $tokenData[$jwtKey]; - unset($tokenData[$jwtKey]); - } - } - - return $tokenData; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/JwtAccessTokenInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/JwtAccessTokenInterface.php deleted file mode 100644 index 3abb2aa..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/JwtAccessTokenInterface.php +++ /dev/null @@ -1,14 +0,0 @@ - - */ -interface JwtAccessTokenInterface extends AccessTokenInterface -{ - -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/JwtBearerInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/JwtBearerInterface.php deleted file mode 100644 index c83aa72..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/JwtBearerInterface.php +++ /dev/null @@ -1,74 +0,0 @@ - - */ -interface JwtBearerInterface -{ - /** - * Get the public key associated with a client_id - * - * @param $client_id - * Client identifier to be checked with. - * - * @return - * STRING Return the public key for the client_id if it exists, and MUST return FALSE if it doesn't. - */ - public function getClientKey($client_id, $subject); - - /** - * Get a jti (JSON token identifier) by matching against the client_id, subject, audience and expiration. - * - * @param $client_id - * Client identifier to match. - * - * @param $subject - * The subject to match. - * - * @param $audience - * The audience to match. - * - * @param $expiration - * The expiration of the jti. - * - * @param $jti - * The jti to match. - * - * @return - * An associative array as below, and return NULL if the jti does not exist. - * - issuer: Stored client identifier. - * - subject: Stored subject. - * - audience: Stored audience. - * - expires: Stored expiration in unix timestamp. - * - jti: The stored jti. - */ - public function getJti($client_id, $subject, $audience, $expiration, $jti); - - /** - * Store a used jti so that we can check against it to prevent replay attacks. - * @param $client_id - * Client identifier to insert. - * - * @param $subject - * The subject to insert. - * - * @param $audience - * The audience to insert. - * - * @param $expiration - * The expiration of the jti. - * - * @param $jti - * The jti to insert. - */ - public function setJti($client_id, $subject, $audience, $expiration, $jti); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Memory.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Memory.php deleted file mode 100644 index 4f0859d..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Memory.php +++ /dev/null @@ -1,369 +0,0 @@ - - */ -class Memory implements AuthorizationCodeInterface, - UserCredentialsInterface, - UserClaimsInterface, - AccessTokenInterface, - ClientCredentialsInterface, - RefreshTokenInterface, - JwtBearerInterface, - ScopeInterface, - PublicKeyInterface, - OpenIDAuthorizationCodeInterface -{ - public $authorizationCodes; - public $userCredentials; - public $clientCredentials; - public $refreshTokens; - public $accessTokens; - public $jwt; - public $jti; - public $supportedScopes; - public $defaultScope; - public $keys; - - public function __construct($params = array()) - { - $params = array_merge(array( - 'authorization_codes' => array(), - 'user_credentials' => array(), - 'client_credentials' => array(), - 'refresh_tokens' => array(), - 'access_tokens' => array(), - 'jwt' => array(), - 'jti' => array(), - 'default_scope' => null, - 'supported_scopes' => array(), - 'keys' => array(), - ), $params); - - $this->authorizationCodes = $params['authorization_codes']; - $this->userCredentials = $params['user_credentials']; - $this->clientCredentials = $params['client_credentials']; - $this->refreshTokens = $params['refresh_tokens']; - $this->accessTokens = $params['access_tokens']; - $this->jwt = $params['jwt']; - $this->jti = $params['jti']; - $this->supportedScopes = $params['supported_scopes']; - $this->defaultScope = $params['default_scope']; - $this->keys = $params['keys']; - } - - /* AuthorizationCodeInterface */ - public function getAuthorizationCode($code) - { - if (!isset($this->authorizationCodes[$code])) { - return false; - } - - return array_merge(array( - 'authorization_code' => $code, - ), $this->authorizationCodes[$code]); - } - - public function setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null) - { - $this->authorizationCodes[$code] = compact('code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope', 'id_token'); - - return true; - } - - public function setAuthorizationCodes($authorization_codes) - { - $this->authorizationCodes = $authorization_codes; - } - - public function expireAuthorizationCode($code) - { - unset($this->authorizationCodes[$code]); - } - - /* UserCredentialsInterface */ - public function checkUserCredentials($username, $password) - { - $userDetails = $this->getUserDetails($username); - - return $userDetails && $userDetails['password'] && $userDetails['password'] === $password; - } - - public function setUser($username, $password, $firstName = null, $lastName = null) - { - $this->userCredentials[$username] = array( - 'password' => $password, - 'first_name' => $firstName, - 'last_name' => $lastName, - ); - - return true; - } - - public function getUserDetails($username) - { - if (!isset($this->userCredentials[$username])) { - return false; - } - - return array_merge(array( - 'user_id' => $username, - 'password' => null, - 'first_name' => null, - 'last_name' => null, - ), $this->userCredentials[$username]); - } - - /* UserClaimsInterface */ - public function getUserClaims($user_id, $claims) - { - if (!$userDetails = $this->getUserDetails($user_id)) { - return false; - } - - $claims = explode(' ', trim($claims)); - $userClaims = array(); - - // for each requested claim, if the user has the claim, set it in the response - $validClaims = explode(' ', self::VALID_CLAIMS); - foreach ($validClaims as $validClaim) { - if (in_array($validClaim, $claims)) { - if ($validClaim == 'address') { - // address is an object with subfields - $userClaims['address'] = $this->getUserClaim($validClaim, $userDetails['address'] ?: $userDetails); - } else { - $userClaims = array_merge($this->getUserClaim($validClaim, $userDetails)); - } - } - } - - return $userClaims; - } - - protected function getUserClaim($claim, $userDetails) - { - $userClaims = array(); - $claimValuesString = constant(sprintf('self::%s_CLAIM_VALUES', strtoupper($claim))); - $claimValues = explode(' ', $claimValuesString); - - foreach ($claimValues as $value) { - $userClaims[$value] = isset($userDetails[$value]) ? $userDetails[$value] : null; - } - - return $userClaims; - } - - /* ClientCredentialsInterface */ - public function checkClientCredentials($client_id, $client_secret = null) - { - return isset($this->clientCredentials[$client_id]['client_secret']) && $this->clientCredentials[$client_id]['client_secret'] === $client_secret; - } - - public function isPublicClient($client_id) - { - if (!isset($this->clientCredentials[$client_id])) { - return false; - } - - return empty($this->clientCredentials[$client_id]['client_secret']); - } - - /* ClientInterface */ - public function getClientDetails($client_id) - { - if (!isset($this->clientCredentials[$client_id])) { - return false; - } - - $clientDetails = array_merge(array( - 'client_id' => $client_id, - 'client_secret' => null, - 'redirect_uri' => null, - 'scope' => null, - ), $this->clientCredentials[$client_id]); - - return $clientDetails; - } - - public function checkRestrictedGrantType($client_id, $grant_type) - { - if (isset($this->clientCredentials[$client_id]['grant_types'])) { - $grant_types = explode(' ', $this->clientCredentials[$client_id]['grant_types']); - - return in_array($grant_type, $grant_types); - } - - // if grant_types are not defined, then none are restricted - return true; - } - - public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null) - { - $this->clientCredentials[$client_id] = array( - 'client_id' => $client_id, - 'client_secret' => $client_secret, - 'redirect_uri' => $redirect_uri, - 'grant_types' => $grant_types, - 'scope' => $scope, - 'user_id' => $user_id, - ); - - return true; - } - - /* RefreshTokenInterface */ - public function getRefreshToken($refresh_token) - { - return isset($this->refreshTokens[$refresh_token]) ? $this->refreshTokens[$refresh_token] : false; - } - - public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null) - { - $this->refreshTokens[$refresh_token] = compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope'); - - return true; - } - - public function unsetRefreshToken($refresh_token) - { - unset($this->refreshTokens[$refresh_token]); - } - - public function setRefreshTokens($refresh_tokens) - { - $this->refreshTokens = $refresh_tokens; - } - - /* AccessTokenInterface */ - public function getAccessToken($access_token) - { - return isset($this->accessTokens[$access_token]) ? $this->accessTokens[$access_token] : false; - } - - public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null, $id_token = null) - { - $this->accessTokens[$access_token] = compact('access_token', 'client_id', 'user_id', 'expires', 'scope', 'id_token'); - - return true; - } - - public function unsetAccessToken($access_token) - { - unset($this->accessTokens[$access_token]); - } - - public function scopeExists($scope) - { - $scope = explode(' ', trim($scope)); - - return (count(array_diff($scope, $this->supportedScopes)) == 0); - } - - public function getDefaultScope($client_id = null) - { - return $this->defaultScope; - } - - /*JWTBearerInterface */ - public function getClientKey($client_id, $subject) - { - if (isset($this->jwt[$client_id])) { - $jwt = $this->jwt[$client_id]; - if ($jwt) { - if ($jwt["subject"] == $subject) { - return $jwt["key"]; - } - } - } - - return false; - } - - public function getClientScope($client_id) - { - if (!$clientDetails = $this->getClientDetails($client_id)) { - return false; - } - - if (isset($clientDetails['scope'])) { - return $clientDetails['scope']; - } - - return null; - } - - public function getJti($client_id, $subject, $audience, $expires, $jti) - { - foreach ($this->jti as $storedJti) { - if ($storedJti['issuer'] == $client_id && $storedJti['subject'] == $subject && $storedJti['audience'] == $audience && $storedJti['expires'] == $expires && $storedJti['jti'] == $jti) { - return array( - 'issuer' => $storedJti['issuer'], - 'subject' => $storedJti['subject'], - 'audience' => $storedJti['audience'], - 'expires' => $storedJti['expires'], - 'jti' => $storedJti['jti'] - ); - } - } - - return null; - } - - public function setJti($client_id, $subject, $audience, $expires, $jti) - { - $this->jti[] = array('issuer' => $client_id, 'subject' => $subject, 'audience' => $audience, 'expires' => $expires, 'jti' => $jti); - } - - /*PublicKeyInterface */ - public function getPublicKey($client_id = null) - { - if (isset($this->keys[$client_id])) { - return $this->keys[$client_id]['public_key']; - } - - // use a global encryption pair - if (isset($this->keys['public_key'])) { - return $this->keys['public_key']; - } - - return false; - } - - public function getPrivateKey($client_id = null) - { - if (isset($this->keys[$client_id])) { - return $this->keys[$client_id]['private_key']; - } - - // use a global encryption pair - if (isset($this->keys['private_key'])) { - return $this->keys['private_key']; - } - - return false; - } - - public function getEncryptionAlgorithm($client_id = null) - { - if (isset($this->keys[$client_id]['encryption_algorithm'])) { - return $this->keys[$client_id]['encryption_algorithm']; - } - - // use a global encryption algorithm - if (isset($this->keys['encryption_algorithm'])) { - return $this->keys['encryption_algorithm']; - } - - return 'RS256'; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Mongo.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Mongo.php deleted file mode 100644 index 9510447..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Mongo.php +++ /dev/null @@ -1,333 +0,0 @@ - - */ -class Mongo implements AuthorizationCodeInterface, - AccessTokenInterface, - ClientCredentialsInterface, - UserCredentialsInterface, - RefreshTokenInterface, - JwtBearerInterface, - OpenIDAuthorizationCodeInterface -{ - protected $db; - protected $config; - - public function __construct($connection, $config = array()) - { - if ($connection instanceof \MongoDB) { - $this->db = $connection; - } else { - if (!is_array($connection)) { - throw new \InvalidArgumentException('First argument to OAuth2\Storage\Mongo must be an instance of MongoDB or a configuration array'); - } - $server = sprintf('mongodb://%s:%d', $connection['host'], $connection['port']); - $m = new \MongoClient($server); - $this->db = $m->{$connection['database']}; - } - - $this->config = array_merge(array( - 'client_table' => 'oauth_clients', - 'access_token_table' => 'oauth_access_tokens', - 'refresh_token_table' => 'oauth_refresh_tokens', - 'code_table' => 'oauth_authorization_codes', - 'user_table' => 'oauth_users', - 'jwt_table' => 'oauth_jwt', - ), $config); - } - - // Helper function to access a MongoDB collection by `type`: - protected function collection($name) - { - return $this->db->{$this->config[$name]}; - } - - /* ClientCredentialsInterface */ - public function checkClientCredentials($client_id, $client_secret = null) - { - if ($result = $this->collection('client_table')->findOne(array('client_id' => $client_id))) { - return $result['client_secret'] == $client_secret; - } - - return false; - } - - public function isPublicClient($client_id) - { - if (!$result = $this->collection('client_table')->findOne(array('client_id' => $client_id))) { - return false; - } - - return empty($result['client_secret']); - } - - /* ClientInterface */ - public function getClientDetails($client_id) - { - $result = $this->collection('client_table')->findOne(array('client_id' => $client_id)); - - return is_null($result) ? false : $result; - } - - public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null) - { - if ($this->getClientDetails($client_id)) { - $this->collection('client_table')->update( - array('client_id' => $client_id), - array('$set' => array( - 'client_secret' => $client_secret, - 'redirect_uri' => $redirect_uri, - 'grant_types' => $grant_types, - 'scope' => $scope, - 'user_id' => $user_id, - )) - ); - } else { - $client = array( - 'client_id' => $client_id, - 'client_secret' => $client_secret, - 'redirect_uri' => $redirect_uri, - 'grant_types' => $grant_types, - 'scope' => $scope, - 'user_id' => $user_id, - ); - $this->collection('client_table')->insert($client); - } - - return true; - } - - public function checkRestrictedGrantType($client_id, $grant_type) - { - $details = $this->getClientDetails($client_id); - if (isset($details['grant_types'])) { - $grant_types = explode(' ', $details['grant_types']); - - return in_array($grant_type, $grant_types); - } - - // if grant_types are not defined, then none are restricted - return true; - } - - /* AccessTokenInterface */ - public function getAccessToken($access_token) - { - $token = $this->collection('access_token_table')->findOne(array('access_token' => $access_token)); - - return is_null($token) ? false : $token; - } - - public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null) - { - // if it exists, update it. - if ($this->getAccessToken($access_token)) { - $this->collection('access_token_table')->update( - array('access_token' => $access_token), - array('$set' => array( - 'client_id' => $client_id, - 'expires' => $expires, - 'user_id' => $user_id, - 'scope' => $scope - )) - ); - } else { - $token = array( - 'access_token' => $access_token, - 'client_id' => $client_id, - 'expires' => $expires, - 'user_id' => $user_id, - 'scope' => $scope - ); - $this->collection('access_token_table')->insert($token); - } - - return true; - } - - public function unsetAccessToken($access_token) - { - $this->collection('access_token_table')->remove(array('access_token' => $access_token)); - } - - - /* AuthorizationCodeInterface */ - public function getAuthorizationCode($code) - { - $code = $this->collection('code_table')->findOne(array('authorization_code' => $code)); - - return is_null($code) ? false : $code; - } - - public function setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null) - { - // if it exists, update it. - if ($this->getAuthorizationCode($code)) { - $this->collection('code_table')->update( - array('authorization_code' => $code), - array('$set' => array( - 'client_id' => $client_id, - 'user_id' => $user_id, - 'redirect_uri' => $redirect_uri, - 'expires' => $expires, - 'scope' => $scope, - 'id_token' => $id_token, - )) - ); - } else { - $token = array( - 'authorization_code' => $code, - 'client_id' => $client_id, - 'user_id' => $user_id, - 'redirect_uri' => $redirect_uri, - 'expires' => $expires, - 'scope' => $scope, - 'id_token' => $id_token, - ); - $this->collection('code_table')->insert($token); - } - - return true; - } - - public function expireAuthorizationCode($code) - { - $this->collection('code_table')->remove(array('authorization_code' => $code)); - - return true; - } - - /* UserCredentialsInterface */ - public function checkUserCredentials($username, $password) - { - if ($user = $this->getUser($username)) { - return $this->checkPassword($user, $password); - } - - return false; - } - - public function getUserDetails($username) - { - if ($user = $this->getUser($username)) { - $user['user_id'] = $user['username']; - } - - return $user; - } - - /* RefreshTokenInterface */ - public function getRefreshToken($refresh_token) - { - $token = $this->collection('refresh_token_table')->findOne(array('refresh_token' => $refresh_token)); - - return is_null($token) ? false : $token; - } - - public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null) - { - $token = array( - 'refresh_token' => $refresh_token, - 'client_id' => $client_id, - 'user_id' => $user_id, - 'expires' => $expires, - 'scope' => $scope - ); - $this->collection('refresh_token_table')->insert($token); - - return true; - } - - public function unsetRefreshToken($refresh_token) - { - $this->collection('refresh_token_table')->remove(array('refresh_token' => $refresh_token)); - - return true; - } - - // plaintext passwords are bad! Override this for your application - protected function checkPassword($user, $password) - { - return $user['password'] == $password; - } - - public function getUser($username) - { - $result = $this->collection('user_table')->findOne(array('username' => $username)); - - return is_null($result) ? false : $result; - } - - public function setUser($username, $password, $firstName = null, $lastName = null) - { - if ($this->getUser($username)) { - $this->collection('user_table')->update( - array('username' => $username), - array('$set' => array( - 'password' => $password, - 'first_name' => $firstName, - 'last_name' => $lastName - )) - ); - } else { - $user = array( - 'username' => $username, - 'password' => $password, - 'first_name' => $firstName, - 'last_name' => $lastName - ); - $this->collection('user_table')->insert($user); - } - - return true; - } - - public function getClientKey($client_id, $subject) - { - $result = $this->collection('jwt_table')->findOne(array( - 'client_id' => $client_id, - 'subject' => $subject - )); - - return is_null($result) ? false : $result['key']; - } - - public function getClientScope($client_id) - { - if (!$clientDetails = $this->getClientDetails($client_id)) { - return false; - } - - if (isset($clientDetails['scope'])) { - return $clientDetails['scope']; - } - - return null; - } - - public function getJti($client_id, $subject, $audience, $expiration, $jti) - { - //TODO: Needs mongodb implementation. - throw new \Exception('getJti() for the MongoDB driver is currently unimplemented.'); - } - - public function setJti($client_id, $subject, $audience, $expiration, $jti) - { - //TODO: Needs mongodb implementation. - throw new \Exception('setJti() for the MongoDB driver is currently unimplemented.'); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Pdo.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Pdo.php deleted file mode 100644 index b8fac34..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Pdo.php +++ /dev/null @@ -1,543 +0,0 @@ - - */ -class Pdo implements - AuthorizationCodeInterface, - AccessTokenInterface, - ClientCredentialsInterface, - UserCredentialsInterface, - RefreshTokenInterface, - JwtBearerInterface, - ScopeInterface, - PublicKeyInterface, - UserClaimsInterface, - OpenIDAuthorizationCodeInterface -{ - protected $db; - protected $config; - - public function __construct($connection, $config = array()) - { - if (!$connection instanceof \PDO) { - if (is_string($connection)) { - $connection = array('dsn' => $connection); - } - if (!is_array($connection)) { - throw new \InvalidArgumentException('First argument to OAuth2\Storage\Pdo must be an instance of PDO, a DSN string, or a configuration array'); - } - if (!isset($connection['dsn'])) { - throw new \InvalidArgumentException('configuration array must contain "dsn"'); - } - // merge optional parameters - $connection = array_merge(array( - 'username' => null, - 'password' => null, - 'options' => array(), - ), $connection); - $connection = new \PDO($connection['dsn'], $connection['username'], $connection['password'], $connection['options']); - } - $this->db = $connection; - - // debugging - $connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - - $this->config = array_merge(array( - 'client_table' => 'oauth_clients', - 'access_token_table' => 'oauth_access_tokens', - 'refresh_token_table' => 'oauth_refresh_tokens', - 'code_table' => 'oauth_authorization_codes', - 'user_table' => 'oauth_users', - 'jwt_table' => 'oauth_jwt', - 'jti_table' => 'oauth_jti', - 'scope_table' => 'oauth_scopes', - 'public_key_table' => 'oauth_public_keys', - ), $config); - } - - /* OAuth2\Storage\ClientCredentialsInterface */ - public function checkClientCredentials($client_id, $client_secret = null) - { - $stmt = $this->db->prepare(sprintf('SELECT * from %s where client_id = :client_id', $this->config['client_table'])); - $stmt->execute(compact('client_id')); - $result = $stmt->fetch(\PDO::FETCH_ASSOC); - - // make this extensible - return $result && $result['client_secret'] == $client_secret; - } - - public function isPublicClient($client_id) - { - $stmt = $this->db->prepare(sprintf('SELECT * from %s where client_id = :client_id', $this->config['client_table'])); - $stmt->execute(compact('client_id')); - - if (!$result = $stmt->fetch(\PDO::FETCH_ASSOC)) { - return false; - } - - return empty($result['client_secret']); - } - - /* OAuth2\Storage\ClientInterface */ - public function getClientDetails($client_id) - { - $stmt = $this->db->prepare(sprintf('SELECT * from %s where client_id = :client_id', $this->config['client_table'])); - $stmt->execute(compact('client_id')); - - return $stmt->fetch(\PDO::FETCH_ASSOC); - } - - public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null) - { - // if it exists, update it. - if ($this->getClientDetails($client_id)) { - $stmt = $this->db->prepare($sql = sprintf('UPDATE %s SET client_secret=:client_secret, redirect_uri=:redirect_uri, grant_types=:grant_types, scope=:scope, user_id=:user_id where client_id=:client_id', $this->config['client_table'])); - } else { - $stmt = $this->db->prepare(sprintf('INSERT INTO %s (client_id, client_secret, redirect_uri, grant_types, scope, user_id) VALUES (:client_id, :client_secret, :redirect_uri, :grant_types, :scope, :user_id)', $this->config['client_table'])); - } - - return $stmt->execute(compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id')); - } - - public function checkRestrictedGrantType($client_id, $grant_type) - { - $details = $this->getClientDetails($client_id); - if (isset($details['grant_types'])) { - $grant_types = explode(' ', $details['grant_types']); - - return in_array($grant_type, (array) $grant_types); - } - - // if grant_types are not defined, then none are restricted - return true; - } - - /* OAuth2\Storage\AccessTokenInterface */ - public function getAccessToken($access_token) - { - $stmt = $this->db->prepare(sprintf('SELECT * from %s where access_token = :access_token', $this->config['access_token_table'])); - - $token = $stmt->execute(compact('access_token')); - if ($token = $stmt->fetch(\PDO::FETCH_ASSOC)) { - // convert date string back to timestamp - $token['expires'] = strtotime($token['expires']); - } - - return $token; - } - - public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null) - { - // convert expires to datestring - $expires = date('Y-m-d H:i:s', $expires); - - // if it exists, update it. - if ($this->getAccessToken($access_token)) { - $stmt = $this->db->prepare(sprintf('UPDATE %s SET client_id=:client_id, expires=:expires, user_id=:user_id, scope=:scope where access_token=:access_token', $this->config['access_token_table'])); - } else { - $stmt = $this->db->prepare(sprintf('INSERT INTO %s (access_token, client_id, expires, user_id, scope) VALUES (:access_token, :client_id, :expires, :user_id, :scope)', $this->config['access_token_table'])); - } - - return $stmt->execute(compact('access_token', 'client_id', 'user_id', 'expires', 'scope')); - } - - public function unsetAccessToken($access_token) - { - $stmt = $this->db->prepare(sprintf('DELETE FROM %s WHERE access_token = :access_token', $this->config['access_token_table'])); - - return $stmt->execute(compact('access_token')); - } - - /* OAuth2\Storage\AuthorizationCodeInterface */ - public function getAuthorizationCode($code) - { - $stmt = $this->db->prepare(sprintf('SELECT * from %s where authorization_code = :code', $this->config['code_table'])); - $stmt->execute(compact('code')); - - if ($code = $stmt->fetch(\PDO::FETCH_ASSOC)) { - // convert date string back to timestamp - $code['expires'] = strtotime($code['expires']); - } - - return $code; - } - - public function setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null) - { - if (func_num_args() > 6) { - // we are calling with an id token - return call_user_func_array(array($this, 'setAuthorizationCodeWithIdToken'), func_get_args()); - } - - // convert expires to datestring - $expires = date('Y-m-d H:i:s', $expires); - - // if it exists, update it. - if ($this->getAuthorizationCode($code)) { - $stmt = $this->db->prepare($sql = sprintf('UPDATE %s SET client_id=:client_id, user_id=:user_id, redirect_uri=:redirect_uri, expires=:expires, scope=:scope where authorization_code=:code', $this->config['code_table'])); - } else { - $stmt = $this->db->prepare(sprintf('INSERT INTO %s (authorization_code, client_id, user_id, redirect_uri, expires, scope) VALUES (:code, :client_id, :user_id, :redirect_uri, :expires, :scope)', $this->config['code_table'])); - } - - return $stmt->execute(compact('code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope')); - } - - private function setAuthorizationCodeWithIdToken($code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null) - { - // convert expires to datestring - $expires = date('Y-m-d H:i:s', $expires); - - // if it exists, update it. - if ($this->getAuthorizationCode($code)) { - $stmt = $this->db->prepare($sql = sprintf('UPDATE %s SET client_id=:client_id, user_id=:user_id, redirect_uri=:redirect_uri, expires=:expires, scope=:scope, id_token =:id_token where authorization_code=:code', $this->config['code_table'])); - } else { - $stmt = $this->db->prepare(sprintf('INSERT INTO %s (authorization_code, client_id, user_id, redirect_uri, expires, scope, id_token) VALUES (:code, :client_id, :user_id, :redirect_uri, :expires, :scope, :id_token)', $this->config['code_table'])); - } - - return $stmt->execute(compact('code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope', 'id_token')); - } - - public function expireAuthorizationCode($code) - { - $stmt = $this->db->prepare(sprintf('DELETE FROM %s WHERE authorization_code = :code', $this->config['code_table'])); - - return $stmt->execute(compact('code')); - } - - /* OAuth2\Storage\UserCredentialsInterface */ - public function checkUserCredentials($username, $password) - { - if ($user = $this->getUser($username)) { - return $this->checkPassword($user, $password); - } - - return false; - } - - public function getUserDetails($username) - { - return $this->getUser($username); - } - - /* UserClaimsInterface */ - public function getUserClaims($user_id, $claims) - { - if (!$userDetails = $this->getUserDetails($user_id)) { - return false; - } - - $claims = explode(' ', trim($claims)); - $userClaims = array(); - - // for each requested claim, if the user has the claim, set it in the response - $validClaims = explode(' ', self::VALID_CLAIMS); - foreach ($validClaims as $validClaim) { - if (in_array($validClaim, $claims)) { - if ($validClaim == 'address') { - // address is an object with subfields - $userClaims['address'] = $this->getUserClaim($validClaim, $userDetails['address'] ?: $userDetails); - } else { - $userClaims = array_merge($userClaims, $this->getUserClaim($validClaim, $userDetails)); - } - } - } - - return $userClaims; - } - - protected function getUserClaim($claim, $userDetails) - { - $userClaims = array(); - $claimValuesString = constant(sprintf('self::%s_CLAIM_VALUES', strtoupper($claim))); - $claimValues = explode(' ', $claimValuesString); - - foreach ($claimValues as $value) { - $userClaims[$value] = isset($userDetails[$value]) ? $userDetails[$value] : null; - } - - return $userClaims; - } - - /* OAuth2\Storage\RefreshTokenInterface */ - public function getRefreshToken($refresh_token) - { - $stmt = $this->db->prepare(sprintf('SELECT * FROM %s WHERE refresh_token = :refresh_token', $this->config['refresh_token_table'])); - - $token = $stmt->execute(compact('refresh_token')); - if ($token = $stmt->fetch(\PDO::FETCH_ASSOC)) { - // convert expires to epoch time - $token['expires'] = strtotime($token['expires']); - } - - return $token; - } - - public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null) - { - // convert expires to datestring - $expires = date('Y-m-d H:i:s', $expires); - - $stmt = $this->db->prepare(sprintf('INSERT INTO %s (refresh_token, client_id, user_id, expires, scope) VALUES (:refresh_token, :client_id, :user_id, :expires, :scope)', $this->config['refresh_token_table'])); - - return $stmt->execute(compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope')); - } - - public function unsetRefreshToken($refresh_token) - { - $stmt = $this->db->prepare(sprintf('DELETE FROM %s WHERE refresh_token = :refresh_token', $this->config['refresh_token_table'])); - - return $stmt->execute(compact('refresh_token')); - } - - // plaintext passwords are bad! Override this for your application - protected function checkPassword($user, $password) - { - return $user['password'] == sha1($password); - } - - public function getUser($username) - { - $stmt = $this->db->prepare($sql = sprintf('SELECT * from %s where username=:username', $this->config['user_table'])); - $stmt->execute(array('username' => $username)); - - if (!$userInfo = $stmt->fetch(\PDO::FETCH_ASSOC)) { - return false; - } - - // the default behavior is to use "username" as the user_id - return array_merge(array( - 'user_id' => $username - ), $userInfo); - } - - public function setUser($username, $password, $firstName = null, $lastName = null) - { - // do not store in plaintext - $password = sha1($password); - - // if it exists, update it. - if ($this->getUser($username)) { - $stmt = $this->db->prepare($sql = sprintf('UPDATE %s SET password=:password, first_name=:firstName, last_name=:lastName where username=:username', $this->config['user_table'])); - } else { - $stmt = $this->db->prepare(sprintf('INSERT INTO %s (username, password, first_name, last_name) VALUES (:username, :password, :firstName, :lastName)', $this->config['user_table'])); - } - - return $stmt->execute(compact('username', 'password', 'firstName', 'lastName')); - } - - /* ScopeInterface */ - public function scopeExists($scope) - { - $scope = explode(' ', $scope); - $whereIn = implode(',', array_fill(0, count($scope), '?')); - $stmt = $this->db->prepare(sprintf('SELECT count(scope) as count FROM %s WHERE scope IN (%s)', $this->config['scope_table'], $whereIn)); - $stmt->execute($scope); - - if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) { - return $result['count'] == count($scope); - } - - return false; - } - - public function getDefaultScope($client_id = null) - { - $stmt = $this->db->prepare(sprintf('SELECT scope FROM %s WHERE is_default=:is_default', $this->config['scope_table'])); - $stmt->execute(array('is_default' => true)); - - if ($result = $stmt->fetchAll(\PDO::FETCH_ASSOC)) { - $defaultScope = array_map(function ($row) { - return $row['scope']; - }, $result); - - return implode(' ', $defaultScope); - } - - return null; - } - - /* JWTBearerInterface */ - public function getClientKey($client_id, $subject) - { - $stmt = $this->db->prepare($sql = sprintf('SELECT public_key from %s where client_id=:client_id AND subject=:subject', $this->config['jwt_table'])); - - $stmt->execute(array('client_id' => $client_id, 'subject' => $subject)); - - return $stmt->fetchColumn(); - } - - public function getClientScope($client_id) - { - if (!$clientDetails = $this->getClientDetails($client_id)) { - return false; - } - - if (isset($clientDetails['scope'])) { - return $clientDetails['scope']; - } - - return null; - } - - public function getJti($client_id, $subject, $audience, $expires, $jti) - { - $stmt = $this->db->prepare($sql = sprintf('SELECT * FROM %s WHERE issuer=:client_id AND subject=:subject AND audience=:audience AND expires=:expires AND jti=:jti', $this->config['jti_table'])); - - $stmt->execute(compact('client_id', 'subject', 'audience', 'expires', 'jti')); - - if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) { - return array( - 'issuer' => $result['issuer'], - 'subject' => $result['subject'], - 'audience' => $result['audience'], - 'expires' => $result['expires'], - 'jti' => $result['jti'], - ); - } - - return null; - } - - public function setJti($client_id, $subject, $audience, $expires, $jti) - { - $stmt = $this->db->prepare(sprintf('INSERT INTO %s (issuer, subject, audience, expires, jti) VALUES (:client_id, :subject, :audience, :expires, :jti)', $this->config['jti_table'])); - - return $stmt->execute(compact('client_id', 'subject', 'audience', 'expires', 'jti')); - } - - /* PublicKeyInterface */ - public function getPublicKey($client_id = null) - { - $stmt = $this->db->prepare($sql = sprintf('SELECT public_key FROM %s WHERE client_id=:client_id OR client_id IS NULL ORDER BY client_id IS NOT NULL DESC', $this->config['public_key_table'])); - - $stmt->execute(compact('client_id')); - if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) { - return $result['public_key']; - } - } - - public function getPrivateKey($client_id = null) - { - $stmt = $this->db->prepare($sql = sprintf('SELECT private_key FROM %s WHERE client_id=:client_id OR client_id IS NULL ORDER BY client_id IS NOT NULL DESC', $this->config['public_key_table'])); - - $stmt->execute(compact('client_id')); - if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) { - return $result['private_key']; - } - } - - public function getEncryptionAlgorithm($client_id = null) - { - $stmt = $this->db->prepare($sql = sprintf('SELECT encryption_algorithm FROM %s WHERE client_id=:client_id OR client_id IS NULL ORDER BY client_id IS NOT NULL DESC', $this->config['public_key_table'])); - - $stmt->execute(compact('client_id')); - if ($result = $stmt->fetch(\PDO::FETCH_ASSOC)) { - return $result['encryption_algorithm']; - } - - return 'RS256'; - } - - /** - * DDL to create OAuth2 database and tables for PDO storage - * - * @see https://github.com/dsquier/oauth2-server-php-mysql - */ - public function getBuildSql($dbName = 'oauth2_server_php') - { - $sql = " - CREATE TABLE {$this->config['client_table']} ( - client_id VARCHAR(80) NOT NULL, - client_secret VARCHAR(80) NOT NULL, - redirect_uri VARCHAR(2000), - grant_types VARCHAR(80), - scope VARCHAR(4000), - user_id VARCHAR(80), - PRIMARY KEY (client_id) - ); - - CREATE TABLE {$this->config['access_token_table']} ( - access_token VARCHAR(40) NOT NULL, - client_id VARCHAR(80) NOT NULL, - user_id VARCHAR(80), - expires TIMESTAMP NOT NULL, - scope VARCHAR(4000), - PRIMARY KEY (access_token) - ); - - CREATE TABLE {$this->config['code_table']} ( - authorization_code VARCHAR(40) NOT NULL, - client_id VARCHAR(80) NOT NULL, - user_id VARCHAR(80), - redirect_uri VARCHAR(2000), - expires TIMESTAMP NOT NULL, - scope VARCHAR(4000), - id_token VARCHAR(1000), - PRIMARY KEY (authorization_code) - ); - - CREATE TABLE {$this->config['refresh_token_table']} ( - refresh_token VARCHAR(40) NOT NULL, - client_id VARCHAR(80) NOT NULL, - user_id VARCHAR(80), - expires TIMESTAMP NOT NULL, - scope VARCHAR(4000), - PRIMARY KEY (refresh_token) - ); - - CREATE TABLE {$this->config['user_table']} ( - username VARCHAR(80), - password VARCHAR(80), - first_name VARCHAR(80), - last_name VARCHAR(80), - email VARCHAR(80), - email_verified BOOLEAN, - scope VARCHAR(4000) - ); - - CREATE TABLE {$this->config['scope_table']} ( - scope VARCHAR(80) NOT NULL, - is_default BOOLEAN, - PRIMARY KEY (scope) - ); - - CREATE TABLE {$this->config['jwt_table']} ( - client_id VARCHAR(80) NOT NULL, - subject VARCHAR(80), - public_key VARCHAR(2000) NOT NULL - ); - - CREATE TABLE {$this->config['jti_table']} ( - issuer VARCHAR(80) NOT NULL, - subject VARCHAR(80), - audiance VARCHAR(80), - expires TIMESTAMP NOT NULL, - jti VARCHAR(2000) NOT NULL - ); - - CREATE TABLE {$this->config['public_key_table']} ( - client_id VARCHAR(80), - public_key VARCHAR(2000), - private_key VARCHAR(2000), - encryption_algorithm VARCHAR(100) DEFAULT 'RS256' - ) -"; - - return $sql; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/PublicKeyInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/PublicKeyInterface.php deleted file mode 100644 index 108418d..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/PublicKeyInterface.php +++ /dev/null @@ -1,16 +0,0 @@ - - */ -interface PublicKeyInterface -{ - public function getPublicKey($client_id = null); - public function getPrivateKey($client_id = null); - public function getEncryptionAlgorithm($client_id = null); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Redis.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Redis.php deleted file mode 100644 index c274f91..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/Redis.php +++ /dev/null @@ -1,317 +0,0 @@ - - * $storage = new OAuth2\Storage\Redis($redis); - * $storage->setClientDetails($client_id, $client_secret, $redirect_uri); - * - */ -class Redis implements AuthorizationCodeInterface, - AccessTokenInterface, - ClientCredentialsInterface, - UserCredentialsInterface, - RefreshTokenInterface, - JwtBearerInterface, - ScopeInterface, - OpenIDAuthorizationCodeInterface -{ - - private $cache; - - /* The redis client */ - protected $redis; - - /* Configuration array */ - protected $config; - - /** - * Redis Storage! - * - * @param \Predis\Client $redis - * @param array $config - */ - public function __construct($redis, $config=array()) - { - $this->redis = $redis; - $this->config = array_merge(array( - 'client_key' => 'oauth_clients:', - 'access_token_key' => 'oauth_access_tokens:', - 'refresh_token_key' => 'oauth_refresh_tokens:', - 'code_key' => 'oauth_authorization_codes:', - 'user_key' => 'oauth_users:', - 'jwt_key' => 'oauth_jwt:', - 'scope_key' => 'oauth_scopes:', - ), $config); - } - - protected function getValue($key) - { - if ( isset($this->cache[$key]) ) { - return $this->cache[$key]; - } - $value = $this->redis->get($key); - if ( isset($value) ) { - return json_decode($value, true); - } else { - return false; - } - } - - protected function setValue($key, $value, $expire=0) - { - $this->cache[$key] = $value; - $str = json_encode($value); - if ($expire > 0) { - $seconds = $expire - time(); - $ret = $this->redis->setex($key, $seconds, $str); - } else { - $ret = $this->redis->set($key, $str); - } - - // check that the key was set properly - // if this fails, an exception will usually thrown, so this step isn't strictly necessary - return is_bool($ret) ? $ret : $ret->getPayload() == 'OK'; - } - - protected function expireValue($key) - { - unset($this->cache[$key]); - - return $this->redis->del($key); - } - - /* AuthorizationCodeInterface */ - public function getAuthorizationCode($code) - { - return $this->getValue($this->config['code_key'] . $code); - } - - public function setAuthorizationCode($authorization_code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null) - { - return $this->setValue( - $this->config['code_key'] . $authorization_code, - compact('authorization_code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope', 'id_token'), - $expires - ); - } - - public function expireAuthorizationCode($code) - { - $key = $this->config['code_key'] . $code; - unset($this->cache[$key]); - - return $this->expireValue($key); - } - - /* UserCredentialsInterface */ - public function checkUserCredentials($username, $password) - { - $user = $this->getUserDetails($username); - - return $user && $user['password'] === $password; - } - - public function getUserDetails($username) - { - return $this->getUser($username); - } - - public function getUser($username) - { - if (!$userInfo = $this->getValue($this->config['user_key'] . $username)) { - return false; - } - - // the default behavior is to use "username" as the user_id - return array_merge(array( - 'user_id' => $username, - ), $userInfo); - } - - public function setUser($username, $password, $first_name = null, $last_name = null) - { - return $this->setValue( - $this->config['user_key'] . $username, - compact('username', 'password', 'first_name', 'last_name') - ); - } - - /* ClientCredentialsInterface */ - public function checkClientCredentials($client_id, $client_secret = null) - { - if (!$client = $this->getClientDetails($client_id)) { - return false; - } - - return isset($client['client_secret']) - && $client['client_secret'] == $client_secret; - } - - public function isPublicClient($client_id) - { - if (!$client = $this->getClientDetails($client_id)) { - return false; - } - - return empty($result['client_secret']); - } - - /* ClientInterface */ - public function getClientDetails($client_id) - { - return $this->getValue($this->config['client_key'] . $client_id); - } - - public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null) - { - return $this->setValue( - $this->config['client_key'] . $client_id, - compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id') - ); - } - - public function checkRestrictedGrantType($client_id, $grant_type) - { - $details = $this->getClientDetails($client_id); - if (isset($details['grant_types'])) { - $grant_types = explode(' ', $details['grant_types']); - - return in_array($grant_type, (array) $grant_types); - } - - // if grant_types are not defined, then none are restricted - return true; - } - - /* RefreshTokenInterface */ - public function getRefreshToken($refresh_token) - { - return $this->getValue($this->config['refresh_token_key'] . $refresh_token); - } - - public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null) - { - return $this->setValue( - $this->config['refresh_token_key'] . $refresh_token, - compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope'), - $expires - ); - } - - public function unsetRefreshToken($refresh_token) - { - return $this->expireValue($this->config['refresh_token_key'] . $refresh_token); - } - - /* AccessTokenInterface */ - public function getAccessToken($access_token) - { - return $this->getValue($this->config['access_token_key'].$access_token); - } - - public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null) - { - return $this->setValue( - $this->config['access_token_key'].$access_token, - compact('access_token', 'client_id', 'user_id', 'expires', 'scope'), - $expires - ); - } - - public function unsetAccessToken($access_token) - { - return $this->expireValue($this->config['access_token_key'] . $access_token); - } - - /* ScopeInterface */ - public function scopeExists($scope) - { - $scope = explode(' ', $scope); - - $result = $this->getValue($this->config['scope_key'].'supported:global'); - - $supportedScope = explode(' ', (string) $result); - - return (count(array_diff($scope, $supportedScope)) == 0); - } - - public function getDefaultScope($client_id = null) - { - if (is_null($client_id) || !$result = $this->getValue($this->config['scope_key'].'default:'.$client_id)) { - $result = $this->getValue($this->config['scope_key'].'default:global'); - } - - return $result; - } - - public function setScope($scope, $client_id = null, $type = 'supported') - { - if (!in_array($type, array('default', 'supported'))) { - throw new \InvalidArgumentException('"$type" must be one of "default", "supported"'); - } - - if (is_null($client_id)) { - $key = $this->config['scope_key'].$type.':global'; - } else { - $key = $this->config['scope_key'].$type.':'.$client_id; - } - - return $this->setValue($key, $scope); - } - - /*JWTBearerInterface */ - public function getClientKey($client_id, $subject) - { - if (!$jwt = $this->getValue($this->config['jwt_key'] . $client_id)) { - return false; - } - - if (isset($jwt['subject']) && $jwt['subject'] == $subject) { - return $jwt['key']; - } - - return null; - } - - public function setClientKey($client_id, $key, $subject = null) - { - return $this->setValue($this->config['jwt_key'] . $client_id, array( - 'key' => $key, - 'subject' => $subject - )); - } - - public function getClientScope($client_id) - { - if (!$clientDetails = $this->getClientDetails($client_id)) { - return false; - } - - if (isset($clientDetails['scope'])) { - return $clientDetails['scope']; - } - - return null; - } - - public function getJti($client_id, $subject, $audience, $expiration, $jti) - { - //TODO: Needs redis implementation. - throw new \Exception('getJti() for the Redis driver is currently unimplemented.'); - } - - public function setJti($client_id, $subject, $audience, $expiration, $jti) - { - //TODO: Needs redis implementation. - throw new \Exception('setJti() for the Redis driver is currently unimplemented.'); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/RefreshTokenInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/RefreshTokenInterface.php deleted file mode 100644 index 0273f21..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/RefreshTokenInterface.php +++ /dev/null @@ -1,82 +0,0 @@ - - */ -interface RefreshTokenInterface -{ - /** - * Grant refresh access tokens. - * - * Retrieve the stored data for the given refresh token. - * - * Required for OAuth2::GRANT_TYPE_REFRESH_TOKEN. - * - * @param $refresh_token - * Refresh token to be check with. - * - * @return - * An associative array as below, and NULL if the refresh_token is - * invalid: - * - refresh_token: Refresh token identifier. - * - client_id: Client identifier. - * - user_id: User identifier. - * - expires: Expiration unix timestamp, or 0 if the token doesn't expire. - * - scope: (optional) Scope values in space-separated string. - * - * @see http://tools.ietf.org/html/rfc6749#section-6 - * - * @ingroup oauth2_section_6 - */ - public function getRefreshToken($refresh_token); - - /** - * Take the provided refresh token values and store them somewhere. - * - * This function should be the storage counterpart to getRefreshToken(). - * - * If storage fails for some reason, we're not currently checking for - * any sort of success/failure, so you should bail out of the script - * and provide a descriptive fail message. - * - * Required for OAuth2::GRANT_TYPE_REFRESH_TOKEN. - * - * @param $refresh_token - * Refresh token to be stored. - * @param $client_id - * Client identifier to be stored. - * @param $user_id - * User identifier to be stored. - * @param $expires - * Expiration timestamp to be stored. 0 if the token doesn't expire. - * @param $scope - * (optional) Scopes to be stored in space-separated string. - * - * @ingroup oauth2_section_6 - */ - public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null); - - /** - * Expire a used refresh token. - * - * This is not explicitly required in the spec, but is almost implied. - * After granting a new refresh token, the old one is no longer useful and - * so should be forcibly expired in the data store so it can't be used again. - * - * If storage fails for some reason, we're not currently checking for - * any sort of success/failure, so you should bail out of the script - * and provide a descriptive fail message. - * - * @param $refresh_token - * Refresh token to be expirse. - * - * @ingroup oauth2_section_6 - */ - public function unsetRefreshToken($refresh_token); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/ScopeInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/ScopeInterface.php deleted file mode 100644 index a829226..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/ScopeInterface.php +++ /dev/null @@ -1,46 +0,0 @@ - - */ -interface ScopeInterface -{ - /** - * Check if the provided scope exists. - * - * @param $scope - * A space-separated string of scopes. - * - * @return - * TRUE if it exists, FALSE otherwise. - */ - public function scopeExists($scope); - - /** - * The default scope to use in the event the client - * does not request one. By returning "false", a - * request_error is returned by the server to force a - * scope request by the client. By returning "null", - * opt out of requiring scopes - * - * @param $client_id - * An optional client id that can be used to return customized default scopes. - * - * @return - * string representation of default scope, null if - * scopes are not defined, or false to force scope - * request by the client - * - * ex: - * 'default' - * ex: - * null - */ - public function getDefaultScope($client_id = null); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/UserCredentialsInterface.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/UserCredentialsInterface.php deleted file mode 100644 index 6e0fd7b..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/Storage/UserCredentialsInterface.php +++ /dev/null @@ -1,52 +0,0 @@ - - */ -interface UserCredentialsInterface -{ - /** - * Grant access tokens for basic user credentials. - * - * Check the supplied username and password for validity. - * - * You can also use the $client_id param to do any checks required based - * on a client, if you need that. - * - * Required for OAuth2::GRANT_TYPE_USER_CREDENTIALS. - * - * @param $username - * Username to be check with. - * @param $password - * Password to be check with. - * - * @return - * TRUE if the username and password are valid, and FALSE if it isn't. - * Moreover, if the username and password are valid, and you want to - * - * @see http://tools.ietf.org/html/rfc6749#section-4.3 - * - * @ingroup oauth2_section_4 - */ - public function checkUserCredentials($username, $password); - - /** - * @return - * ARRAY the associated "user_id" and optional "scope" values - * This function MUST return FALSE if the requested user does not exist or is - * invalid. "scope" is a space-separated list of restricted scopes. - * @code - * return array( - * "user_id" => USER_ID, // REQUIRED user_id to be stored with the authorization code or access token - * "scope" => SCOPE // OPTIONAL space-separated list of restricted scopes - * ); - * @endcode - */ - public function getUserDetails($username); -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/TokenType/Bearer.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/TokenType/Bearer.php deleted file mode 100644 index 8ac8596..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/TokenType/Bearer.php +++ /dev/null @@ -1,130 +0,0 @@ -config = array_merge(array( - 'token_param_name' => 'access_token', - 'token_bearer_header_name' => 'Bearer', - ), $config); - } - - public function getTokenType() - { - return 'Bearer'; - } - - /** - * Check if the request has supplied token - * - * @see https://github.com/bshaffer/oauth2-server-php/issues/349#issuecomment-37993588 - */ - public function requestHasToken(RequestInterface $request) - { - $headers = $request->headers('AUTHORIZATION'); - - // check the header, then the querystring, then the request body - return !empty($headers) || (bool) ($request->request($this->config['token_param_name'])) || (bool) ($request->query($this->config['token_param_name'])); - } - - /** - * This is a convenience function that can be used to get the token, which can then - * be passed to getAccessTokenData(). The constraints specified by the draft are - * attempted to be adheared to in this method. - * - * As per the Bearer spec (draft 8, section 2) - there are three ways for a client - * to specify the bearer token, in order of preference: Authorization Header, - * POST and GET. - * - * NB: Resource servers MUST accept tokens via the Authorization scheme - * (http://tools.ietf.org/html/rfc6750#section-2). - * - * @todo Should we enforce TLS/SSL in this function? - * - * @see http://tools.ietf.org/html/rfc6750#section-2.1 - * @see http://tools.ietf.org/html/rfc6750#section-2.2 - * @see http://tools.ietf.org/html/rfc6750#section-2.3 - * - * Old Android version bug (at least with version 2.2) - * @see http://code.google.com/p/android/issues/detail?id=6684 - * - */ - public function getAccessTokenParameter(RequestInterface $request, ResponseInterface $response) - { - $headers = $request->headers('AUTHORIZATION'); - - /** - * Ensure more than one method is not used for including an - * access token - * - * @see http://tools.ietf.org/html/rfc6750#section-3.1 - */ - $methodsUsed = !empty($headers) + (bool) ($request->query($this->config['token_param_name'])) + (bool) ($request->request($this->config['token_param_name'])); - if ($methodsUsed > 1) { - $response->setError(400, 'invalid_request', 'Only one method may be used to authenticate at a time (Auth header, GET or POST)'); - - return null; - } - - /** - * If no authentication is provided, set the status code - * to 401 and return no other error information - * - * @see http://tools.ietf.org/html/rfc6750#section-3.1 - */ - if ($methodsUsed == 0) { - $response->setStatusCode(401); - - return null; - } - - // HEADER: Get the access token from the header - if (!empty($headers)) { - if (!preg_match('/' . $this->config['token_bearer_header_name'] . '\s(\S+)/i', $headers, $matches)) { - $response->setError(400, 'invalid_request', 'Malformed auth header'); - - return null; - } - - return $matches[1]; - } - - if ($request->request($this->config['token_param_name'])) { - // // POST: Get the token from POST data - if (!in_array(strtolower($request->server('REQUEST_METHOD')), array('post', 'put'))) { - $response->setError(400, 'invalid_request', 'When putting the token in the body, the method must be POST or PUT', '#section-2.2'); - - return null; - } - - $contentType = $request->server('CONTENT_TYPE'); - if (false !== $pos = strpos($contentType, ';')) { - $contentType = substr($contentType, 0, $pos); - } - - if ($contentType !== null && $contentType != 'application/x-www-form-urlencoded') { - // IETF specifies content-type. NB: Not all webservers populate this _SERVER variable - // @see http://tools.ietf.org/html/rfc6750#section-2.2 - $response->setError(400, 'invalid_request', 'The content type for POST requests must be "application/x-www-form-urlencoded"'); - - return null; - } - - return $request->request($this->config['token_param_name']); - } - - // GET method - return $request->query($this->config['token_param_name']); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/src/OAuth2/TokenType/Mac.php b/vendor/bshaffer/oauth2-server-php/src/OAuth2/TokenType/Mac.php deleted file mode 100644 index fe6a86a..0000000 --- a/vendor/bshaffer/oauth2-server-php/src/OAuth2/TokenType/Mac.php +++ /dev/null @@ -1,22 +0,0 @@ -assertTrue(class_exists('OAuth2\Server')); - $this->assertTrue(class_exists('OAuth2\Request')); - $this->assertTrue(class_exists('OAuth2\Response')); - $this->assertTrue(class_exists('OAuth2\GrantType\UserCredentials')); - $this->assertTrue(interface_exists('OAuth2\Storage\AccessTokenInterface')); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Controller/AuthorizeControllerTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Controller/AuthorizeControllerTest.php deleted file mode 100644 index c2745d6..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Controller/AuthorizeControllerTest.php +++ /dev/null @@ -1,476 +0,0 @@ -getTestServer(); - $request = new Request(); - $server->handleAuthorizeRequest($request, $response = new Response(), false); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_client'); - $this->assertEquals($response->getParameter('error_description'), 'No client id supplied'); - } - - public function testInvalidClientIdResponse() - { - $server = $this->getTestServer(); - $request = new Request(array( - 'client_id' => 'Fake Client ID', // invalid client id - )); - $server->handleAuthorizeRequest($request, $response = new Response(), false); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_client'); - $this->assertEquals($response->getParameter('error_description'), 'The client id supplied is invalid'); - } - - public function testNoRedirectUriSuppliedOrStoredResponse() - { - $server = $this->getTestServer(); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - )); - $server->handleAuthorizeRequest($request, $response = new Response(), false); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_uri'); - $this->assertEquals($response->getParameter('error_description'), 'No redirect URI was supplied or stored'); - } - - public function testNoResponseTypeResponse() - { - $server = $this->getTestServer(); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - )); - $server->handleAuthorizeRequest($request, $response = new Response(), false); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - parse_str($parts['query'], $query); - - $this->assertEquals($query['error'], 'invalid_request'); - $this->assertEquals($query['error_description'], 'Invalid or missing response type'); - } - - public function testInvalidResponseTypeResponse() - { - $server = $this->getTestServer(); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'invalid', // invalid response type - )); - $server->handleAuthorizeRequest($request, $response = new Response(), false); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - parse_str($parts['query'], $query); - - $this->assertEquals($query['error'], 'invalid_request'); - $this->assertEquals($query['error_description'], 'Invalid or missing response type'); - } - - public function testRedirectUriFragmentResponse() - { - $server = $this->getTestServer(); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com#fragment', // valid redirect URI - 'response_type' => 'code', // invalid response type - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_uri'); - $this->assertEquals($response->getParameter('error_description'), 'The redirect URI must not contain a fragment'); - } - - public function testEnforceState() - { - $server = $this->getTestServer(array('enforce_state' => true)); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'code', - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - parse_str($parts['query'], $query); - - $this->assertEquals($query['error'], 'invalid_request'); - $this->assertEquals($query['error_description'], 'The state parameter is required'); - } - - public function testDoNotEnforceState() - { - $server = $this->getTestServer(array('enforce_state' => false)); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'code', - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $this->assertNotContains('error', $response->getHttpHeader('Location')); - } - - public function testEnforceScope() - { - $server = $this->getTestServer(); - $scopeStorage = new Memory(array('default_scope' => false, 'supported_scopes' => array('testscope'))); - $server->setScopeUtil(new Scope($scopeStorage)); - - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'code', - 'state' => 'xyz', - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $parts = parse_url($response->getHttpHeader('Location')); - parse_str($parts['query'], $query); - - $this->assertEquals($query['error'], 'invalid_client'); - $this->assertEquals($query['error_description'], 'This application requires you specify a scope parameter'); - - $request->query['scope'] = 'testscope'; - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $this->assertNotContains('error', $response->getHttpHeader('Location')); - } - - public function testInvalidRedirectUri() - { - $server = $this->getTestServer(); - $request = new Request(array( - 'client_id' => 'Test Client ID with Redirect Uri', // valid client id - 'redirect_uri' => 'http://adobe.com', // invalid redirect URI - 'response_type' => 'code', - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'redirect_uri_mismatch'); - $this->assertEquals($response->getParameter('error_description'), 'The redirect URI provided is missing or does not match'); - } - - public function testNoRedirectUriWithMultipleRedirectUris() - { - $server = $this->getTestServer(); - - // create a request with no "redirect_uri" in querystring - $request = new Request(array( - 'client_id' => 'Test Client ID with Multiple Redirect Uris', // valid client id - 'response_type' => 'code', - )); - - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_uri'); - $this->assertEquals($response->getParameter('error_description'), 'A redirect URI must be supplied when multiple redirect URIs are registered'); - } - - public function testRedirectUriWithValidRedirectUri() - { - $server = $this->getTestServer(); - - // create a request with no "redirect_uri" in querystring - $request = new Request(array( - 'client_id' => 'Test Client ID with Redirect Uri Parts', // valid client id - 'response_type' => 'code', - 'redirect_uri' => 'http://user:pass@brentertainment.com:2222/authorize/cb?auth_type=oauth&test=true', - 'state' => 'xyz', - )); - - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $this->assertContains('code', $response->getHttpHeader('Location')); - } - - public function testRedirectUriWithDifferentQueryAndExactMatchRequired() - { - $server = $this->getTestServer(array('require_exact_redirect_uri' => true)); - - // create a request with no "redirect_uri" in querystring - $request = new Request(array( - 'client_id' => 'Test Client ID with Redirect Uri Parts', // valid client id - 'response_type' => 'code', - 'redirect_uri' => 'http://user:pass@brentertainment.com:2222/authorize/cb?auth_type=oauth&test=true&hereisa=querystring', - )); - - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'redirect_uri_mismatch'); - $this->assertEquals($response->getParameter('error_description'), 'The redirect URI provided is missing or does not match'); - } - - public function testRedirectUriWithDifferentQueryAndExactMatchNotRequired() - { - $server = $this->getTestServer(array('require_exact_redirect_uri' => false)); - - // create a request with no "redirect_uri" in querystring - $request = new Request(array( - 'client_id' => 'Test Client ID with Redirect Uri Parts', // valid client id - 'response_type' => 'code', - 'redirect_uri' => 'http://user:pass@brentertainment.com:2222/authorize/cb?auth_type=oauth&test=true&hereisa=querystring', - 'state' => 'xyz', - )); - - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $this->assertContains('code', $response->getHttpHeader('Location')); - } - - public function testMultipleRedirectUris() - { - $server = $this->getTestServer(); - $request = new Request(array( - 'client_id' => 'Test Client ID with Multiple Redirect Uris', // valid client id - 'redirect_uri' => 'http://brentertainment.com', // valid redirect URI - 'response_type' => 'code', - 'state' => 'xyz' - )); - - $server->handleAuthorizeRequest($request, $response = new Response(), true); - $this->assertEquals($response->getStatusCode(), 302); - $this->assertContains('code', $response->getHttpHeader('Location')); - - // call again with different (but still valid) redirect URI - $request->query['redirect_uri'] = 'http://morehazards.com'; - - $server->handleAuthorizeRequest($request, $response = new Response(), true); - $this->assertEquals($response->getStatusCode(), 302); - $this->assertContains('code', $response->getHttpHeader('Location')); - } - - /** - * @see http://tools.ietf.org/html/rfc6749#section-4.1.3 - * @see https://github.com/bshaffer/oauth2-server-php/issues/163 - */ - public function testNoRedirectUriSuppliedDoesNotRequireTokenRedirectUri() - { - $server = $this->getTestServer(); - $request = new Request(array( - 'client_id' => 'Test Client ID with Redirect Uri', // valid client id - 'response_type' => 'code', - 'state' => 'xyz', - )); - - $server->handleAuthorizeRequest($request, $response = new Response(), true); - $this->assertEquals($response->getStatusCode(), 302); - $this->assertContains('state', $response->getHttpHeader('Location')); - $this->assertStringStartsWith('http://brentertainment.com?code=', $response->getHttpHeader('Location')); - - $parts = parse_url($response->getHttpHeader('Location')); - parse_str($parts['query'], $query); - - // call token endpoint with no redirect_uri supplied - $request = TestRequest::createPost(array( - 'client_id' => 'Test Client ID with Redirect Uri', // valid client id - 'client_secret' => 'TestSecret2', - 'grant_type' => 'authorization_code', - 'code' => $query['code'], - )); - - $server->handleTokenRequest($request, $response = new Response(), true); - $this->assertEquals($response->getStatusCode(), 200); - $this->assertNotNull($response->getParameter('access_token')); - } - - public function testUserDeniesAccessResponse() - { - $server = $this->getTestServer(); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'code', - 'state' => 'xyz', - )); - $server->handleAuthorizeRequest($request, $response = new Response(), false); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - parse_str($parts['query'], $query); - - $this->assertEquals($query['error'], 'access_denied'); - $this->assertEquals($query['error_description'], 'The user denied access to your application'); - } - - public function testCodeQueryParamIsSet() - { - $server = $this->getTestServer(); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'code', - 'state' => 'xyz', - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - parse_str($parts['query'], $query); - - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - - $this->assertEquals('http', $parts['scheme']); // same as passed in to redirect_uri - $this->assertEquals('adobe.com', $parts['host']); // same as passed in to redirect_uri - $this->assertArrayHasKey('query', $parts); - $this->assertFalse(isset($parts['fragment'])); - - // assert fragment is in "application/x-www-form-urlencoded" format - parse_str($parts['query'], $query); - $this->assertNotNull($query); - $this->assertArrayHasKey('code', $query); - - // ensure no id_token was saved, since the openid scope wasn't requested - $storage = $server->getStorage('authorization_code'); - $code = $storage->getAuthorizationCode($query['code']); - $this->assertTrue(empty($code['id_token'])); - - // ensure no error was returned - $this->assertFalse(isset($query['error'])); - $this->assertFalse(isset($query['error_description'])); - } - - public function testSuccessfulRequestReturnsStateParameter() - { - $server = $this->getTestServer(array('allow_implicit' => true)); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'code', - 'state' => 'test', // valid state string (just needs to be passed back to us) - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - $this->assertArrayHasKey('query', $parts); - parse_str($parts['query'], $query); - - $this->assertArrayHasKey('state', $query); - $this->assertEquals($query['state'], 'test'); - - // ensure no error was returned - $this->assertFalse(isset($query['error'])); - $this->assertFalse(isset($query['error_description'])); - } - - public function testSuccessfulRequestStripsExtraParameters() - { - $server = $this->getTestServer(array('allow_implicit' => true)); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'code', - 'state' => 'test', // valid state string (just needs to be passed back to us) - 'fake' => 'something', // extra query param - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $this->assertNotContains('error', $location); - - $parts = parse_url($location); - $this->assertFalse(isset($parts['fake'])); - $this->assertArrayHasKey('query', $parts); - parse_str($parts['query'], $query); - - $this->assertFalse(isset($parmas['fake'])); - $this->assertArrayHasKey('state', $query); - $this->assertEquals($query['state'], 'test'); - } - - public function testSuccessfulOpenidConnectRequest() - { - $server = $this->getTestServer(array( - 'use_openid_connect' => true, - 'issuer' => 'bojanz', - )); - - $request = new Request(array( - 'client_id' => 'Test Client ID', - 'redirect_uri' => 'http://adobe.com', - 'response_type' => 'code', - 'state' => 'xyz', - 'scope' => 'openid', - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - parse_str($parts['query'], $query); - - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - $this->assertArrayHasKey('query', $parts); - $this->assertFalse(isset($parts['fragment'])); - - // assert fragment is in "application/x-www-form-urlencoded" format - parse_str($parts['query'], $query); - $this->assertNotNull($query); - $this->assertArrayHasKey('code', $query); - - // ensure no error was returned - $this->assertFalse(isset($query['error'])); - $this->assertFalse(isset($query['error_description'])); - - // confirm that the id_token has been created. - $storage = $server->getStorage('authorization_code'); - $code = $storage->getAuthorizationCode($query['code']); - $this->assertTrue(!empty($code['id_token'])); - } - - public function testCreateController() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $controller = new AuthorizeController($storage); - } - - private function getTestServer($config = array()) - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage, $config); - - // Add the two types supported for authorization grant - $server->addGrantType(new AuthorizationCode($storage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Controller/ResourceControllerTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Controller/ResourceControllerTest.php deleted file mode 100644 index ee6d96f..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Controller/ResourceControllerTest.php +++ /dev/null @@ -1,175 +0,0 @@ -getTestServer(); - $request = Request::createFromGlobals(); - $allow = $server->verifyResourceRequest($request, $response = new Response()); - $this->assertFalse($allow); - - $this->assertEquals($response->getStatusCode(), 401); - $this->assertNull($response->getParameter('error')); - $this->assertNull($response->getParameter('error_description')); - } - - public function testMalformedHeader() - { - $server = $this->getTestServer(); - $request = Request::createFromGlobals(); - $request->headers['AUTHORIZATION'] = 'tH1s i5 B0gU5'; - $allow = $server->verifyResourceRequest($request, $response = new Response()); - $this->assertFalse($allow); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'Malformed auth header'); - } - - public function testMultipleTokensSubmitted() - { - $server = $this->getTestServer(); - $request = Request::createFromGlobals(); - $request->request['access_token'] = 'TEST'; - $request->query['access_token'] = 'TEST'; - $allow = $server->verifyResourceRequest($request, $response = new Response()); - $this->assertFalse($allow); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'Only one method may be used to authenticate at a time (Auth header, GET or POST)'); - } - - public function testInvalidRequestMethod() - { - $server = $this->getTestServer(); - $request = Request::createFromGlobals(); - $request->server['REQUEST_METHOD'] = 'GET'; - $request->request['access_token'] = 'TEST'; - $allow = $server->verifyResourceRequest($request, $response = new Response()); - $this->assertFalse($allow); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'When putting the token in the body, the method must be POST or PUT'); - } - - public function testInvalidContentType() - { - $server = $this->getTestServer(); - $request = Request::createFromGlobals(); - $request->server['REQUEST_METHOD'] = 'POST'; - $request->server['CONTENT_TYPE'] = 'application/json'; - $request->request['access_token'] = 'TEST'; - $allow = $server->verifyResourceRequest($request, $response = new Response()); - $this->assertFalse($allow); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'The content type for POST requests must be "application/x-www-form-urlencoded"'); - } - - public function testInvalidToken() - { - $server = $this->getTestServer(); - $request = Request::createFromGlobals(); - $request->headers['AUTHORIZATION'] = 'Bearer TESTTOKEN'; - $allow = $server->verifyResourceRequest($request, $response = new Response()); - $this->assertFalse($allow); - - $this->assertEquals($response->getStatusCode(), 401); - $this->assertEquals($response->getParameter('error'), 'invalid_token'); - $this->assertEquals($response->getParameter('error_description'), 'The access token provided is invalid'); - } - - public function testExpiredToken() - { - $server = $this->getTestServer(); - $request = Request::createFromGlobals(); - $request->headers['AUTHORIZATION'] = 'Bearer accesstoken-expired'; - $allow = $server->verifyResourceRequest($request, $response = new Response()); - $this->assertFalse($allow); - - $this->assertEquals($response->getStatusCode(), 401); - $this->assertEquals($response->getParameter('error'), 'expired_token'); - $this->assertEquals($response->getParameter('error_description'), 'The access token provided has expired'); - } - - public function testOutOfScopeToken() - { - $server = $this->getTestServer(); - $request = Request::createFromGlobals(); - $request->headers['AUTHORIZATION'] = 'Bearer accesstoken-scope'; - $scope = 'outofscope'; - $allow = $server->verifyResourceRequest($request, $response = new Response(), $scope); - $this->assertFalse($allow); - - $this->assertEquals($response->getStatusCode(), 403); - $this->assertEquals($response->getParameter('error'), 'insufficient_scope'); - $this->assertEquals($response->getParameter('error_description'), 'The request requires higher privileges than provided by the access token'); - - // verify the "scope" has been set in the "WWW-Authenticate" header - preg_match('/scope="(.*?)"/', $response->getHttpHeader('WWW-Authenticate'), $matches); - $this->assertEquals(2, count($matches)); - $this->assertEquals($matches[1], 'outofscope'); - } - - public function testMalformedToken() - { - $server = $this->getTestServer(); - $request = Request::createFromGlobals(); - $request->headers['AUTHORIZATION'] = 'Bearer accesstoken-malformed'; - $allow = $server->verifyResourceRequest($request, $response = new Response()); - $this->assertFalse($allow); - - $this->assertEquals($response->getStatusCode(), 401); - $this->assertEquals($response->getParameter('error'), 'malformed_token'); - $this->assertEquals($response->getParameter('error_description'), 'Malformed token (missing "expires")'); - } - - public function testValidToken() - { - $server = $this->getTestServer(); - $request = Request::createFromGlobals(); - $request->headers['AUTHORIZATION'] = 'Bearer accesstoken-scope'; - $allow = $server->verifyResourceRequest($request, $response = new Response()); - $this->assertTrue($allow); - } - - public function testValidTokenWithScopeParam() - { - $server = $this->getTestServer(); - $request = Request::createFromGlobals(); - $request->headers['AUTHORIZATION'] = 'Bearer accesstoken-scope'; - $request->query['scope'] = 'testscope'; - $allow = $server->verifyResourceRequest($request, $response = new Response()); - $this->assertTrue($allow); - } - - public function testCreateController() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $tokenType = new \OAuth2\TokenType\Bearer(); - $controller = new ResourceController($tokenType, $storage); - } - - private function getTestServer($config = array()) - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage, $config); - - // Add the two types supported for authorization grant - $server->addGrantType(new AuthorizationCode($storage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Controller/TokenControllerTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Controller/TokenControllerTest.php deleted file mode 100644 index 4a217bd..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Controller/TokenControllerTest.php +++ /dev/null @@ -1,289 +0,0 @@ -getTestServer(); - $server->handleTokenRequest(TestRequest::createPost(), $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'The grant type was not specified in the request'); - } - - public function testInvalidGrantType() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'invalid_grant_type', // invalid grant type - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'unsupported_grant_type'); - $this->assertEquals($response->getParameter('error_description'), 'Grant type "invalid_grant_type" not supported'); - } - - public function testNoClientId() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'code' => 'testcode', - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_client'); - $this->assertEquals($response->getParameter('error_description'), 'Client credentials were not found in the headers or body'); - } - - public function testNoClientSecretWithConfidentialClient() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'code' => 'testcode', - 'client_id' => 'Test Client ID', // valid client id - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_client'); - $this->assertEquals($response->getParameter('error_description'), 'This client is invalid or must authenticate using a client secret'); - } - - public function testNoClientSecretWithEmptySecret() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'code' => 'testcode-empty-secret', - 'client_id' => 'Test Client ID Empty Secret', // valid client id - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 200); - } - - public function testInvalidClientId() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'code' => 'testcode', - 'client_id' => 'Fake Client ID', // invalid client id - 'client_secret' => 'TestSecret', // valid client secret - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_client'); - $this->assertEquals($response->getParameter('error_description'), 'The client credentials are invalid'); - } - - public function testInvalidClientSecret() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'code' => 'testcode', - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'Fake Client Secret', // invalid client secret - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_client'); - $this->assertEquals($response->getParameter('error_description'), 'The client credentials are invalid'); - } - - public function testValidTokenResponse() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'testcode', // valid authorization code - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertTrue($response instanceof Response); - $this->assertEquals($response->getStatusCode(), 200); - $this->assertNull($response->getParameter('error')); - $this->assertNull($response->getParameter('error_description')); - $this->assertNotNull($response->getParameter('access_token')); - $this->assertNotNull($response->getParameter('expires_in')); - $this->assertNotNull($response->getParameter('token_type')); - } - - public function testValidClientIdScope() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'code' => 'testcode', - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'scope' => 'clientscope1 clientscope2' - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 200); - $this->assertNull($response->getParameter('error')); - $this->assertNull($response->getParameter('error_description')); - $this->assertEquals('clientscope1 clientscope2', $response->getParameter('scope')); - } - - public function testInvalidClientIdScope() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'code' => 'testcode-with-scope', - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'scope' => 'clientscope3' - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_scope'); - $this->assertEquals($response->getParameter('error_description'), 'The scope requested is invalid for this request'); - } - - public function testEnforceScope() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage); - $server->addGrantType(new ClientCredentials($storage)); - - $scope = new Scope(array( - 'default_scope' => false, - 'supported_scopes' => array('testscope') - )); - $server->setScopeUtil($scope); - - $request = TestRequest::createPost(array( - 'grant_type' => 'client_credentials', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - )); - $response = $server->handleTokenRequest($request); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_scope'); - $this->assertEquals($response->getParameter('error_description'), 'This application requires you specify a scope parameter'); - } - - public function testCanReceiveAccessTokenUsingPasswordGrantTypeWithoutClientSecret() - { - // add the test parameters in memory - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage); - $server->addGrantType(new UserCredentials($storage)); - - $request = TestRequest::createPost(array( - 'grant_type' => 'password', // valid grant type - 'client_id' => 'Test Client ID For Password Grant', // valid client id - 'username' => 'johndoe', // valid username - 'password' => 'password', // valid password for username - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertTrue($response instanceof Response); - $this->assertEquals(200, $response->getStatusCode(), var_export($response, 1)); - $this->assertNull($response->getParameter('error')); - $this->assertNull($response->getParameter('error_description')); - $this->assertNotNull($response->getParameter('access_token')); - $this->assertNotNull($response->getParameter('expires_in')); - $this->assertNotNull($response->getParameter('token_type')); - } - - public function testInvalidTokenTypeHintForRevoke() - { - $server = $this->getTestServer(); - - $request = TestRequest::createPost(array( - 'token_type_hint' => 'foo', - 'token' => 'sometoken' - )); - - $server->handleRevokeRequest($request, $response = new Response()); - - $this->assertTrue($response instanceof Response); - $this->assertEquals(400, $response->getStatusCode(), var_export($response, 1)); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'Token type hint must be either \'access_token\' or \'refresh_token\''); - } - - public function testMissingTokenForRevoke() - { - $server = $this->getTestServer(); - - $request = TestRequest::createPost(array( - 'token_type_hint' => 'access_token' - )); - - $server->handleRevokeRequest($request, $response = new Response()); - $this->assertTrue($response instanceof Response); - $this->assertEquals(400, $response->getStatusCode(), var_export($response, 1)); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'Missing token parameter to revoke'); - } - - public function testInvalidRequestMethodForRevoke() - { - $server = $this->getTestServer(); - - $request = new TestRequest(); - $request->setQuery(array( - 'token_type_hint' => 'access_token' - )); - - $server->handleRevokeRequest($request, $response = new Response()); - $this->assertTrue($response instanceof Response); - $this->assertEquals(405, $response->getStatusCode(), var_export($response, 1)); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'The request method must be POST when revoking an access token'); - } - - public function testCreateController() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $accessToken = new \OAuth2\ResponseType\AccessToken($storage); - $controller = new TokenController($accessToken, $storage); - } - - private function getTestServer() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage); - $server->addGrantType(new AuthorizationCode($storage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Encryption/FirebaseJwtTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Encryption/FirebaseJwtTest.php deleted file mode 100644 index d341367..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Encryption/FirebaseJwtTest.php +++ /dev/null @@ -1,102 +0,0 @@ -privateKey = << $client_id, - 'exp' => time() + 1000, - 'iat' => time(), - 'sub' => 'testuser@ourdomain.com', - 'aud' => 'http://myapp.com/oauth/auth', - 'scope' => null, - ); - - $encoded = $jwtUtil->encode($params, $this->privateKey, 'RS256'); - - // test BC behaviour of trusting the algorithm in the header - $payload = $jwtUtil->decode($encoded, $client_key, array('RS256')); - $this->assertEquals($params, $payload); - - // test BC behaviour of not verifying by passing false - $payload = $jwtUtil->decode($encoded, $client_key, false); - $this->assertEquals($params, $payload); - - // test the new restricted algorithms header - $payload = $jwtUtil->decode($encoded, $client_key, array('RS256')); - $this->assertEquals($params, $payload); - } - - public function testInvalidJwt() - { - $jwtUtil = new FirebaseJwt(); - - $this->assertFalse($jwtUtil->decode('goob')); - $this->assertFalse($jwtUtil->decode('go.o.b')); - } - - /** @dataProvider provideClientCredentials */ - public function testInvalidJwtHeader($client_id, $client_key) - { - $jwtUtil = new FirebaseJwt(); - - $params = array( - 'iss' => $client_id, - 'exp' => time() + 1000, - 'iat' => time(), - 'sub' => 'testuser@ourdomain.com', - 'aud' => 'http://myapp.com/oauth/auth', - 'scope' => null, - ); - - // testing for algorithm tampering when only RSA256 signing is allowed - // @see https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/ - $tampered = $jwtUtil->encode($params, $client_key, 'HS256'); - - $payload = $jwtUtil->decode($tampered, $client_key, array('RS256')); - - $this->assertFalse($payload); - } - - public function provideClientCredentials() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $client_id = 'Test Client ID'; - $client_key = $storage->getClientKey($client_id, "testuser@ourdomain.com"); - - return array( - array($client_id, $client_key), - ); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Encryption/JwtTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Encryption/JwtTest.php deleted file mode 100644 index 214eeba..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Encryption/JwtTest.php +++ /dev/null @@ -1,102 +0,0 @@ -privateKey = << $client_id, - 'exp' => time() + 1000, - 'iat' => time(), - 'sub' => 'testuser@ourdomain.com', - 'aud' => 'http://myapp.com/oauth/auth', - 'scope' => null, - ); - - $encoded = $jwtUtil->encode($params, $this->privateKey, 'RS256'); - - // test BC behaviour of trusting the algorithm in the header - $payload = $jwtUtil->decode($encoded, $client_key); - $this->assertEquals($params, $payload); - - // test BC behaviour of not verifying by passing false - $payload = $jwtUtil->decode($encoded, $client_key, false); - $this->assertEquals($params, $payload); - - // test the new restricted algorithms header - $payload = $jwtUtil->decode($encoded, $client_key, array('RS256')); - $this->assertEquals($params, $payload); - } - - public function testInvalidJwt() - { - $jwtUtil = new Jwt(); - - $this->assertFalse($jwtUtil->decode('goob')); - $this->assertFalse($jwtUtil->decode('go.o.b')); - } - - /** @dataProvider provideClientCredentials */ - public function testInvalidJwtHeader($client_id, $client_key) - { - $jwtUtil = new Jwt(); - - $params = array( - 'iss' => $client_id, - 'exp' => time() + 1000, - 'iat' => time(), - 'sub' => 'testuser@ourdomain.com', - 'aud' => 'http://myapp.com/oauth/auth', - 'scope' => null, - ); - - // testing for algorithm tampering when only RSA256 signing is allowed - // @see https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/ - $tampered = $jwtUtil->encode($params, $client_key, 'HS256'); - - $payload = $jwtUtil->decode($tampered, $client_key, array('RS256')); - - $this->assertFalse($payload); - } - - public function provideClientCredentials() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $client_id = 'Test Client ID'; - $client_key = $storage->getClientKey($client_id, "testuser@ourdomain.com"); - - return array( - array($client_id, $client_key), - ); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/AuthorizationCodeTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/AuthorizationCodeTest.php deleted file mode 100644 index 7409896..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/AuthorizationCodeTest.php +++ /dev/null @@ -1,207 +0,0 @@ -getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'Missing parameter: "code" is required'); - } - - public function testInvalidCode() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'InvalidCode', // invalid authorization code - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'Authorization code doesn\'t exist or is invalid for the client'); - } - - public function testCodeCannotBeUsedTwice() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'testcode', // valid code - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 200); - $this->assertNotNull($response->getParameter('access_token')); - - // try to use the same code again - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'Authorization code doesn\'t exist or is invalid for the client'); - } - - public function testExpiredCode() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'testcode-expired', // expired authorization code - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'The authorization code has expired'); - } - - public function testValidCode() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'testcode', // valid code - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - } - - public function testValidCodeNoScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'testcode-with-scope', // valid code - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertArrayHasKey('scope', $token); - $this->assertEquals($token['scope'], 'scope1 scope2'); - } - - public function testValidCodeSameScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'testcode-with-scope', // valid code - 'scope' => 'scope2 scope1', - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertArrayHasKey('scope', $token); - $this->assertEquals($token['scope'], 'scope2 scope1'); - } - - public function testValidCodeLessScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'testcode-with-scope', // valid code - 'scope' => 'scope1', - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertArrayHasKey('scope', $token); - $this->assertEquals($token['scope'], 'scope1'); - } - - public function testValidCodeDifferentScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'testcode-with-scope', // valid code - 'scope' => 'scope3', - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_scope'); - $this->assertEquals($response->getParameter('error_description'), 'The scope requested is invalid for this request'); - } - - public function testValidCodeInvalidScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'testcode-with-scope', // valid code - 'scope' => 'invalid-scope', - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_scope'); - $this->assertEquals($response->getParameter('error_description'), 'The scope requested is invalid for this request'); - } - - public function testValidClientDifferentCode() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Some Other Client', // valid client id - 'client_secret' => 'TestSecret3', // valid client secret - 'code' => 'testcode', // valid code - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'authorization_code doesn\'t exist or is invalid for the client'); - } - - private function getTestServer() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage); - $server->addGrantType(new AuthorizationCode($storage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/ClientCredentialsTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/ClientCredentialsTest.php deleted file mode 100644 index f0d46cc..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/ClientCredentialsTest.php +++ /dev/null @@ -1,159 +0,0 @@ -getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'client_credentials', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'FakeSecret', // valid client secret - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_client'); - $this->assertEquals($response->getParameter('error_description'), 'The client credentials are invalid'); - } - - public function testValidCredentials() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'client_credentials', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('scope', $token); - $this->assertNull($token['scope']); - } - - public function testValidCredentialsWithScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'client_credentials', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'scope' => 'scope1', - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertArrayHasKey('scope', $token); - $this->assertEquals($token['scope'], 'scope1'); - } - - public function testValidCredentialsInvalidScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'client_credentials', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'scope' => 'invalid-scope', - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_scope'); - $this->assertEquals($response->getParameter('error_description'), 'An unsupported scope was requested'); - } - - public function testValidCredentialsInHeader() - { - // create with HTTP_AUTHORIZATION in header - $server = $this->getTestServer(); - $headers = array('HTTP_AUTHORIZATION' => 'Basic '.base64_encode('Test Client ID:TestSecret'), 'REQUEST_METHOD' => 'POST'); - $params = array('grant_type' => 'client_credentials'); - $request = new Request(array(), $params, array(), array(), array(), $headers); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertNotNull($token['access_token']); - - // create using PHP Authorization Globals - $headers = array('PHP_AUTH_USER' => 'Test Client ID', 'PHP_AUTH_PW' => 'TestSecret', 'REQUEST_METHOD' => 'POST'); - $params = array('grant_type' => 'client_credentials'); - $request = new Request(array(), $params, array(), array(), array(), $headers); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertNotNull($token['access_token']); - } - - public function testValidCredentialsInRequest() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'client_credentials', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertNotNull($token['access_token']); - } - - public function testValidCredentialsInQuerystring() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'client_credentials', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertNotNull($token['access_token']); - } - - public function testClientUserIdIsSetInAccessToken() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'client_credentials', // valid grant type - 'client_id' => 'Client ID With User ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - - // verify the user_id was associated with the token - $storage = $server->getStorage('client'); - $token = $storage->getAccessToken($token['access_token']); - $this->assertNotNull($token); - $this->assertArrayHasKey('user_id', $token); - $this->assertEquals($token['user_id'], 'brent@brentertainment.com'); - } - - private function getTestServer() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage); - $server->addGrantType(new ClientCredentials($storage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/ImplicitTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/ImplicitTest.php deleted file mode 100644 index a312ebc..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/ImplicitTest.php +++ /dev/null @@ -1,143 +0,0 @@ -getTestServer(); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'token', // invalid response type - )); - $server->handleAuthorizeRequest($request, $response = new Response(), false); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - parse_str($parts['query'], $query); - - $this->assertEquals($query['error'], 'unsupported_response_type'); - $this->assertEquals($query['error_description'], 'implicit grant type not supported'); - } - - public function testUserDeniesAccessResponse() - { - $server = $this->getTestServer(array('allow_implicit' => true)); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'token', // valid response type - 'state' => 'xyz', - )); - $server->handleAuthorizeRequest($request, $response = new Response(), false); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - parse_str($parts['query'], $query); - - $this->assertEquals($query['error'], 'access_denied'); - $this->assertEquals($query['error_description'], 'The user denied access to your application'); - } - - public function testSuccessfulRequestFragmentParameter() - { - $server = $this->getTestServer(array('allow_implicit' => true)); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'token', // valid response type - 'state' => 'xyz', - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $this->assertNull($response->getParameter('error')); - $this->assertNull($response->getParameter('error_description')); - - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - - $this->assertEquals('http', $parts['scheme']); // same as passed in to redirect_uri - $this->assertEquals('adobe.com', $parts['host']); // same as passed in to redirect_uri - $this->assertArrayHasKey('fragment', $parts); - $this->assertFalse(isset($parts['query'])); - - // assert fragment is in "application/x-www-form-urlencoded" format - parse_str($parts['fragment'], $params); - $this->assertNotNull($params); - $this->assertArrayHasKey('access_token', $params); - $this->assertArrayHasKey('expires_in', $params); - $this->assertArrayHasKey('token_type', $params); - } - - public function testSuccessfulRequestReturnsStateParameter() - { - $server = $this->getTestServer(array('allow_implicit' => true)); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'token', // valid response type - 'state' => 'test', // valid state string (just needs to be passed back to us) - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $this->assertNull($response->getParameter('error')); - $this->assertNull($response->getParameter('error_description')); - - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - $this->assertArrayHasKey('fragment', $parts); - parse_str($parts['fragment'], $params); - - $this->assertArrayHasKey('state', $params); - $this->assertEquals($params['state'], 'test'); - } - - public function testSuccessfulRequestStripsExtraParameters() - { - $server = $this->getTestServer(array('allow_implicit' => true)); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com?fake=something', // valid redirect URI - 'response_type' => 'token', // valid response type - 'state' => 'test', // valid state string (just needs to be passed back to us) - 'fake' => 'something', // add extra param to querystring - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $this->assertNull($response->getParameter('error')); - $this->assertNull($response->getParameter('error_description')); - - $location = $response->getHttpHeader('Location'); - $parts = parse_url($location); - $this->assertFalse(isset($parts['fake'])); - $this->assertArrayHasKey('fragment', $parts); - parse_str($parts['fragment'], $params); - - $this->assertFalse(isset($parmas['fake'])); - $this->assertArrayHasKey('state', $params); - $this->assertEquals($params['state'], 'test'); - } - - private function getTestServer($config = array()) - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage, $config); - - // Add the two types supported for authorization grant - $server->addGrantType(new AuthorizationCode($storage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/JwtBearerTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/JwtBearerTest.php deleted file mode 100644 index 0a6c4b8..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/JwtBearerTest.php +++ /dev/null @@ -1,360 +0,0 @@ -privateKey = <<getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - )); - - //Get the jwt and break it - $jwt = $this->getJWT(); - $jwt = substr_replace($jwt, 'broken', 3, 6); - - $request->request['assertion'] = $jwt; - - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'JWT is malformed'); - } - - public function testBrokenSignature() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - )); - - //Get the jwt and break signature - $jwt = $this->getJWT() . 'notSupposeToBeHere'; - $request->request['assertion'] = $jwt; - - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'JWT failed signature verification'); - } - - public function testExpiredJWT() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - )); - - //Get an expired JWT - $jwt = $this->getJWT(1234); - $request->request['assertion'] = $jwt; - - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'JWT has expired'); - } - - public function testBadExp() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - )); - - //Get an expired JWT - $jwt = $this->getJWT('badtimestamp'); - $request->request['assertion'] = $jwt; - - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'Expiration (exp) time must be a unix time stamp'); - } - - public function testNoAssert() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - )); - - //Do not pass the assert (JWT) - - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'Missing parameters: "assertion" required'); - } - - public function testNotBefore() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - )); - - //Get a future NBF - $jwt = $this->getJWT(null, time() + 10000); - $request->request['assertion'] = $jwt; - - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'JWT cannot be used before the Not Before (nbf) time'); - } - - public function testBadNotBefore() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - )); - - //Get a non timestamp nbf - $jwt = $this->getJWT(null, 'notatimestamp'); - $request->request['assertion'] = $jwt; - - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'Not Before (nbf) time must be a unix time stamp'); - } - - public function testNonMatchingAudience() - { - $server = $this->getTestServer('http://google.com/oauth/o/auth'); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - 'assertion' => $this->getJWT(), - )); - - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'Invalid audience (aud)'); - } - - public function testBadClientID() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - 'assertion' => $this->getJWT(null, null, null, 'bad_client_id'), - )); - - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'Invalid issuer (iss) or subject (sub) provided'); - } - - public function testBadSubject() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - 'assertion' => $this->getJWT(null, null, 'anotheruser@ourdomain,com'), - )); - - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'Invalid issuer (iss) or subject (sub) provided'); - } - - public function testMissingKey() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - 'assertion' => $this->getJWT(null, null, null, 'Missing Key Cli,nt'), - )); - - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'Invalid issuer (iss) or subject (sub) provided'); - } - - public function testValidJwt() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - 'assertion' => $this->getJWT(), // valid assertion - )); - - $token = $server->grantAccessToken($request, new Response()); - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - } - - public function testValidJwtWithScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - 'assertion' => $this->getJWT(null, null, null, 'Test Client ID'), // valid assertion - 'scope' => 'scope1', // valid scope - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertArrayHasKey('scope', $token); - $this->assertEquals($token['scope'], 'scope1'); - } - - public function testValidJwtInvalidScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - 'assertion' => $this->getJWT(null, null, null, 'Test Client ID'), // valid assertion - 'scope' => 'invalid-scope', // invalid scope - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_scope'); - $this->assertEquals($response->getParameter('error_description'), 'An unsupported scope was requested'); - } - - public function testValidJti() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - 'assertion' => $this->getJWT(null, null, 'testuser@ourdomain.com', 'Test Client ID', 'unused_jti'), // valid assertion with invalid scope - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - } - - public function testInvalidJti() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - 'assertion' => $this->getJWT(99999999900, null, 'testuser@ourdomain.com', 'Test Client ID', 'used_jti'), // valid assertion with invalid scope - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'JSON Token Identifier (jti) has already been used'); - } - - public function testJtiReplayAttack() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', // valid grant type - 'assertion' => $this->getJWT(99999999900, null, 'testuser@ourdomain.com', 'Test Client ID', 'totally_new_jti'), // valid assertion with invalid scope - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - - //Replay the same request - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'JSON Token Identifier (jti) has already been used'); - } - - /** - * Generates a JWT - * @param $exp The expiration date. If the current time is greater than the exp, the JWT is invalid. - * @param $nbf The "not before" time. If the current time is less than the nbf, the JWT is invalid. - * @param $sub The subject we are acting on behalf of. This could be the email address of the user in the system. - * @param $iss The issuer, usually the client_id. - * @return string - */ - private function getJWT($exp = null, $nbf = null, $sub = null, $iss = 'Test Client ID', $jti = null) - { - if (!$exp) { - $exp = time() + 1000; - } - - if (!$sub) { - $sub = "testuser@ourdomain.com"; - } - - $params = array( - 'iss' => $iss, - 'exp' => $exp, - 'iat' => time(), - 'sub' => $sub, - 'aud' => 'http://myapp.com/oauth/auth', - ); - - if ($nbf) { - $params['nbf'] = $nbf; - } - - if ($jti) { - $params['jti'] = $jti; - } - - $jwtUtil = new Jwt(); - - return $jwtUtil->encode($params, $this->privateKey, 'RS256'); - } - - private function getTestServer($audience = 'http://myapp.com/oauth/auth') - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage); - $server->addGrantType(new JwtBearer($storage, $audience, new Jwt())); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/RefreshTokenTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/RefreshTokenTest.php deleted file mode 100644 index a458aad..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/RefreshTokenTest.php +++ /dev/null @@ -1,204 +0,0 @@ -getTestServer(); - $server->addGrantType(new RefreshToken($this->storage)); - - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - )); - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'Missing parameter: "refresh_token" is required'); - } - - public function testInvalidRefreshToken() - { - $server = $this->getTestServer(); - $server->addGrantType(new RefreshToken($this->storage)); - - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'refresh_token' => 'fake-token', // invalid refresh token - )); - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'Invalid refresh token'); - } - - public function testValidRefreshTokenWithNewRefreshTokenInResponse() - { - $server = $this->getTestServer(); - $server->addGrantType(new RefreshToken($this->storage, array('always_issue_new_refresh_token' => true))); - - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'refresh_token' => 'test-refreshtoken', // valid refresh token - )); - $token = $server->grantAccessToken($request, new Response()); - $this->assertTrue(isset($token['refresh_token']), 'refresh token should always refresh'); - - $refresh_token = $this->storage->getRefreshToken($token['refresh_token']); - $this->assertNotNull($refresh_token); - $this->assertEquals($refresh_token['refresh_token'], $token['refresh_token']); - $this->assertEquals($refresh_token['client_id'], $request->request('client_id')); - $this->assertTrue($token['refresh_token'] != 'test-refreshtoken', 'the refresh token returned is not the one used'); - $used_token = $this->storage->getRefreshToken('test-refreshtoken'); - $this->assertFalse($used_token, 'the refresh token used is no longer valid'); - } - - public function testValidRefreshTokenDoesNotUnsetToken() - { - $server = $this->getTestServer(); - $server->addGrantType(new RefreshToken($this->storage, array( - 'always_issue_new_refresh_token' => true, - 'unset_refresh_token_after_use' => false, - ))); - - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'refresh_token' => 'test-refreshtoken', // valid refresh token - )); - $token = $server->grantAccessToken($request, new Response()); - $this->assertTrue(isset($token['refresh_token']), 'refresh token should always refresh'); - - $used_token = $this->storage->getRefreshToken('test-refreshtoken'); - $this->assertNotNull($used_token, 'the refresh token used is still valid'); - } - - public function testValidRefreshTokenWithNoRefreshTokenInResponse() - { - $server = $this->getTestServer(); - $server->addGrantType(new RefreshToken($this->storage, array('always_issue_new_refresh_token' => false))); - - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'refresh_token' => 'test-refreshtoken', // valid refresh token - )); - $token = $server->grantAccessToken($request, new Response()); - $this->assertFalse(isset($token['refresh_token']), 'refresh token should not be returned'); - - $used_token = $this->storage->getRefreshToken('test-refreshtoken'); - $this->assertNotNull($used_token, 'the refresh token used is still valid'); - } - - public function testValidRefreshTokenSameScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'refresh_token' => 'test-refreshtoken-with-scope', // valid refresh token (with scope) - 'scope' => 'scope2 scope1', - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertArrayHasKey('scope', $token); - $this->assertEquals($token['scope'], 'scope2 scope1'); - } - - public function testValidRefreshTokenLessScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'refresh_token' => 'test-refreshtoken-with-scope', // valid refresh token (with scope) - 'scope' => 'scope1', - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertArrayHasKey('scope', $token); - $this->assertEquals($token['scope'], 'scope1'); - } - - public function testValidRefreshTokenDifferentScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'refresh_token' => 'test-refreshtoken-with-scope', // valid refresh token (with scope) - 'scope' => 'scope3', - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_scope'); - $this->assertEquals($response->getParameter('error_description'), 'The scope requested is invalid for this request'); - } - - public function testValidRefreshTokenInvalidScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'refresh_token' => 'test-refreshtoken-with-scope', // valid refresh token (with scope) - 'scope' => 'invalid-scope', - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_scope'); - $this->assertEquals($response->getParameter('error_description'), 'The scope requested is invalid for this request'); - } - - public function testValidClientDifferentRefreshToken() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', // valid grant type - 'client_id' => 'Test Some Other Client', // valid client id - 'client_secret' => 'TestSecret3', // valid client secret - 'refresh_token' => 'test-refreshtoken', // valid refresh token - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'refresh_token doesn\'t exist or is invalid for the client'); - } - - private function getTestServer() - { - $this->storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($this->storage); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/UserCredentialsTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/UserCredentialsTest.php deleted file mode 100644 index 18943d0..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/GrantType/UserCredentialsTest.php +++ /dev/null @@ -1,172 +0,0 @@ -getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'password', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'password' => 'testpass', // valid password - )); - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'Missing parameters: "username" and "password" required'); - } - - public function testNoPassword() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'password', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'username' => 'test-username', // valid username - )); - $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'Missing parameters: "username" and "password" required'); - } - - public function testInvalidUsername() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'password', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'username' => 'fake-username', // valid username - 'password' => 'testpass', // valid password - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 401); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'Invalid username and password combination'); - } - - public function testInvalidPassword() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'password', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'username' => 'test-username', // valid username - 'password' => 'fakepass', // invalid password - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 401); - $this->assertEquals($response->getParameter('error'), 'invalid_grant'); - $this->assertEquals($response->getParameter('error_description'), 'Invalid username and password combination'); - } - - public function testValidCredentials() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'password', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'username' => 'test-username', // valid username - 'password' => 'testpass', // valid password - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - } - - public function testValidCredentialsWithScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'password', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'username' => 'test-username', // valid username - 'password' => 'testpass', // valid password - 'scope' => 'scope1', // valid scope - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertArrayHasKey('scope', $token); - $this->assertEquals($token['scope'], 'scope1'); - } - - public function testValidCredentialsInvalidScope() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'password', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'username' => 'test-username', // valid username - 'password' => 'testpass', // valid password - 'scope' => 'invalid-scope', - )); - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_scope'); - $this->assertEquals($response->getParameter('error_description'), 'An unsupported scope was requested'); - } - - public function testNoSecretWithPublicClient() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'password', // valid grant type - 'client_id' => 'Test Client ID Empty Secret', // valid public client - 'username' => 'test-username', // valid username - 'password' => 'testpass', // valid password - )); - - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - } - - public function testNoSecretWithConfidentialClient() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'password', // valid grant type - 'client_id' => 'Test Client ID', // valid public client - 'username' => 'test-username', // valid username - 'password' => 'testpass', // valid password - )); - - $token = $server->grantAccessToken($request, $response = new Response()); - - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_client'); - $this->assertEquals($response->getParameter('error_description'), 'This client is invalid or must authenticate using a client secret'); - } - - private function getTestServer() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage); - $server->addGrantType(new UserCredentials($storage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Controller/AuthorizeControllerTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Controller/AuthorizeControllerTest.php deleted file mode 100644 index 46de936..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Controller/AuthorizeControllerTest.php +++ /dev/null @@ -1,182 +0,0 @@ -getTestServer(); - - $response = new Response(); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'id_token', - 'state' => 'af0ifjsldkj', - 'nonce' => 'n-0S6_WzA2Mj', - )); - - // Test valid id_token request - $server->handleAuthorizeRequest($request, $response, true); - - $parts = parse_url($response->getHttpHeader('Location')); - parse_str($parts['fragment'], $query); - - $this->assertEquals('n-0S6_WzA2Mj', $server->getAuthorizeController()->getNonce()); - $this->assertEquals($query['state'], 'af0ifjsldkj'); - - $this->assertArrayHasKey('id_token', $query); - $this->assertArrayHasKey('state', $query); - $this->assertArrayNotHasKey('access_token', $query); - $this->assertArrayNotHasKey('expires_in', $query); - $this->assertArrayNotHasKey('token_type', $query); - - // Test valid token id_token request - $request->query['response_type'] = 'id_token token'; - $server->handleAuthorizeRequest($request, $response, true); - - $parts = parse_url($response->getHttpHeader('Location')); - parse_str($parts['fragment'], $query); - - $this->assertEquals('n-0S6_WzA2Mj', $server->getAuthorizeController()->getNonce()); - $this->assertEquals($query['state'], 'af0ifjsldkj'); - - $this->assertArrayHasKey('access_token', $query); - $this->assertArrayHasKey('expires_in', $query); - $this->assertArrayHasKey('token_type', $query); - $this->assertArrayHasKey('state', $query); - $this->assertArrayHasKey('id_token', $query); - - // assert that with multiple-valued response types, order does not matter - $request->query['response_type'] = 'token id_token'; - $server->handleAuthorizeRequest($request, $response, true); - - $parts = parse_url($response->getHttpHeader('Location')); - parse_str($parts['fragment'], $query); - - $this->assertEquals('n-0S6_WzA2Mj', $server->getAuthorizeController()->getNonce()); - $this->assertEquals($query['state'], 'af0ifjsldkj'); - - $this->assertArrayHasKey('access_token', $query); - $this->assertArrayHasKey('expires_in', $query); - $this->assertArrayHasKey('token_type', $query); - $this->assertArrayHasKey('state', $query); - $this->assertArrayHasKey('id_token', $query); - - // assert that with multiple-valued response types with extra spaces do not matter - $request->query['response_type'] = ' token id_token '; - $server->handleAuthorizeRequest($request, $response, true); - - $parts = parse_url($response->getHttpHeader('Location')); - parse_str($parts['fragment'], $query); - - $this->assertEquals('n-0S6_WzA2Mj', $server->getAuthorizeController()->getNonce()); - $this->assertEquals($query['state'], 'af0ifjsldkj'); - - $this->assertArrayHasKey('access_token', $query); - $this->assertArrayHasKey('expires_in', $query); - $this->assertArrayHasKey('token_type', $query); - $this->assertArrayHasKey('state', $query); - $this->assertArrayHasKey('id_token', $query); - } - - public function testMissingNonce() - { - $server = $this->getTestServer(); - $authorize = $server->getAuthorizeController(); - - $response = new Response(); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'id_token', - 'state' => 'xyz', - )); - - // Test missing nonce for 'id_token' response type - $server->handleAuthorizeRequest($request, $response, true); - $params = $response->getParameters(); - - $this->assertEquals($params['error'], 'invalid_nonce'); - $this->assertEquals($params['error_description'], 'This application requires you specify a nonce parameter'); - - // Test missing nonce for 'id_token token' response type - $request->query['response_type'] = 'id_token token'; - $server->handleAuthorizeRequest($request, $response, true); - $params = $response->getParameters(); - - $this->assertEquals($params['error'], 'invalid_nonce'); - $this->assertEquals($params['error_description'], 'This application requires you specify a nonce parameter'); - } - - public function testNotGrantedApplication() - { - $server = $this->getTestServer(); - - $response = new Response(); - $request = new Request(array( - 'client_id' => 'Test Client ID', // valid client id - 'redirect_uri' => 'http://adobe.com', // valid redirect URI - 'response_type' => 'id_token', - 'state' => 'af0ifjsldkj', - 'nonce' => 'n-0S6_WzA2Mj', - )); - - // Test not approved application - $server->handleAuthorizeRequest($request, $response, false); - - $params = $response->getParameters(); - - $this->assertEquals($params['error'], 'consent_required'); - $this->assertEquals($params['error_description'], 'The user denied access to your application'); - - // Test not approved application with prompt parameter - $request->query['prompt'] = 'none'; - $server->handleAuthorizeRequest($request, $response, false); - - $params = $response->getParameters(); - - $this->assertEquals($params['error'], 'login_required'); - $this->assertEquals($params['error_description'], 'The user must log in'); - - // Test not approved application with user_id set - $request->query['prompt'] = 'none'; - $server->handleAuthorizeRequest($request, $response, false, 'some-user-id'); - - $params = $response->getParameters(); - - $this->assertEquals($params['error'], 'interaction_required'); - $this->assertEquals($params['error_description'], 'The user must grant access to your application'); - } - - public function testNeedsIdToken() - { - $server = $this->getTestServer(); - $authorize = $server->getAuthorizeController(); - - $this->assertTrue($authorize->needsIdToken('openid')); - $this->assertTrue($authorize->needsIdToken('openid profile')); - $this->assertFalse($authorize->needsIdToken('')); - $this->assertFalse($authorize->needsIdToken('some-scope')); - } - - private function getTestServer($config = array()) - { - $config += array( - 'use_openid_connect' => true, - 'issuer' => 'phpunit', - 'allow_implicit' => true - ); - - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage, $config); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Controller/UserInfoControllerTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Controller/UserInfoControllerTest.php deleted file mode 100644 index b1b6870..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Controller/UserInfoControllerTest.php +++ /dev/null @@ -1,44 +0,0 @@ -handleUserInfoRequest(new Request(), $response); - $this->assertEquals(401, $response->getStatusCode()); - } - - public function testValidToken() - { - $server = $this->getTestServer(); - $request = Request::createFromGlobals(); - $request->headers['AUTHORIZATION'] = 'Bearer accesstoken-openid-connect'; - $response = new Response(); - - $server->handleUserInfoRequest($request, $response); - $parameters = $response->getParameters(); - $this->assertEquals($parameters['sub'], 'testuser'); - $this->assertEquals($parameters['email'], 'testuser@test.com'); - $this->assertEquals($parameters['email_verified'], true); - } - - private function getTestServer($config = array()) - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage, $config); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/GrantType/AuthorizationCodeTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/GrantType/AuthorizationCodeTest.php deleted file mode 100644 index 776002d..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/GrantType/AuthorizationCodeTest.php +++ /dev/null @@ -1,57 +0,0 @@ -getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'testcode-openid', // valid code - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('id_token', $token); - $this->assertEquals('test_id_token', $token['id_token']); - - // this is only true if "offline_access" was requested - $this->assertFalse(isset($token['refresh_token'])); - } - - public function testOfflineAccess() - { - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'code' => 'testcode-openid', // valid code - 'scope' => 'offline_access', // valid code - )); - $token = $server->grantAccessToken($request, new Response()); - - $this->assertNotNull($token); - $this->assertArrayHasKey('id_token', $token); - $this->assertEquals('test_id_token', $token['id_token']); - $this->assertTrue(isset($token['refresh_token'])); - } - - private function getTestServer() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage, array('use_openid_connect' => true)); - $server->addGrantType(new AuthorizationCode($storage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/ResponseType/CodeIdTokenTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/ResponseType/CodeIdTokenTest.php deleted file mode 100644 index 5daaaa6..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/ResponseType/CodeIdTokenTest.php +++ /dev/null @@ -1,91 +0,0 @@ -getTestServer(); - - $request = new Request(array( - 'response_type' => 'code id_token', - 'redirect_uri' => 'http://adobe.com', - 'client_id' => 'Test Client ID', - 'scope' => 'openid', - 'state' => 'test', - 'nonce' => 'test', - )); - - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $this->assertNotContains('error', $location); - - $parts = parse_url($location); - $this->assertArrayHasKey('query', $parts); - - // assert fragment is in "application/x-www-form-urlencoded" format - parse_str($parts['query'], $params); - $this->assertNotNull($params); - $this->assertArrayHasKey('id_token', $params); - $this->assertArrayHasKey('code', $params); - - // validate ID Token - $parts = explode('.', $params['id_token']); - foreach ($parts as &$part) { - // Each part is a base64url encoded json string. - $part = str_replace(array('-', '_'), array('+', '/'), $part); - $part = base64_decode($part); - $part = json_decode($part, true); - } - list($header, $claims, $signature) = $parts; - - $this->assertArrayHasKey('iss', $claims); - $this->assertArrayHasKey('sub', $claims); - $this->assertArrayHasKey('aud', $claims); - $this->assertArrayHasKey('iat', $claims); - $this->assertArrayHasKey('exp', $claims); - $this->assertArrayHasKey('auth_time', $claims); - $this->assertArrayHasKey('nonce', $claims); - - // only exists if an access token was granted along with the id_token - $this->assertArrayNotHasKey('at_hash', $claims); - - $this->assertEquals($claims['iss'], 'test'); - $this->assertEquals($claims['aud'], 'Test Client ID'); - $this->assertEquals($claims['nonce'], 'test'); - $duration = $claims['exp'] - $claims['iat']; - $this->assertEquals($duration, 3600); - } - - private function getTestServer($config = array()) - { - $config += array( - 'use_openid_connect' => true, - 'issuer' => 'test', - 'id_lifetime' => 3600, - 'allow_implicit' => true, - ); - - $memoryStorage = Bootstrap::getInstance()->getMemoryStorage(); - $responseTypes = array( - 'code' => $code = new AuthorizationCode($memoryStorage), - 'id_token' => $idToken = new IdToken($memoryStorage, $memoryStorage, $config), - 'code id_token' => new CodeIdToken($code, $idToken), - ); - - $server = new Server($memoryStorage, $config, array(), $responseTypes); - $server->addGrantType(new ClientCredentials($memoryStorage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/ResponseType/IdTokenTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/ResponseType/IdTokenTest.php deleted file mode 100644 index e772f6b..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/ResponseType/IdTokenTest.php +++ /dev/null @@ -1,184 +0,0 @@ - 'id_token', - 'redirect_uri' => 'http://adobe.com', - 'client_id' => 'Test Client ID', - 'scope' => 'openid', - 'state' => 'test', - ); - - // attempt to do the request without a nonce. - $server = $this->getTestServer(array('allow_implicit' => true)); - $request = new Request($query); - $valid = $server->validateAuthorizeRequest($request, $response = new Response()); - - // Add a nonce and retry. - $query['nonce'] = 'test'; - $request = new Request($query); - $valid = $server->validateAuthorizeRequest($request, $response = new Response()); - $this->assertTrue($valid); - } - - public function testHandleAuthorizeRequest() - { - // add the test parameters in memory - $server = $this->getTestServer(array('allow_implicit' => true)); - $request = new Request(array( - 'response_type' => 'id_token', - 'redirect_uri' => 'http://adobe.com', - 'client_id' => 'Test Client ID', - 'scope' => 'openid email', - 'state' => 'test', - 'nonce' => 'test', - )); - - $user_id = 'testuser'; - $server->handleAuthorizeRequest($request, $response = new Response(), true, $user_id); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $this->assertNotContains('error', $location); - - $parts = parse_url($location); - $this->assertArrayHasKey('fragment', $parts); - $this->assertFalse(isset($parts['query'])); - - // assert fragment is in "application/x-www-form-urlencoded" format - parse_str($parts['fragment'], $params); - $this->assertNotNull($params); - $this->assertArrayHasKey('id_token', $params); - $this->assertArrayNotHasKey('access_token', $params); - $this->validateIdToken($params['id_token']); - } - - public function testPassInAuthTime() - { - $server = $this->getTestServer(array('allow_implicit' => true)); - $request = new Request(array( - 'response_type' => 'id_token', - 'redirect_uri' => 'http://adobe.com', - 'client_id' => 'Test Client ID', - 'scope' => 'openid email', - 'state' => 'test', - 'nonce' => 'test', - )); - - // test with a scalar user id - $user_id = 'testuser123'; - $server->handleAuthorizeRequest($request, $response = new Response(), true, $user_id); - - list($header, $payload, $signature) = $this->extractTokenDataFromResponse($response); - - $this->assertTrue(is_array($payload)); - $this->assertArrayHasKey('sub', $payload); - $this->assertEquals($user_id, $payload['sub']); - $this->assertArrayHasKey('auth_time', $payload); - - // test with an array of user info - $userInfo = array( - 'user_id' => 'testuser1234', - 'auth_time' => date('Y-m-d H:i:s', strtotime('20 minutes ago') - )); - - $server->handleAuthorizeRequest($request, $response = new Response(), true, $userInfo); - - list($header, $payload, $signature) = $this->extractTokenDataFromResponse($response); - - $this->assertTrue(is_array($payload)); - $this->assertArrayHasKey('sub', $payload); - $this->assertEquals($userInfo['user_id'], $payload['sub']); - $this->assertArrayHasKey('auth_time', $payload); - $this->assertEquals($userInfo['auth_time'], $payload['auth_time']); - } - - private function extractTokenDataFromResponse(Response $response) - { - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $this->assertNotContains('error', $location); - - $parts = parse_url($location); - $this->assertArrayHasKey('fragment', $parts); - $this->assertFalse(isset($parts['query'])); - - parse_str($parts['fragment'], $params); - $this->assertNotNull($params); - $this->assertArrayHasKey('id_token', $params); - $this->assertArrayNotHasKey('access_token', $params); - - list($headb64, $payloadb64, $signature) = explode('.', $params['id_token']); - - $jwt = new Jwt(); - $header = json_decode($jwt->urlSafeB64Decode($headb64), true); - $payload = json_decode($jwt->urlSafeB64Decode($payloadb64), true); - - return array($header, $payload, $signature); - } - - private function validateIdToken($id_token) - { - $parts = explode('.', $id_token); - foreach ($parts as &$part) { - // Each part is a base64url encoded json string. - $part = str_replace(array('-', '_'), array('+', '/'), $part); - $part = base64_decode($part); - $part = json_decode($part, true); - } - list($header, $claims, $signature) = $parts; - - $this->assertArrayHasKey('iss', $claims); - $this->assertArrayHasKey('sub', $claims); - $this->assertArrayHasKey('aud', $claims); - $this->assertArrayHasKey('iat', $claims); - $this->assertArrayHasKey('exp', $claims); - $this->assertArrayHasKey('auth_time', $claims); - $this->assertArrayHasKey('nonce', $claims); - $this->assertArrayHasKey('email', $claims); - $this->assertArrayHasKey('email_verified', $claims); - - $this->assertEquals($claims['iss'], 'test'); - $this->assertEquals($claims['aud'], 'Test Client ID'); - $this->assertEquals($claims['nonce'], 'test'); - $this->assertEquals($claims['email'], 'testuser@test.com'); - $duration = $claims['exp'] - $claims['iat']; - $this->assertEquals($duration, 3600); - } - - private function getTestServer($config = array()) - { - $config += array( - 'use_openid_connect' => true, - 'issuer' => 'test', - 'id_lifetime' => 3600, - ); - - $memoryStorage = Bootstrap::getInstance()->getMemoryStorage(); - $memoryStorage->supportedScopes[] = 'email'; - $storage = array( - 'client' => $memoryStorage, - 'scope' => $memoryStorage, - ); - $responseTypes = array( - 'id_token' => new IdToken($memoryStorage, $memoryStorage, $config), - ); - - $server = new Server($storage, $config, array(), $responseTypes); - $server->addGrantType(new ClientCredentials($memoryStorage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/ResponseType/IdTokenTokenTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/ResponseType/IdTokenTokenTest.php deleted file mode 100644 index bc564d3..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/ResponseType/IdTokenTokenTest.php +++ /dev/null @@ -1,91 +0,0 @@ -getTestServer(array('allow_implicit' => true)); - - $request = new Request(array( - 'response_type' => 'id_token token', - 'redirect_uri' => 'http://adobe.com', - 'client_id' => 'Test Client ID', - 'scope' => 'openid', - 'state' => 'test', - 'nonce' => 'test', - )); - - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - $this->assertEquals($response->getStatusCode(), 302); - $location = $response->getHttpHeader('Location'); - $this->assertNotContains('error', $location); - - $parts = parse_url($location); - $this->assertArrayHasKey('fragment', $parts); - $this->assertFalse(isset($parts['query'])); - - // assert fragment is in "application/x-www-form-urlencoded" format - parse_str($parts['fragment'], $params); - $this->assertNotNull($params); - $this->assertArrayHasKey('id_token', $params); - $this->assertArrayHasKey('access_token', $params); - - // validate ID Token - $parts = explode('.', $params['id_token']); - foreach ($parts as &$part) { - // Each part is a base64url encoded json string. - $part = str_replace(array('-', '_'), array('+', '/'), $part); - $part = base64_decode($part); - $part = json_decode($part, true); - } - list($header, $claims, $signature) = $parts; - - $this->assertArrayHasKey('iss', $claims); - $this->assertArrayHasKey('sub', $claims); - $this->assertArrayHasKey('aud', $claims); - $this->assertArrayHasKey('iat', $claims); - $this->assertArrayHasKey('exp', $claims); - $this->assertArrayHasKey('auth_time', $claims); - $this->assertArrayHasKey('nonce', $claims); - $this->assertArrayHasKey('at_hash', $claims); - - $this->assertEquals($claims['iss'], 'test'); - $this->assertEquals($claims['aud'], 'Test Client ID'); - $this->assertEquals($claims['nonce'], 'test'); - $duration = $claims['exp'] - $claims['iat']; - $this->assertEquals($duration, 3600); - } - - private function getTestServer($config = array()) - { - $config += array( - 'use_openid_connect' => true, - 'issuer' => 'test', - 'id_lifetime' => 3600, - ); - - $memoryStorage = Bootstrap::getInstance()->getMemoryStorage(); - $responseTypes = array( - 'token' => $token = new AccessToken($memoryStorage, $memoryStorage), - 'id_token' => $idToken = new IdToken($memoryStorage, $memoryStorage, $config), - 'id_token token' => new IdTokenToken($token, $idToken), - ); - - $server = new Server($memoryStorage, $config, array(), $responseTypes); - $server->addGrantType(new ClientCredentials($memoryStorage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Storage/AuthorizationCodeTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Storage/AuthorizationCodeTest.php deleted file mode 100644 index bdfb085..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Storage/AuthorizationCodeTest.php +++ /dev/null @@ -1,95 +0,0 @@ -markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - if (!$storage instanceof AuthorizationCodeInterface) { - return; - } - - // assert code we are about to add does not exist - $code = $storage->getAuthorizationCode('new-openid-code'); - $this->assertFalse($code); - - // add new code - $expires = time() + 20; - $scope = null; - $id_token = 'fake_id_token'; - $success = $storage->setAuthorizationCode('new-openid-code', 'client ID', 'SOMEUSERID', 'http://example.com', $expires, $scope, $id_token); - $this->assertTrue($success); - - $code = $storage->getAuthorizationCode('new-openid-code'); - $this->assertNotNull($code); - $this->assertArrayHasKey('authorization_code', $code); - $this->assertArrayHasKey('client_id', $code); - $this->assertArrayHasKey('user_id', $code); - $this->assertArrayHasKey('redirect_uri', $code); - $this->assertArrayHasKey('expires', $code); - $this->assertEquals($code['authorization_code'], 'new-openid-code'); - $this->assertEquals($code['client_id'], 'client ID'); - $this->assertEquals($code['user_id'], 'SOMEUSERID'); - $this->assertEquals($code['redirect_uri'], 'http://example.com'); - $this->assertEquals($code['expires'], $expires); - $this->assertEquals($code['id_token'], $id_token); - - // change existing code - $expires = time() + 42; - $new_id_token = 'fake_id_token-2'; - $success = $storage->setAuthorizationCode('new-openid-code', 'client ID2', 'SOMEOTHERID', 'http://example.org', $expires, $scope, $new_id_token); - $this->assertTrue($success); - - $code = $storage->getAuthorizationCode('new-openid-code'); - $this->assertNotNull($code); - $this->assertArrayHasKey('authorization_code', $code); - $this->assertArrayHasKey('client_id', $code); - $this->assertArrayHasKey('user_id', $code); - $this->assertArrayHasKey('redirect_uri', $code); - $this->assertArrayHasKey('expires', $code); - $this->assertEquals($code['authorization_code'], 'new-openid-code'); - $this->assertEquals($code['client_id'], 'client ID2'); - $this->assertEquals($code['user_id'], 'SOMEOTHERID'); - $this->assertEquals($code['redirect_uri'], 'http://example.org'); - $this->assertEquals($code['expires'], $expires); - $this->assertEquals($code['id_token'], $new_id_token); - } - - /** @dataProvider provideStorage */ - public function testRemoveIdTokenFromAuthorizationCode($storage) - { - // add new code - $expires = time() + 20; - $scope = null; - $id_token = 'fake_id_token_to_remove'; - $authcode = 'new-openid-code-'.rand(); - $success = $storage->setAuthorizationCode($authcode, 'client ID', 'SOMEUSERID', 'http://example.com', $expires, $scope, $id_token); - $this->assertTrue($success); - - // verify params were set - $code = $storage->getAuthorizationCode($authcode); - $this->assertNotNull($code); - $this->assertArrayHasKey('id_token', $code); - $this->assertEquals($code['id_token'], $id_token); - - // remove the id_token - $success = $storage->setAuthorizationCode($authcode, 'client ID', 'SOMEUSERID', 'http://example.com', $expires, $scope, null); - - // verify the "id_token" is now null - $code = $storage->getAuthorizationCode($authcode); - $this->assertNotNull($code); - $this->assertArrayHasKey('id_token', $code); - $this->assertEquals($code['id_token'], null); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Storage/UserClaimsTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Storage/UserClaimsTest.php deleted file mode 100644 index 840f6c5..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/OpenID/Storage/UserClaimsTest.php +++ /dev/null @@ -1,41 +0,0 @@ -markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - if (!$storage instanceof UserClaimsInterface) { - // incompatible storage - return; - } - - // invalid user - $claims = $storage->getUserClaims('fake-user', ''); - $this->assertFalse($claims); - - // valid user (no scope) - $claims = $storage->getUserClaims('testuser', ''); - - /* assert the decoded token is the same */ - $this->assertFalse(isset($claims['email'])); - - // valid user - $claims = $storage->getUserClaims('testuser', 'email'); - - /* assert the decoded token is the same */ - $this->assertEquals($claims['email'], "testuser@test.com"); - $this->assertEquals($claims['email_verified'], true); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/RequestTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/RequestTest.php deleted file mode 100644 index 10db321..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/RequestTest.php +++ /dev/null @@ -1,98 +0,0 @@ -getTestServer(); - - // Smoke test for override request class - // $server->handleTokenRequest($request, $response = new Response()); - // $this->assertInstanceOf('Response', $response); - // $server->handleAuthorizeRequest($request, $response = new Response(), true); - // $this->assertInstanceOf('Response', $response); - // $response = $server->verifyResourceRequest($request, $response = new Response()); - // $this->assertTrue(is_bool($response)); - - /*** make some valid requests ***/ - - // Valid Token Request - $request->setPost(array( - 'grant_type' => 'authorization_code', - 'client_id' => 'Test Client ID', - 'client_secret' => 'TestSecret', - 'code' => 'testcode', - )); - $server->handleTokenRequest($request, $response = new Response()); - $this->assertEquals($response->getStatusCode(), 200); - $this->assertNull($response->getParameter('error')); - $this->assertNotNUll($response->getParameter('access_token')); - } - - public function testHeadersReturnsValueByKey() - { - $request = new Request( - array(), - array(), - array(), - array(), - array(), - array(), - array(), - array('AUTHORIZATION' => 'Basic secret') - ); - - $this->assertEquals('Basic secret', $request->headers('AUTHORIZATION')); - } - - public function testHeadersReturnsDefaultIfHeaderNotPresent() - { - $request = new Request(); - - $this->assertEquals('Bearer', $request->headers('AUTHORIZATION', 'Bearer')); - } - - public function testHeadersIsCaseInsensitive() - { - $request = new Request( - array(), - array(), - array(), - array(), - array(), - array(), - array(), - array('AUTHORIZATION' => 'Basic secret') - ); - - $this->assertEquals('Basic secret', $request->headers('Authorization')); - } - - public function testRequestReturnsPostParamIfNoQueryParamAvailable() - { - $request = new Request( - array(), - array('client_id' => 'correct') - ); - - $this->assertEquals('correct', $request->query('client_id', $request->request('client_id'))); - } - - private function getTestServer($config = array()) - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage, $config); - - // Add the two types supported for authorization grant - $server->addGrantType(new AuthorizationCode($storage)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/ResponseTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/ResponseTest.php deleted file mode 100644 index b814900..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/ResponseTest.php +++ /dev/null @@ -1,17 +0,0 @@ - 'bar', - 'halland' => 'oates', - )); - - $string = $response->getResponseBody('xml'); - $this->assertContains('baroates', $string); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/ResponseType/AccessTokenTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/ResponseType/AccessTokenTest.php deleted file mode 100644 index 0ed1c82..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/ResponseType/AccessTokenTest.php +++ /dev/null @@ -1,107 +0,0 @@ - array( - 'revoke' => array('mytoken'), - ), - )); - - $this->assertEquals(array('mytoken'), $tokenStorage->getAccessToken('revoke')); - $accessToken = new AccessToken($tokenStorage); - $accessToken->revokeToken('revoke', 'access_token'); - $this->assertFalse($tokenStorage->getAccessToken('revoke')); - } - - public function testRevokeAccessTokenWithoutTypeHint() - { - $tokenStorage = new Memory(array( - 'access_tokens' => array( - 'revoke' => array('mytoken'), - ), - )); - - $this->assertEquals(array('mytoken'), $tokenStorage->getAccessToken('revoke')); - $accessToken = new AccessToken($tokenStorage); - $accessToken->revokeToken('revoke'); - $this->assertFalse($tokenStorage->getAccessToken('revoke')); - } - - public function testRevokeRefreshTokenWithTypeHint() - { - $tokenStorage = new Memory(array( - 'refresh_tokens' => array( - 'revoke' => array('mytoken'), - ), - )); - - $this->assertEquals(array('mytoken'), $tokenStorage->getRefreshToken('revoke')); - $accessToken = new AccessToken(new Memory, $tokenStorage); - $accessToken->revokeToken('revoke', 'refresh_token'); - $this->assertFalse($tokenStorage->getRefreshToken('revoke')); - } - - public function testRevokeRefreshTokenWithoutTypeHint() - { - $tokenStorage = new Memory(array( - 'refresh_tokens' => array( - 'revoke' => array('mytoken'), - ), - )); - - $this->assertEquals(array('mytoken'), $tokenStorage->getRefreshToken('revoke')); - $accessToken = new AccessToken(new Memory, $tokenStorage); - $accessToken->revokeToken('revoke'); - $this->assertFalse($tokenStorage->getRefreshToken('revoke')); - } - - public function testRevokeAccessTokenWithRefreshTokenTypeHint() - { - $tokenStorage = new Memory(array( - 'access_tokens' => array( - 'revoke' => array('mytoken'), - ), - )); - - $this->assertEquals(array('mytoken'), $tokenStorage->getAccessToken('revoke')); - $accessToken = new AccessToken($tokenStorage); - $accessToken->revokeToken('revoke', 'refresh_token'); - $this->assertFalse($tokenStorage->getAccessToken('revoke')); - } - - public function testRevokeAccessTokenWithBogusTypeHint() - { - $tokenStorage = new Memory(array( - 'access_tokens' => array( - 'revoke' => array('mytoken'), - ), - )); - - $this->assertEquals(array('mytoken'), $tokenStorage->getAccessToken('revoke')); - $accessToken = new AccessToken($tokenStorage); - $accessToken->revokeToken('revoke', 'foo'); - $this->assertFalse($tokenStorage->getAccessToken('revoke')); - } - - public function testRevokeRefreshTokenWithBogusTypeHint() - { - $tokenStorage = new Memory(array( - 'refresh_tokens' => array( - 'revoke' => array('mytoken'), - ), - )); - - $this->assertEquals(array('mytoken'), $tokenStorage->getRefreshToken('revoke')); - $accessToken = new AccessToken(new Memory, $tokenStorage); - $accessToken->revokeToken('revoke', 'foo'); - $this->assertFalse($tokenStorage->getRefreshToken('revoke')); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/ResponseType/JwtAccessTokenTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/ResponseType/JwtAccessTokenTest.php deleted file mode 100644 index 51b01a9..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/ResponseType/JwtAccessTokenTest.php +++ /dev/null @@ -1,160 +0,0 @@ -getTestServer(); - $jwtResponseType = $server->getResponseType('token'); - - $accessToken = $jwtResponseType->createAccessToken('Test Client ID', 123, 'test', false); - $jwt = new Jwt; - $decodedAccessToken = $jwt->decode($accessToken['access_token'], null, false); - - $this->assertArrayHasKey('id', $decodedAccessToken); - $this->assertArrayHasKey('jti', $decodedAccessToken); - $this->assertArrayHasKey('iss', $decodedAccessToken); - $this->assertArrayHasKey('aud', $decodedAccessToken); - $this->assertArrayHasKey('exp', $decodedAccessToken); - $this->assertArrayHasKey('iat', $decodedAccessToken); - $this->assertArrayHasKey('token_type', $decodedAccessToken); - $this->assertArrayHasKey('scope', $decodedAccessToken); - - $this->assertEquals('https://api.example.com', $decodedAccessToken['iss']); - $this->assertEquals('Test Client ID', $decodedAccessToken['aud']); - $this->assertEquals(123, $decodedAccessToken['sub']); - $delta = $decodedAccessToken['exp'] - $decodedAccessToken['iat']; - $this->assertEquals(3600, $delta); - $this->assertEquals($decodedAccessToken['id'], $decodedAccessToken['jti']); - } - - public function testGrantJwtAccessToken() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'client_credentials', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - )); - $server->handleTokenRequest($request, $response = new Response()); - - $this->assertNotNull($response->getParameter('access_token')); - $this->assertEquals(2, substr_count($response->getParameter('access_token'), '.')); - } - - public function testAccessResourceWithJwtAccessToken() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'client_credentials', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - )); - $server->handleTokenRequest($request, $response = new Response()); - $this->assertNotNull($JwtAccessToken = $response->getParameter('access_token')); - - // make a call to the resource server using the crypto token - $request = TestRequest::createPost(array( - 'access_token' => $JwtAccessToken, - )); - - $this->assertTrue($server->verifyResourceRequest($request)); - } - - public function testAccessResourceWithJwtAccessTokenUsingSecondaryStorage() - { - // add the test parameters in memory - $server = $this->getTestServer(); - $request = TestRequest::createPost(array( - 'grant_type' => 'client_credentials', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - )); - $server->handleTokenRequest($request, $response = new Response()); - $this->assertNotNull($JwtAccessToken = $response->getParameter('access_token')); - - // make a call to the resource server using the crypto token - $request = TestRequest::createPost(array( - 'access_token' => $JwtAccessToken, - )); - - // create a resource server with the "memory" storage from the grant server - $resourceServer = new Server($server->getStorage('client_credentials')); - - $this->assertTrue($resourceServer->verifyResourceRequest($request)); - } - - public function testJwtAccessTokenWithRefreshToken() - { - $server = $this->getTestServer(); - - // add "UserCredentials" grant type and "JwtAccessToken" response type - // and ensure "JwtAccessToken" response type has "RefreshToken" storage - $memoryStorage = Bootstrap::getInstance()->getMemoryStorage(); - $server->addGrantType(new UserCredentials($memoryStorage)); - $server->addGrantType(new RefreshToken($memoryStorage)); - $server->addResponseType(new JwtAccessToken($memoryStorage, $memoryStorage, $memoryStorage), 'token'); - - $request = TestRequest::createPost(array( - 'grant_type' => 'password', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'username' => 'test-username', // valid username - 'password' => 'testpass', // valid password - )); - - // make the call to grant a crypto token - $server->handleTokenRequest($request, $response = new Response()); - $this->assertNotNull($JwtAccessToken = $response->getParameter('access_token')); - $this->assertNotNull($refreshToken = $response->getParameter('refresh_token')); - - // decode token and make sure refresh_token isn't set - list($header, $payload, $signature) = explode('.', $JwtAccessToken); - $decodedToken = json_decode(base64_decode($payload), true); - $this->assertFalse(array_key_exists('refresh_token', $decodedToken)); - - // use the refresh token to get another access token - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'refresh_token' => $refreshToken, - )); - - $server->handleTokenRequest($request, $response = new Response()); - $this->assertNotNull($response->getParameter('access_token')); - } - - private function getTestServer() - { - $memoryStorage = Bootstrap::getInstance()->getMemoryStorage(); - - $storage = array( - 'access_token' => new JwtAccessTokenStorage($memoryStorage), - 'client' => $memoryStorage, - 'client_credentials' => $memoryStorage, - ); - $server = new Server($storage); - $server->addGrantType(new ClientCredentials($memoryStorage)); - - // make the "token" response type a JwtAccessToken - $config = array('issuer' => 'https://api.example.com'); - $server->addResponseType(new JwtAccessToken($memoryStorage, $memoryStorage, null, $config)); - - return $server; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/ScopeTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/ScopeTest.php deleted file mode 100644 index 99f9cf6..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/ScopeTest.php +++ /dev/null @@ -1,42 +0,0 @@ -assertFalse($scopeUtil->checkScope('invalid', 'list of scopes')); - $this->assertTrue($scopeUtil->checkScope('valid', 'valid and-some other-scopes')); - $this->assertTrue($scopeUtil->checkScope('valid another-valid', 'valid another-valid and-some other-scopes')); - // all scopes must match - $this->assertFalse($scopeUtil->checkScope('valid invalid', 'valid and-some other-scopes')); - $this->assertFalse($scopeUtil->checkScope('valid valid2 invalid', 'valid valid2 and-some other-scopes')); - } - - public function testScopeStorage() - { - $scopeUtil = new Scope(); - $this->assertEquals($scopeUtil->getDefaultScope(), null); - - $scopeUtil = new Scope(array( - 'default_scope' => 'default', - 'supported_scopes' => array('this', 'that', 'another'), - )); - $this->assertEquals($scopeUtil->getDefaultScope(), 'default'); - $this->assertTrue($scopeUtil->scopeExists('this that another', 'client_id')); - - $memoryStorage = new Memory(array( - 'default_scope' => 'base', - 'supported_scopes' => array('only-this-one'), - )); - $scopeUtil = new Scope($memoryStorage); - - $this->assertEquals($scopeUtil->getDefaultScope(), 'base'); - $this->assertTrue($scopeUtil->scopeExists('only-this-one', 'client_id')); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/ServerTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/ServerTest.php deleted file mode 100644 index 747e120..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/ServerTest.php +++ /dev/null @@ -1,684 +0,0 @@ -getAuthorizeController(); - } - - /** - * @expectedException LogicException OAuth2\Storage\AccessTokenInterface - **/ - public function testGetAuthorizeControllerWithNoAccessTokenStorageThrowsException() - { - // must set AccessToken or AuthorizationCode - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface')); - $server->getAuthorizeController(); - } - - public function testGetAuthorizeControllerWithClientStorageAndAccessTokenResponseType() - { - // must set AccessToken or AuthorizationCode - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface')); - $server->addResponseType($this->getMock('OAuth2\ResponseType\AccessTokenInterface')); - - $this->assertNotNull($server->getAuthorizeController()); - } - - public function testGetAuthorizeControllerWithClientStorageAndAuthorizationCodeResponseType() - { - // must set AccessToken or AuthorizationCode - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface')); - $server->addResponseType($this->getMock('OAuth2\ResponseType\AuthorizationCodeInterface')); - - $this->assertNotNull($server->getAuthorizeController()); - } - - /** - * @expectedException LogicException allow_implicit - **/ - public function testGetAuthorizeControllerWithClientStorageAndAccessTokenStorageThrowsException() - { - // must set AuthorizationCode or AccessToken / implicit - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface')); - $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface')); - - $this->assertNotNull($server->getAuthorizeController()); - } - - public function testGetAuthorizeControllerWithClientStorageAndAccessTokenStorage() - { - // must set AuthorizationCode or AccessToken / implicit - $server = new Server(array(), array('allow_implicit' => true)); - $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface')); - $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface')); - - $this->assertNotNull($server->getAuthorizeController()); - } - - public function testGetAuthorizeControllerWithClientStorageAndAuthorizationCodeStorage() - { - // must set AccessToken or AuthorizationCode - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\ClientInterface')); - $server->addStorage($this->getMock('OAuth2\Storage\AuthorizationCodeInterface')); - - $this->assertNotNull($server->getAuthorizeController()); - } - - /** - * @expectedException LogicException grant_types - **/ - public function testGetTokenControllerWithGrantTypeStorageThrowsException() - { - $server = new Server(); - $server->getTokenController(); - } - - /** - * @expectedException LogicException OAuth2\Storage\ClientCredentialsInterface - **/ - public function testGetTokenControllerWithNoClientCredentialsStorageThrowsException() - { - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\UserCredentialsInterface')); - $server->getTokenController(); - } - - /** - * @expectedException LogicException OAuth2\Storage\AccessTokenInterface - **/ - public function testGetTokenControllerWithNoAccessTokenStorageThrowsException() - { - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\ClientCredentialsInterface')); - $server->getTokenController(); - } - - public function testGetTokenControllerWithAccessTokenAndClientCredentialsStorage() - { - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface')); - $server->addStorage($this->getMock('OAuth2\Storage\ClientCredentialsInterface')); - $server->getTokenController(); - } - - public function testGetTokenControllerAccessTokenStorageAndClientCredentialsStorageAndGrantTypes() - { - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface')); - $server->addStorage($this->getMock('OAuth2\Storage\ClientCredentialsInterface')); - $server->addGrantType($this->getMockBuilder('OAuth2\GrantType\AuthorizationCode')->disableOriginalConstructor()->getMock()); - $server->getTokenController(); - } - - /** - * @expectedException LogicException OAuth2\Storage\AccessTokenInterface - **/ - public function testGetResourceControllerWithNoAccessTokenStorageThrowsException() - { - $server = new Server(); - $server->getResourceController(); - } - - public function testGetResourceControllerWithAccessTokenStorage() - { - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface')); - $server->getResourceController(); - } - - /** - * @expectedException InvalidArgumentException OAuth2\Storage\AccessTokenInterface - **/ - public function testAddingStorageWithInvalidClass() - { - $server = new Server(); - $server->addStorage(new \StdClass()); - } - - /** - * @expectedException InvalidArgumentException access_token - **/ - public function testAddingStorageWithInvalidKey() - { - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface'), 'nonexistant_storage'); - } - - /** - * @expectedException InvalidArgumentException OAuth2\Storage\AuthorizationCodeInterface - **/ - public function testAddingStorageWithInvalidKeyStorageCombination() - { - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\AccessTokenInterface'), 'authorization_code'); - } - - public function testAddingStorageWithValidKeyOnlySetsThatKey() - { - $server = new Server(); - $server->addStorage($this->getMock('OAuth2\Storage\Memory'), 'access_token'); - - $reflection = new \ReflectionClass($server); - $prop = $reflection->getProperty('storages'); - $prop->setAccessible(true); - - $storages = $prop->getValue($server); // get the private "storages" property - - $this->assertEquals(1, count($storages)); - $this->assertTrue(isset($storages['access_token'])); - $this->assertFalse(isset($storages['authorization_code'])); - } - - public function testAddingClientStorageSetsClientCredentialsStorageByDefault() - { - $server = new Server(); - $memory = $this->getMock('OAuth2\Storage\Memory'); - $server->addStorage($memory, 'client'); - - $client_credentials = $server->getStorage('client_credentials'); - - $this->assertNotNull($client_credentials); - $this->assertEquals($client_credentials, $memory); - } - - public function testAddStorageWithNullValue() - { - $memory = $this->getMock('OAuth2\Storage\Memory'); - $server = new Server($memory); - $server->addStorage(null, 'refresh_token'); - - $client_credentials = $server->getStorage('client_credentials'); - - $this->assertNotNull($client_credentials); - $this->assertEquals($client_credentials, $memory); - - $refresh_token = $server->getStorage('refresh_token'); - - $this->assertNull($refresh_token); - } - - public function testNewServerWithNullStorageValue() - { - $memory = $this->getMock('OAuth2\Storage\Memory'); - $server = new Server(array( - 'client_credentials' => $memory, - 'refresh_token' => null, - )); - - $client_credentials = $server->getStorage('client_credentials'); - - $this->assertNotNull($client_credentials); - $this->assertEquals($client_credentials, $memory); - - $refresh_token = $server->getStorage('refresh_token'); - - $this->assertNull($refresh_token); - } - - public function testAddingClientCredentialsStorageSetsClientStorageByDefault() - { - $server = new Server(); - $memory = $this->getMock('OAuth2\Storage\Memory'); - $server->addStorage($memory, 'client_credentials'); - - $client = $server->getStorage('client'); - - $this->assertNotNull($client); - $this->assertEquals($client, $memory); - } - - public function testSettingClientStorageByDefaultDoesNotOverrideSetStorage() - { - $server = new Server(); - $pdo = $this->getMockBuilder('OAuth2\Storage\Pdo') - ->disableOriginalConstructor()->getMock(); - - $memory = $this->getMock('OAuth2\Storage\Memory'); - - $server->addStorage($pdo, 'client'); - $server->addStorage($memory, 'client_credentials'); - - $client = $server->getStorage('client'); - $client_credentials = $server->getStorage('client_credentials'); - - $this->assertEquals($client, $pdo); - $this->assertEquals($client_credentials, $memory); - } - - public function testAddingResponseType() - { - $storage = $this->getMock('OAuth2\Storage\Memory'); - $storage - ->expects($this->any()) - ->method('getClientDetails') - ->will($this->returnValue(array('client_id' => 'some_client'))); - $storage - ->expects($this->any()) - ->method('checkRestrictedGrantType') - ->will($this->returnValue(true)); - - // add with the "code" key explicitly set - $codeType = new AuthorizationCode($storage); - $server = new Server(); - $server->addStorage($storage); - $server->addResponseType($codeType); - $request = new Request(array( - 'response_type' => 'code', - 'client_id' => 'some_client', - 'redirect_uri' => 'http://example.com', - 'state' => 'xyx', - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - // the response is successful - $this->assertEquals($response->getStatusCode(), 302); - $parts = parse_url($response->getHttpHeader('Location')); - parse_str($parts['query'], $query); - $this->assertTrue(isset($query['code'])); - $this->assertFalse(isset($query['error'])); - - // add with the "code" key not set - $codeType = new AuthorizationCode($storage); - $server = new Server(array($storage), array(), array(), array($codeType)); - $request = new Request(array( - 'response_type' => 'code', - 'client_id' => 'some_client', - 'redirect_uri' => 'http://example.com', - 'state' => 'xyx', - )); - $server->handleAuthorizeRequest($request, $response = new Response(), true); - - // the response is successful - $this->assertEquals($response->getStatusCode(), 302); - $parts = parse_url($response->getHttpHeader('Location')); - parse_str($parts['query'], $query); - $this->assertTrue(isset($query['code'])); - $this->assertFalse(isset($query['error'])); - } - - public function testCustomClientAssertionType() - { - $request = TestRequest::createPost(array( - 'grant_type' => 'authorization_code', - 'client_id' =>'Test Client ID', - 'code' => 'testcode', - )); - // verify the mock clientAssertionType was called as expected - $clientAssertionType = $this->getMock('OAuth2\ClientAssertionType\ClientAssertionTypeInterface', array('validateRequest', 'getClientId')); - $clientAssertionType - ->expects($this->once()) - ->method('validateRequest') - ->will($this->returnValue(true)); - $clientAssertionType - ->expects($this->once()) - ->method('getClientId') - ->will($this->returnValue('Test Client ID')); - - // create mock storage - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server(array($storage), array(), array(), array(), null, null, $clientAssertionType); - $server->handleTokenRequest($request, $response = new Response()); - } - - public function testHttpBasicConfig() - { - // create mock storage - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server(array($storage), array( - 'allow_credentials_in_request_body' => false, - 'allow_public_clients' => false - )); - $server->getTokenController(); - $httpBasic = $server->getClientAssertionType(); - - $reflection = new \ReflectionClass($httpBasic); - $prop = $reflection->getProperty('config'); - $prop->setAccessible(true); - - $config = $prop->getValue($httpBasic); // get the private "config" property - - $this->assertEquals($config['allow_credentials_in_request_body'], false); - $this->assertEquals($config['allow_public_clients'], false); - } - - public function testRefreshTokenConfig() - { - // create mock storage - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server1 = new Server(array($storage)); - $server2 = new Server(array($storage), array('always_issue_new_refresh_token' => true, 'unset_refresh_token_after_use' => false)); - - $server1->getTokenController(); - $refreshToken1 = $server1->getGrantType('refresh_token'); - - $server2->getTokenController(); - $refreshToken2 = $server2->getGrantType('refresh_token'); - - $reflection1 = new \ReflectionClass($refreshToken1); - $prop1 = $reflection1->getProperty('config'); - $prop1->setAccessible(true); - - $reflection2 = new \ReflectionClass($refreshToken2); - $prop2 = $reflection2->getProperty('config'); - $prop2->setAccessible(true); - - // get the private "config" property - $config1 = $prop1->getValue($refreshToken1); - $config2 = $prop2->getValue($refreshToken2); - - $this->assertEquals($config1['always_issue_new_refresh_token'], false); - $this->assertEquals($config2['always_issue_new_refresh_token'], true); - - $this->assertEquals($config1['unset_refresh_token_after_use'], true); - $this->assertEquals($config2['unset_refresh_token_after_use'], false); - } - - /** - * Test setting "always_issue_new_refresh_token" on a server level - * - * @see test/OAuth2/GrantType/RefreshTokenTest::testValidRefreshTokenWithNewRefreshTokenInResponse - **/ - public function testValidRefreshTokenWithNewRefreshTokenInResponse() - { - $storage = Bootstrap::getInstance()->getMemoryStorage(); - $server = new Server($storage, array('always_issue_new_refresh_token' => true)); - - $request = TestRequest::createPost(array( - 'grant_type' => 'refresh_token', // valid grant type - 'client_id' => 'Test Client ID', // valid client id - 'client_secret' => 'TestSecret', // valid client secret - 'refresh_token' => 'test-refreshtoken', // valid refresh token - )); - $token = $server->grantAccessToken($request, new Response()); - $this->assertTrue(isset($token['refresh_token']), 'refresh token should always refresh'); - - $refresh_token = $storage->getRefreshToken($token['refresh_token']); - $this->assertNotNull($refresh_token); - $this->assertEquals($refresh_token['refresh_token'], $token['refresh_token']); - $this->assertEquals($refresh_token['client_id'], $request->request('client_id')); - $this->assertTrue($token['refresh_token'] != 'test-refreshtoken', 'the refresh token returned is not the one used'); - $used_token = $storage->getRefreshToken('test-refreshtoken'); - $this->assertFalse($used_token, 'the refresh token used is no longer valid'); - } - - /** - * @expectedException InvalidArgumentException OAuth2\ResponseType\AuthorizationCodeInterface - **/ - public function testAddingUnknownResponseTypeThrowsException() - { - $server = new Server(); - $server->addResponseType($this->getMock('OAuth2\ResponseType\ResponseTypeInterface')); - } - - /** - * @expectedException LogicException OAuth2\Storage\PublicKeyInterface - **/ - public function testUsingJwtAccessTokensWithoutPublicKeyStorageThrowsException() - { - $server = new Server(array(), array('use_jwt_access_tokens' => true)); - $server->addGrantType($this->getMock('OAuth2\GrantType\GrantTypeInterface')); - $server->addStorage($this->getMock('OAuth2\Storage\ClientCredentialsInterface')); - $server->addStorage($this->getMock('OAuth2\Storage\ClientCredentialsInterface')); - - $server->getTokenController(); - } - - public function testUsingJustJwtAccessTokenStorageWithResourceControllerIsOkay() - { - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - $server = new Server(array($pubkey), array('use_jwt_access_tokens' => true)); - - $this->assertNotNull($server->getResourceController()); - $this->assertInstanceOf('OAuth2\Storage\PublicKeyInterface', $server->getStorage('public_key')); - } - - /** - * @expectedException LogicException OAuth2\Storage\ClientInterface - **/ - public function testUsingJustJwtAccessTokenStorageWithAuthorizeControllerThrowsException() - { - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - $server = new Server(array($pubkey), array('use_jwt_access_tokens' => true)); - $this->assertNotNull($server->getAuthorizeController()); - } - - /** - * @expectedException LogicException grant_types - **/ - public function testUsingJustJwtAccessTokenStorageWithTokenControllerThrowsException() - { - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - $server = new Server(array($pubkey), array('use_jwt_access_tokens' => true)); - $server->getTokenController(); - } - - public function testUsingJwtAccessTokenAndClientStorageWithAuthorizeControllerIsOkay() - { - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - $client = $this->getMock('OAuth2\Storage\ClientInterface'); - $server = new Server(array($pubkey, $client), array('use_jwt_access_tokens' => true, 'allow_implicit' => true)); - $this->assertNotNull($server->getAuthorizeController()); - - $this->assertInstanceOf('OAuth2\ResponseType\JwtAccessToken', $server->getResponseType('token')); - } - - /** - * @expectedException LogicException UserClaims - **/ - public function testUsingOpenIDConnectWithoutUserClaimsThrowsException() - { - $client = $this->getMock('OAuth2\Storage\ClientInterface'); - $server = new Server($client, array('use_openid_connect' => true)); - - $server->getAuthorizeController(); - } - - /** - * @expectedException LogicException PublicKeyInterface - **/ - public function testUsingOpenIDConnectWithoutPublicKeyThrowsException() - { - $client = $this->getMock('OAuth2\Storage\ClientInterface'); - $userclaims = $this->getMock('OAuth2\OPenID\Storage\UserClaimsInterface'); - $server = new Server(array($client, $userclaims), array('use_openid_connect' => true)); - - $server->getAuthorizeController(); - } - - /** - * @expectedException LogicException issuer - **/ - public function testUsingOpenIDConnectWithoutIssuerThrowsException() - { - $client = $this->getMock('OAuth2\Storage\ClientInterface'); - $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface'); - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - $server = new Server(array($client, $userclaims, $pubkey), array('use_openid_connect' => true)); - - $server->getAuthorizeController(); - } - - public function testUsingOpenIDConnectWithIssuerPublicKeyAndUserClaimsIsOkay() - { - $client = $this->getMock('OAuth2\Storage\ClientInterface'); - $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface'); - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - $server = new Server(array($client, $userclaims, $pubkey), array( - 'use_openid_connect' => true, - 'issuer' => 'someguy', - )); - - $server->getAuthorizeController(); - - $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenInterface', $server->getResponseType('id_token')); - $this->assertNull($server->getResponseType('id_token token')); - } - - /** - * @expectedException LogicException OAuth2\ResponseType\AccessTokenInterface - **/ - public function testUsingOpenIDConnectWithAllowImplicitWithoutTokenStorageThrowsException() - { - $client = $this->getMock('OAuth2\Storage\ClientInterface'); - $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface'); - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - $server = new Server(array($client, $userclaims, $pubkey), array( - 'use_openid_connect' => true, - 'issuer' => 'someguy', - 'allow_implicit' => true, - )); - - $server->getAuthorizeController(); - } - - public function testUsingOpenIDConnectWithAllowImplicitAndUseJwtAccessTokensIsOkay() - { - $client = $this->getMock('OAuth2\Storage\ClientInterface'); - $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface'); - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - $server = new Server(array($client, $userclaims, $pubkey), array( - 'use_openid_connect' => true, - 'issuer' => 'someguy', - 'allow_implicit' => true, - 'use_jwt_access_tokens' => true, - )); - - $server->getAuthorizeController(); - - $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenInterface', $server->getResponseType('id_token')); - $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenTokenInterface', $server->getResponseType('id_token token')); - } - - public function testUsingOpenIDConnectWithAllowImplicitAndAccessTokenStorageIsOkay() - { - $client = $this->getMock('OAuth2\Storage\ClientInterface'); - $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface'); - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - $token = $this->getMock('OAuth2\Storage\AccessTokenInterface'); - $server = new Server(array($client, $userclaims, $pubkey, $token), array( - 'use_openid_connect' => true, - 'issuer' => 'someguy', - 'allow_implicit' => true, - )); - - $server->getAuthorizeController(); - - $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenInterface', $server->getResponseType('id_token')); - $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenTokenInterface', $server->getResponseType('id_token token')); - } - - public function testUsingOpenIDConnectWithAllowImplicitAndAccessTokenResponseTypeIsOkay() - { - $client = $this->getMock('OAuth2\Storage\ClientInterface'); - $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface'); - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - // $token = $this->getMock('OAuth2\Storage\AccessTokenInterface'); - $server = new Server(array($client, $userclaims, $pubkey), array( - 'use_openid_connect' => true, - 'issuer' => 'someguy', - 'allow_implicit' => true, - )); - - $token = $this->getMock('OAuth2\ResponseType\AccessTokenInterface'); - $server->addResponseType($token, 'token'); - - $server->getAuthorizeController(); - - $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenInterface', $server->getResponseType('id_token')); - $this->assertInstanceOf('OAuth2\OpenID\ResponseType\IdTokenTokenInterface', $server->getResponseType('id_token token')); - } - - /** - * @expectedException LogicException OAuth2\OpenID\Storage\AuthorizationCodeInterface - **/ - public function testUsingOpenIDConnectWithAuthorizationCodeStorageThrowsException() - { - $client = $this->getMock('OAuth2\Storage\ClientCredentialsInterface'); - $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface'); - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - $token = $this->getMock('OAuth2\Storage\AccessTokenInterface'); - $authcode = $this->getMock('OAuth2\Storage\AuthorizationCodeInterface'); - - $server = new Server(array($client, $userclaims, $pubkey, $token, $authcode), array( - 'use_openid_connect' => true, - 'issuer' => 'someguy' - )); - - $server->getTokenController(); - - $this->assertInstanceOf('OAuth2\OpenID\GrantType\AuthorizationCode', $server->getGrantType('authorization_code')); - } - - public function testUsingOpenIDConnectWithOpenIDAuthorizationCodeStorageCreatesOpenIDAuthorizationCodeGrantType() - { - $client = $this->getMock('OAuth2\Storage\ClientCredentialsInterface'); - $userclaims = $this->getMock('OAuth2\OpenID\Storage\UserClaimsInterface'); - $pubkey = $this->getMock('OAuth2\Storage\PublicKeyInterface'); - $token = $this->getMock('OAuth2\Storage\AccessTokenInterface'); - $authcode = $this->getMock('OAuth2\OpenID\Storage\AuthorizationCodeInterface'); - - $server = new Server(array($client, $userclaims, $pubkey, $token, $authcode), array( - 'use_openid_connect' => true, - 'issuer' => 'someguy' - )); - - $server->getTokenController(); - - $this->assertInstanceOf('OAuth2\OpenID\GrantType\AuthorizationCode', $server->getGrantType('authorization_code')); - } - - public function testMultipleValuedResponseTypeOrderDoesntMatter() - { - $responseType = $this->getMock('OAuth2\OpenID\ResponseType\IdTokenTokenInterface'); - $server = new Server(array(), array(), array(), array( - 'token id_token' => $responseType, - )); - - $this->assertEquals($responseType, $server->getResponseType('id_token token')); - } - - public function testAddGrantTypeWithoutKey() - { - $server = new Server(); - $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($this->getMock('OAuth2\Storage\AuthorizationCodeInterface'))); - - $grantTypes = $server->getGrantTypes(); - $this->assertEquals('authorization_code', key($grantTypes)); - } - - public function testAddGrantTypeWithKey() - { - $server = new Server(); - $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($this->getMock('OAuth2\Storage\AuthorizationCodeInterface')), 'ac'); - - $grantTypes = $server->getGrantTypes(); - $this->assertEquals('ac', key($grantTypes)); - } - - public function testAddGrantTypeWithKeyNotString() - { - $server = new Server(); - $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($this->getMock('OAuth2\Storage\AuthorizationCodeInterface')), 42); - - $grantTypes = $server->getGrantTypes(); - $this->assertEquals('authorization_code', key($grantTypes)); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/AccessTokenTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/AccessTokenTest.php deleted file mode 100644 index 345daae..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/AccessTokenTest.php +++ /dev/null @@ -1,82 +0,0 @@ -markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // assert token we are about to add does not exist - $token = $storage->getAccessToken('newtoken'); - $this->assertFalse($token); - - // add new token - $expires = time() + 20; - $success = $storage->setAccessToken('newtoken', 'client ID', 'SOMEUSERID', $expires); - $this->assertTrue($success); - - $token = $storage->getAccessToken('newtoken'); - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertArrayHasKey('client_id', $token); - $this->assertArrayHasKey('user_id', $token); - $this->assertArrayHasKey('expires', $token); - $this->assertEquals($token['access_token'], 'newtoken'); - $this->assertEquals($token['client_id'], 'client ID'); - $this->assertEquals($token['user_id'], 'SOMEUSERID'); - $this->assertEquals($token['expires'], $expires); - - // change existing token - $expires = time() + 42; - $success = $storage->setAccessToken('newtoken', 'client ID2', 'SOMEOTHERID', $expires); - $this->assertTrue($success); - - $token = $storage->getAccessToken('newtoken'); - $this->assertNotNull($token); - $this->assertArrayHasKey('access_token', $token); - $this->assertArrayHasKey('client_id', $token); - $this->assertArrayHasKey('user_id', $token); - $this->assertArrayHasKey('expires', $token); - $this->assertEquals($token['access_token'], 'newtoken'); - $this->assertEquals($token['client_id'], 'client ID2'); - $this->assertEquals($token['user_id'], 'SOMEOTHERID'); - $this->assertEquals($token['expires'], $expires); - - // add token with scope having an empty string value - $expires = time() + 42; - $success = $storage->setAccessToken('newtoken', 'client ID', 'SOMEOTHERID', $expires, ''); - $this->assertTrue($success); - } - - /** @dataProvider provideStorage */ - public function testUnsetAccessToken(AccessTokenInterface $storage) - { - if ($storage instanceof NullStorage || !method_exists($storage, 'unsetAccessToken')) { - $this->markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // assert token we are unset does not exist - $token = $storage->getAccessToken('revokabletoken'); - $this->assertFalse($token); - - // add new token - $expires = time() + 20; - $success = $storage->setAccessToken('revokabletoken', 'client ID', 'SOMEUSERID', $expires); - $this->assertTrue($success); - - $storage->unsetAccessToken('revokabletoken'); - - // assert token we are unset does not exist - $token = $storage->getAccessToken('revokabletoken'); - $this->assertFalse($token); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/AuthorizationCodeTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/AuthorizationCodeTest.php deleted file mode 100644 index 2d901b5..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/AuthorizationCodeTest.php +++ /dev/null @@ -1,106 +0,0 @@ -markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // nonexistant client_id - $details = $storage->getAuthorizationCode('faketoken'); - $this->assertFalse($details); - - // valid client_id - $details = $storage->getAuthorizationCode('testtoken'); - $this->assertNotNull($details); - } - - /** @dataProvider provideStorage */ - public function testSetAuthorizationCode(AuthorizationCodeInterface $storage) - { - if ($storage instanceof NullStorage) { - $this->markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // assert code we are about to add does not exist - $code = $storage->getAuthorizationCode('newcode'); - $this->assertFalse($code); - - // add new code - $expires = time() + 20; - $success = $storage->setAuthorizationCode('newcode', 'client ID', 'SOMEUSERID', 'http://example.com', $expires); - $this->assertTrue($success); - - $code = $storage->getAuthorizationCode('newcode'); - $this->assertNotNull($code); - $this->assertArrayHasKey('authorization_code', $code); - $this->assertArrayHasKey('client_id', $code); - $this->assertArrayHasKey('user_id', $code); - $this->assertArrayHasKey('redirect_uri', $code); - $this->assertArrayHasKey('expires', $code); - $this->assertEquals($code['authorization_code'], 'newcode'); - $this->assertEquals($code['client_id'], 'client ID'); - $this->assertEquals($code['user_id'], 'SOMEUSERID'); - $this->assertEquals($code['redirect_uri'], 'http://example.com'); - $this->assertEquals($code['expires'], $expires); - - // change existing code - $expires = time() + 42; - $success = $storage->setAuthorizationCode('newcode', 'client ID2', 'SOMEOTHERID', 'http://example.org', $expires); - $this->assertTrue($success); - - $code = $storage->getAuthorizationCode('newcode'); - $this->assertNotNull($code); - $this->assertArrayHasKey('authorization_code', $code); - $this->assertArrayHasKey('client_id', $code); - $this->assertArrayHasKey('user_id', $code); - $this->assertArrayHasKey('redirect_uri', $code); - $this->assertArrayHasKey('expires', $code); - $this->assertEquals($code['authorization_code'], 'newcode'); - $this->assertEquals($code['client_id'], 'client ID2'); - $this->assertEquals($code['user_id'], 'SOMEOTHERID'); - $this->assertEquals($code['redirect_uri'], 'http://example.org'); - $this->assertEquals($code['expires'], $expires); - - // add new code with scope having an empty string value - $expires = time() + 20; - $success = $storage->setAuthorizationCode('newcode', 'client ID', 'SOMEUSERID', 'http://example.com', $expires, ''); - $this->assertTrue($success); - } - - /** @dataProvider provideStorage */ - public function testExpireAccessToken(AccessTokenInterface $storage) - { - if ($storage instanceof NullStorage) { - $this->markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // create a valid code - $expires = time() + 20; - $success = $storage->setAuthorizationCode('code-to-expire', 'client ID', 'SOMEUSERID', 'http://example.com', time() + 20); - $this->assertTrue($success); - - // verify the new code exists - $code = $storage->getAuthorizationCode('code-to-expire'); - $this->assertNotNull($code); - - $this->assertArrayHasKey('authorization_code', $code); - $this->assertEquals($code['authorization_code'], 'code-to-expire'); - - // now expire the code and ensure it's no longer available - $storage->expireAuthorizationCode('code-to-expire'); - $code = $storage->getAuthorizationCode('code-to-expire'); - $this->assertFalse($code); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/ClientCredentialsTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/ClientCredentialsTest.php deleted file mode 100644 index 15289af..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/ClientCredentialsTest.php +++ /dev/null @@ -1,28 +0,0 @@ -markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // nonexistant client_id - $pass = $storage->checkClientCredentials('fakeclient', 'testpass'); - $this->assertFalse($pass); - - // invalid password - $pass = $storage->checkClientCredentials('oauth_test_client', 'invalidcredentials'); - $this->assertFalse($pass); - - // valid credentials - $pass = $storage->checkClientCredentials('oauth_test_client', 'testpass'); - $this->assertTrue($pass); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/ClientTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/ClientTest.php deleted file mode 100644 index d4991c1..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/ClientTest.php +++ /dev/null @@ -1,87 +0,0 @@ -markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // nonexistant client_id - $details = $storage->getClientDetails('fakeclient'); - $this->assertFalse($details); - - // valid client_id - $details = $storage->getClientDetails('oauth_test_client'); - $this->assertNotNull($details); - $this->assertArrayHasKey('client_id', $details); - $this->assertArrayHasKey('client_secret', $details); - $this->assertArrayHasKey('redirect_uri', $details); - } - - /** @dataProvider provideStorage */ - public function testCheckRestrictedGrantType(ClientInterface $storage) - { - if ($storage instanceof NullStorage) { - $this->markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // Check invalid - $pass = $storage->checkRestrictedGrantType('oauth_test_client', 'authorization_code'); - $this->assertFalse($pass); - - // Check valid - $pass = $storage->checkRestrictedGrantType('oauth_test_client', 'implicit'); - $this->assertTrue($pass); - } - - /** @dataProvider provideStorage */ - public function testGetAccessToken(ClientInterface $storage) - { - if ($storage instanceof NullStorage) { - $this->markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // nonexistant client_id - $details = $storage->getAccessToken('faketoken'); - $this->assertFalse($details); - - // valid client_id - $details = $storage->getAccessToken('testtoken'); - $this->assertNotNull($details); - } - - /** @dataProvider provideStorage */ - public function testSaveClient(ClientInterface $storage) - { - if ($storage instanceof NullStorage) { - $this->markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - $clientId = 'some-client-'.rand(); - - // create a new client - $success = $storage->setClientDetails($clientId, 'somesecret', 'http://test.com', 'client_credentials', 'clientscope1', 'brent@brentertainment.com'); - $this->assertTrue($success); - - // valid client_id - $details = $storage->getClientDetails($clientId); - $this->assertEquals($details['client_secret'], 'somesecret'); - $this->assertEquals($details['redirect_uri'], 'http://test.com'); - $this->assertEquals($details['grant_types'], 'client_credentials'); - $this->assertEquals($details['scope'], 'clientscope1'); - $this->assertEquals($details['user_id'], 'brent@brentertainment.com'); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/DynamoDBTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/DynamoDBTest.php deleted file mode 100644 index 2147f09..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/DynamoDBTest.php +++ /dev/null @@ -1,40 +0,0 @@ -getMockBuilder('\Aws\DynamoDb\DynamoDbClient') - ->disableOriginalConstructor() - ->setMethods(array('query')) - ->getMock(); - - $return = $this->getMockBuilder('\Guzzle\Service\Resource\Model') - ->setMethods(array('count', 'toArray')) - ->getMock(); - - $data = array( - 'Items' => array(), - 'Count' => 0, - 'ScannedCount'=> 0 - ); - - $return->expects($this->once()) - ->method('count') - ->will($this->returnValue(count($data))); - - $return->expects($this->once()) - ->method('toArray') - ->will($this->returnValue($data)); - - // should return null default scope if none is set in database - $client->expects($this->once()) - ->method('query') - ->will($this->returnValue($return)); - - $storage = new DynamoDB($client); - $this->assertNull($storage->getDefaultScope()); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/JwtAccessTokenTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/JwtAccessTokenTest.php deleted file mode 100644 index a6acbea..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/JwtAccessTokenTest.php +++ /dev/null @@ -1,41 +0,0 @@ -getMemoryStorage(); - $encryptionUtil = new Jwt(); - - $jwtAccessToken = array( - 'access_token' => rand(), - 'expires' => time() + 100, - 'scope' => 'foo', - ); - - $token = $encryptionUtil->encode($jwtAccessToken, $storage->getPrivateKey(), $storage->getEncryptionAlgorithm()); - - $this->assertNotNull($token); - - $tokenData = $crypto->getAccessToken($token); - - $this->assertTrue(is_array($tokenData)); - - /* assert the decoded token is the same */ - $this->assertEquals($tokenData['access_token'], $jwtAccessToken['access_token']); - $this->assertEquals($tokenData['expires'], $jwtAccessToken['expires']); - $this->assertEquals($tokenData['scope'], $jwtAccessToken['scope']); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/JwtBearerTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/JwtBearerTest.php deleted file mode 100644 index d0ab9b8..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/JwtBearerTest.php +++ /dev/null @@ -1,25 +0,0 @@ -markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // nonexistant client_id - $key = $storage->getClientKey('this-is-not-real', 'nor-is-this'); - $this->assertFalse($key); - - // valid client_id and subject - $key = $storage->getClientKey('oauth_test_client', 'test_subject'); - $this->assertNotNull($key); - $this->assertEquals($key, Bootstrap::getInstance()->getTestPublicKey()); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/PdoTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/PdoTest.php deleted file mode 100644 index 57eb390..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/PdoTest.php +++ /dev/null @@ -1,39 +0,0 @@ -getSqliteDir())); - $storage = new Pdo($pdo); - - $this->assertNotNull($storage->getClientDetails('oauth_test_client')); - } - - public function testCreatePdoStorageUsingDSN() - { - $dsn = sprintf('sqlite://%s', Bootstrap::getInstance()->getSqliteDir()); - $storage = new Pdo($dsn); - - $this->assertNotNull($storage->getClientDetails('oauth_test_client')); - } - - public function testCreatePdoStorageUsingConfig() - { - $config = array('dsn' => sprintf('sqlite://%s', Bootstrap::getInstance()->getSqliteDir())); - $storage = new Pdo($config); - - $this->assertNotNull($storage->getClientDetails('oauth_test_client')); - } - - /** - * @expectedException InvalidArgumentException dsn - */ - public function testCreatePdoStorageWithoutDSNThrowsException() - { - $config = array('username' => 'brent', 'password' => 'brentisaballer'); - $storage = new Pdo($config); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/PublicKeyTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/PublicKeyTest.php deleted file mode 100644 index f851958..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/PublicKeyTest.php +++ /dev/null @@ -1,29 +0,0 @@ -markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - if (!$storage instanceof PublicKeyInterface) { - // incompatible storage - return; - } - - $configDir = Bootstrap::getInstance()->getConfigDir(); - $globalPublicKey = file_get_contents($configDir.'/keys/id_rsa.pub'); - $globalPrivateKey = file_get_contents($configDir.'/keys/id_rsa'); - - /* assert values from storage */ - $this->assertEquals($storage->getPublicKey(), $globalPublicKey); - $this->assertEquals($storage->getPrivateKey(), $globalPrivateKey); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/RefreshTokenTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/RefreshTokenTest.php deleted file mode 100644 index 314c931..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/RefreshTokenTest.php +++ /dev/null @@ -1,41 +0,0 @@ -markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // assert token we are about to add does not exist - $token = $storage->getRefreshToken('refreshtoken'); - $this->assertFalse($token); - - // add new token - $expires = time() + 20; - $success = $storage->setRefreshToken('refreshtoken', 'client ID', 'SOMEUSERID', $expires); - $this->assertTrue($success); - - $token = $storage->getRefreshToken('refreshtoken'); - $this->assertNotNull($token); - $this->assertArrayHasKey('refresh_token', $token); - $this->assertArrayHasKey('client_id', $token); - $this->assertArrayHasKey('user_id', $token); - $this->assertArrayHasKey('expires', $token); - $this->assertEquals($token['refresh_token'], 'refreshtoken'); - $this->assertEquals($token['client_id'], 'client ID'); - $this->assertEquals($token['user_id'], 'SOMEUSERID'); - $this->assertEquals($token['expires'], $expires); - - // add token with scope having an empty string value - $expires = time() + 20; - $success = $storage->setRefreshToken('refreshtoken2', 'client ID', 'SOMEUSERID', $expires, ''); - $this->assertTrue($success); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/ScopeTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/ScopeTest.php deleted file mode 100644 index fd1edeb..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/ScopeTest.php +++ /dev/null @@ -1,53 +0,0 @@ -markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - if (!$storage instanceof ScopeInterface) { - // incompatible storage - return; - } - - //Test getting scopes - $scopeUtil = new Scope($storage); - $this->assertTrue($scopeUtil->scopeExists('supportedscope1')); - $this->assertTrue($scopeUtil->scopeExists('supportedscope1 supportedscope2 supportedscope3')); - $this->assertFalse($scopeUtil->scopeExists('fakescope')); - $this->assertFalse($scopeUtil->scopeExists('supportedscope1 supportedscope2 supportedscope3 fakescope')); - } - - /** @dataProvider provideStorage */ - public function testGetDefaultScope($storage) - { - if ($storage instanceof NullStorage) { - $this->markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - if (!$storage instanceof ScopeInterface) { - // incompatible storage - return; - } - - // test getting default scope - $scopeUtil = new Scope($storage); - $expected = explode(' ', $scopeUtil->getDefaultScope()); - $actual = explode(' ', 'defaultscope1 defaultscope2'); - sort($expected); - sort($actual); - $this->assertEquals($expected, $actual); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/UserCredentialsTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/UserCredentialsTest.php deleted file mode 100644 index 65655a6..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/UserCredentialsTest.php +++ /dev/null @@ -1,40 +0,0 @@ -markTestSkipped('Skipped Storage: ' . $storage->getMessage()); - - return; - } - - // create a new user for testing - $success = $storage->setUser('testusername', 'testpass', 'Test', 'User'); - $this->assertTrue($success); - - // correct credentials - $this->assertTrue($storage->checkUserCredentials('testusername', 'testpass')); - // invalid password - $this->assertFalse($storage->checkUserCredentials('testusername', 'fakepass')); - // invalid username - $this->assertFalse($storage->checkUserCredentials('fakeusername', 'testpass')); - - // invalid username - $this->assertFalse($storage->getUserDetails('fakeusername')); - - // ensure all properties are set - $user = $storage->getUserDetails('testusername'); - $this->assertTrue($user !== false); - $this->assertArrayHasKey('user_id', $user); - $this->assertArrayHasKey('first_name', $user); - $this->assertArrayHasKey('last_name', $user); - $this->assertEquals($user['user_id'], 'testusername'); - $this->assertEquals($user['first_name'], 'Test'); - $this->assertEquals($user['last_name'], 'User'); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/OAuth2/TokenType/BearerTest.php b/vendor/bshaffer/oauth2-server-php/test/OAuth2/TokenType/BearerTest.php deleted file mode 100644 index a2e000e..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/OAuth2/TokenType/BearerTest.php +++ /dev/null @@ -1,58 +0,0 @@ - 'ThisIsMyAccessToken' - )); - $request->server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=UTF-8'; - - $param = $bearer->getAccessTokenParameter($request, $response = new Response()); - $this->assertEquals($param, 'ThisIsMyAccessToken'); - } - - public function testInvalidContentType() - { - $bearer = new Bearer(); - $request = TestRequest::createPost(array( - 'access_token' => 'ThisIsMyAccessToken' - )); - $request->server['CONTENT_TYPE'] = 'application/json; charset=UTF-8'; - - $param = $bearer->getAccessTokenParameter($request, $response = new Response()); - $this->assertNull($param); - $this->assertEquals($response->getStatusCode(), 400); - $this->assertEquals($response->getParameter('error'), 'invalid_request'); - $this->assertEquals($response->getParameter('error_description'), 'The content type for POST requests must be "application/x-www-form-urlencoded"'); - } - - public function testValidRequestUsingAuthorizationHeader() - { - $bearer = new Bearer(); - $request = new TestRequest(); - $request->headers['AUTHORIZATION'] = 'Bearer MyToken'; - $request->server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=UTF-8'; - - $param = $bearer->getAccessTokenParameter($request, $response = new Response()); - $this->assertEquals('MyToken', $param); - } - - public function testValidRequestUsingAuthorizationHeaderCaseInsensitive() - { - $bearer = new Bearer(); - $request = new TestRequest(); - $request->server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=UTF-8'; - $request->headers['Authorization'] = 'Bearer MyToken'; - - $param = $bearer->getAccessTokenParameter($request, $response = new Response()); - $this->assertEquals('MyToken', $param); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/bootstrap.php b/vendor/bshaffer/oauth2-server-php/test/bootstrap.php deleted file mode 100644 index 0a4af07..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/bootstrap.php +++ /dev/null @@ -1,12 +0,0 @@ -cleanupTravisDynamoDb(); diff --git a/vendor/bshaffer/oauth2-server-php/test/config/keys/id_rsa b/vendor/bshaffer/oauth2-server-php/test/config/keys/id_rsa deleted file mode 100644 index e8b9eff..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/config/keys/id_rsa +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXQIBAAKBgQC8fpi06NfVYHAOAnxNMVnTXr/ptsLsNjP+uAt2eO0cc5J9H5XV -8lFVujOrRu/JWi1TDmAvOaf/6A3BphIA1Pwp0AAqlZdwizIum8j0KzpsGYH5qReN -QDwF3oUSKMsQCCGCDHrDYifG/pRi9bN1ZVjEXPr35HJuBe+FQpZTs8DewwIDAQAB -AoGARfNxNknmtx/n1bskZ/01iZRzAge6BLEE0LV6Q4gS7mkRZu/Oyiv39Sl5vUlA -+WdGxLjkBwKNjxGN8Vxw9/ASd8rSsqeAUYIwAeifXrHhj5DBPQT/pDPkeFnp9B1w -C6jo+3AbBQ4/b0ONSIEnCL2xGGglSIAxO17T1ViXp7lzXPECQQDe63nkRdWM0OCb -oaHQPT3E26224maIstrGFUdt9yw3yJf4bOF7TtiPLlLuHsTTge3z+fG6ntC0xG56 -1cl37C3ZAkEA2HdVcRGugNp/qmVz4LJTpD+WZKi73PLAO47wDOrYh9Pn2I6fcEH0 -CPnggt1ko4ujvGzFTvRH64HXa6aPCv1j+wJBAMQMah3VQPNf/DlDVFEUmw9XeBZg -VHaifX851aEjgXLp6qVj9IYCmLiLsAmVa9rr6P7p8asD418nZlaHUHE0eDkCQQCr -uxis6GMx1Ka971jcJX2X696LoxXPd0KsvXySMupv79yagKPa8mgBiwPjrnK+EPVo -cj6iochA/bSCshP/mwFrAkBHEKPi6V6gb94JinCT7x3weahbdp6bJ6/nzBH/p9VA -HoT1JtwNFhGv9BCjmDydshQHfSWpY9NxlccBKL7ITm8R ------END RSA PRIVATE KEY----- \ No newline at end of file diff --git a/vendor/bshaffer/oauth2-server-php/test/config/keys/id_rsa.pub b/vendor/bshaffer/oauth2-server-php/test/config/keys/id_rsa.pub deleted file mode 100644 index 1ac15f5..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/config/keys/id_rsa.pub +++ /dev/null @@ -1,16 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICiDCCAfGgAwIBAgIBADANBgkqhkiG9w0BAQQFADA9MQswCQYDVQQGEwJVUzEL -MAkGA1UECBMCVVQxITAfBgNVBAoTGFZpZ25ldHRlIENvcnBvcmF0aW9uIFNCWDAe -Fw0xMTEwMTUwMzE4MjdaFw0zMTEwMTAwMzE4MjdaMD0xCzAJBgNVBAYTAlVTMQsw -CQYDVQQIEwJVVDEhMB8GA1UEChMYVmlnbmV0dGUgQ29ycG9yYXRpb24gU0JYMIGf -MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8fpi06NfVYHAOAnxNMVnTXr/ptsLs -NjP+uAt2eO0cc5J9H5XV8lFVujOrRu/JWi1TDmAvOaf/6A3BphIA1Pwp0AAqlZdw -izIum8j0KzpsGYH5qReNQDwF3oUSKMsQCCGCDHrDYifG/pRi9bN1ZVjEXPr35HJu -Be+FQpZTs8DewwIDAQABo4GXMIGUMB0GA1UdDgQWBBRe8hrEXm+Yim4YlD5Nx+1K -vCYs9DBlBgNVHSMEXjBcgBRe8hrEXm+Yim4YlD5Nx+1KvCYs9KFBpD8wPTELMAkG -A1UEBhMCVVMxCzAJBgNVBAgTAlVUMSEwHwYDVQQKExhWaWduZXR0ZSBDb3Jwb3Jh -dGlvbiBTQliCAQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQBjhyRD -lM7vnLn6drgQVftW5V9nDFAyPAuiGvMIKFSbiAf1PxXCRn5sfJquwWKsJUi4ZGNl -aViXdFmN6/F13PSM+yg63tpKy0fYqMbTM+Oe5WuSHkSW1VuYNHV+24adgNk/FRDL -FRrlM1f6s9VTLWvwGItjfrof0Ba8Uq7ZDSb9Xg== ------END CERTIFICATE----- \ No newline at end of file diff --git a/vendor/bshaffer/oauth2-server-php/test/config/storage.json b/vendor/bshaffer/oauth2-server-php/test/config/storage.json deleted file mode 100644 index 2d43c07..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/config/storage.json +++ /dev/null @@ -1,177 +0,0 @@ -{ - "authorization_codes": { - "testcode": { - "client_id": "Test Client ID", - "user_id": "", - "redirect_uri": "", - "expires": "9999999999", - "id_token": "IDTOKEN" - }, - "testcode-with-scope": { - "client_id": "Test Client ID", - "user_id": "", - "redirect_uri": "", - "expires": "9999999999", - "scope": "scope1 scope2" - }, - "testcode-expired": { - "client_id": "Test Client ID", - "user_id": "", - "redirect_uri": "", - "expires": "1356998400" - }, - "testcode-empty-secret": { - "client_id": "Test Client ID Empty Secret", - "user_id": "", - "redirect_uri": "", - "expires": "9999999999" - }, - "testcode-openid": { - "client_id": "Test Client ID", - "user_id": "", - "redirect_uri": "", - "expires": "9999999999", - "id_token": "test_id_token" - } - }, - "client_credentials" : { - "Test Client ID": { - "client_secret": "TestSecret" - }, - "Test Client ID with Redirect Uri": { - "client_secret": "TestSecret2", - "redirect_uri": "http://brentertainment.com" - }, - "Test Client ID with Multiple Redirect Uris": { - "client_secret": "TestSecret3", - "redirect_uri": "http://brentertainment.com http://morehazards.com" - }, - "Test Client ID with Redirect Uri Parts": { - "client_secret": "TestSecret4", - "redirect_uri": "http://user:pass@brentertainment.com:2222/authorize/cb?auth_type=oauth&test=true" - }, - "Test Some Other Client": { - "client_secret": "TestSecret3" - }, - "Test Client ID Empty Secret": { - "client_secret": "" - }, - "Test Client ID For Password Grant": { - "grant_types": "password", - "client_secret": "" - }, - "Client ID With User ID": { - "client_secret": "TestSecret", - "user_id": "brent@brentertainment.com" - }, - "oauth_test_client": { - "client_secret": "testpass", - "grant_types": "implicit password" - } - }, - "user_credentials" : { - "test-username": { - "password": "testpass" - }, - "testusername": { - "password": "testpass" - }, - "testuser": { - "password": "password", - "email": "testuser@test.com", - "email_verified": true - }, - "johndoe": { - "password": "password" - } - }, - "refresh_tokens" : { - "test-refreshtoken": { - "refresh_token": "test-refreshtoken", - "client_id": "Test Client ID", - "user_id": "test-username", - "expires": 0, - "scope": null - }, - "test-refreshtoken-with-scope": { - "refresh_token": "test-refreshtoken", - "client_id": "Test Client ID", - "user_id": "test-username", - "expires": 0, - "scope": "scope1 scope2" - } - }, - "access_tokens" : { - "accesstoken-expired": { - "access_token": "accesstoken-expired", - "client_id": "Test Client ID", - "expires": 1234567, - "scope": null - }, - "accesstoken-scope": { - "access_token": "accesstoken-scope", - "client_id": "Test Client ID", - "expires": 99999999900, - "scope": "testscope" - }, - "accesstoken-openid-connect": { - "access_token": "accesstoken-openid-connect", - "client_id": "Test Client ID", - "user_id": "testuser", - "expires": 99999999900, - "scope": "openid email" - }, - "accesstoken-malformed": { - "access_token": "accesstoken-mallformed", - "expires": 99999999900, - "scope": "testscope" - } - }, - "jwt": { - "Test Client ID": { - "key": "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5/SxVlE8gnpFqCxgl2wjhzY7u\ncEi00s0kUg3xp7lVEvgLgYcAnHiWp+gtSjOFfH2zsvpiWm6Lz5f743j/FEzHIO1o\nwR0p4d9pOaJK07d01+RzoQLOIQAgXrr4T1CCWUesncwwPBVCyy2Mw3Nmhmr9MrF8\nUlvdRKBxriRnlP3qJQIDAQAB\n-----END PUBLIC KEY-----", - "subject": "testuser@ourdomain.com" - }, - "Test Client ID PHP-5.2": { - "key": "mysecretkey", - "subject": "testuser@ourdomain.com" - }, - "Missing Key Client": { - "key": null, - "subject": "testuser@ourdomain.com" - }, - "Missing Key Client PHP-5.2": { - "key": null, - "subject": "testuser@ourdomain.com" - }, - "oauth_test_client": { - "key": "-----BEGIN CERTIFICATE-----\nMIICiDCCAfGgAwIBAgIBADANBgkqhkiG9w0BAQQFADA9MQswCQYDVQQGEwJVUzEL\nMAkGA1UECBMCVVQxITAfBgNVBAoTGFZpZ25ldHRlIENvcnBvcmF0aW9uIFNCWDAe\nFw0xMTEwMTUwMzE4MjdaFw0zMTEwMTAwMzE4MjdaMD0xCzAJBgNVBAYTAlVTMQsw\nCQYDVQQIEwJVVDEhMB8GA1UEChMYVmlnbmV0dGUgQ29ycG9yYXRpb24gU0JYMIGf\nMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8fpi06NfVYHAOAnxNMVnTXr/ptsLs\nNjP+uAt2eO0cc5J9H5XV8lFVujOrRu/JWi1TDmAvOaf/6A3BphIA1Pwp0AAqlZdw\nizIum8j0KzpsGYH5qReNQDwF3oUSKMsQCCGCDHrDYifG/pRi9bN1ZVjEXPr35HJu\nBe+FQpZTs8DewwIDAQABo4GXMIGUMB0GA1UdDgQWBBRe8hrEXm+Yim4YlD5Nx+1K\nvCYs9DBlBgNVHSMEXjBcgBRe8hrEXm+Yim4YlD5Nx+1KvCYs9KFBpD8wPTELMAkG\nA1UEBhMCVVMxCzAJBgNVBAgTAlVUMSEwHwYDVQQKExhWaWduZXR0ZSBDb3Jwb3Jh\ndGlvbiBTQliCAQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQBjhyRD\nlM7vnLn6drgQVftW5V9nDFAyPAuiGvMIKFSbiAf1PxXCRn5sfJquwWKsJUi4ZGNl\naViXdFmN6/F13PSM+yg63tpKy0fYqMbTM+Oe5WuSHkSW1VuYNHV+24adgNk/FRDL\nFRrlM1f6s9VTLWvwGItjfrof0Ba8Uq7ZDSb9Xg==\n-----END CERTIFICATE-----", - "subject": "test_subject" - } - }, - "jti": [ - { - "issuer": "Test Client ID", - "subject": "testuser@ourdomain.com", - "audience": "http://myapp.com/oauth/auth", - "expires": 99999999900, - "jti": "used_jti" - } - ], - "supported_scopes" : [ - "scope1", - "scope2", - "scope3", - "clientscope1", - "clientscope2", - "clientscope3", - "supportedscope1", - "supportedscope2", - "supportedscope3", - "supportedscope4" - ], - "keys": { - "public_key": "-----BEGIN CERTIFICATE-----\nMIICiDCCAfGgAwIBAgIBADANBgkqhkiG9w0BAQQFADA9MQswCQYDVQQGEwJVUzEL\nMAkGA1UECBMCVVQxITAfBgNVBAoTGFZpZ25ldHRlIENvcnBvcmF0aW9uIFNCWDAe\nFw0xMTEwMTUwMzE4MjdaFw0zMTEwMTAwMzE4MjdaMD0xCzAJBgNVBAYTAlVTMQsw\nCQYDVQQIEwJVVDEhMB8GA1UEChMYVmlnbmV0dGUgQ29ycG9yYXRpb24gU0JYMIGf\nMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8fpi06NfVYHAOAnxNMVnTXr/ptsLs\nNjP+uAt2eO0cc5J9H5XV8lFVujOrRu/JWi1TDmAvOaf/6A3BphIA1Pwp0AAqlZdw\nizIum8j0KzpsGYH5qReNQDwF3oUSKMsQCCGCDHrDYifG/pRi9bN1ZVjEXPr35HJu\nBe+FQpZTs8DewwIDAQABo4GXMIGUMB0GA1UdDgQWBBRe8hrEXm+Yim4YlD5Nx+1K\nvCYs9DBlBgNVHSMEXjBcgBRe8hrEXm+Yim4YlD5Nx+1KvCYs9KFBpD8wPTELMAkG\nA1UEBhMCVVMxCzAJBgNVBAgTAlVUMSEwHwYDVQQKExhWaWduZXR0ZSBDb3Jwb3Jh\ndGlvbiBTQliCAQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQBjhyRD\nlM7vnLn6drgQVftW5V9nDFAyPAuiGvMIKFSbiAf1PxXCRn5sfJquwWKsJUi4ZGNl\naViXdFmN6/F13PSM+yg63tpKy0fYqMbTM+Oe5WuSHkSW1VuYNHV+24adgNk/FRDL\nFRrlM1f6s9VTLWvwGItjfrof0Ba8Uq7ZDSb9Xg==\n-----END CERTIFICATE-----", - "private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQC8fpi06NfVYHAOAnxNMVnTXr/ptsLsNjP+uAt2eO0cc5J9H5XV\n8lFVujOrRu/JWi1TDmAvOaf/6A3BphIA1Pwp0AAqlZdwizIum8j0KzpsGYH5qReN\nQDwF3oUSKMsQCCGCDHrDYifG/pRi9bN1ZVjEXPr35HJuBe+FQpZTs8DewwIDAQAB\nAoGARfNxNknmtx/n1bskZ/01iZRzAge6BLEE0LV6Q4gS7mkRZu/Oyiv39Sl5vUlA\n+WdGxLjkBwKNjxGN8Vxw9/ASd8rSsqeAUYIwAeifXrHhj5DBPQT/pDPkeFnp9B1w\nC6jo+3AbBQ4/b0ONSIEnCL2xGGglSIAxO17T1ViXp7lzXPECQQDe63nkRdWM0OCb\noaHQPT3E26224maIstrGFUdt9yw3yJf4bOF7TtiPLlLuHsTTge3z+fG6ntC0xG56\n1cl37C3ZAkEA2HdVcRGugNp/qmVz4LJTpD+WZKi73PLAO47wDOrYh9Pn2I6fcEH0\nCPnggt1ko4ujvGzFTvRH64HXa6aPCv1j+wJBAMQMah3VQPNf/DlDVFEUmw9XeBZg\nVHaifX851aEjgXLp6qVj9IYCmLiLsAmVa9rr6P7p8asD418nZlaHUHE0eDkCQQCr\nuxis6GMx1Ka971jcJX2X696LoxXPd0KsvXySMupv79yagKPa8mgBiwPjrnK+EPVo\ncj6iochA/bSCshP/mwFrAkBHEKPi6V6gb94JinCT7x3weahbdp6bJ6/nzBH/p9VA\nHoT1JtwNFhGv9BCjmDydshQHfSWpY9NxlccBKL7ITm8R\n-----END RSA PRIVATE KEY-----" - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Request/TestRequest.php b/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Request/TestRequest.php deleted file mode 100644 index 7bbce28..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Request/TestRequest.php +++ /dev/null @@ -1,61 +0,0 @@ -query = $_GET; - $this->request = $_POST; - $this->server = $_SERVER; - $this->headers = array(); - } - - public function query($name, $default = null) - { - return isset($this->query[$name]) ? $this->query[$name] : $default; - } - - public function request($name, $default = null) - { - return isset($this->request[$name]) ? $this->request[$name] : $default; - } - - public function server($name, $default = null) - { - return isset($this->server[$name]) ? $this->server[$name] : $default; - } - - public function getAllQueryParameters() - { - return $this->query; - } - - public function setQuery(array $query) - { - $this->query = $query; - } - - public function setPost(array $params) - { - $this->server['REQUEST_METHOD'] = 'POST'; - $this->request = $params; - } - - public static function createPost(array $params = array()) - { - $request = new self(); - $request->setPost($params); - - return $request; - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Storage/BaseTest.php b/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Storage/BaseTest.php deleted file mode 100755 index 921d525..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Storage/BaseTest.php +++ /dev/null @@ -1,34 +0,0 @@ -getMemoryStorage(); - $sqlite = Bootstrap::getInstance()->getSqlitePdo(); - $mysql = Bootstrap::getInstance()->getMysqlPdo(); - $postgres = Bootstrap::getInstance()->getPostgresPdo(); - $mongo = Bootstrap::getInstance()->getMongo(); - $redis = Bootstrap::getInstance()->getRedisStorage(); - $cassandra = Bootstrap::getInstance()->getCassandraStorage(); - $dynamodb = Bootstrap::getInstance()->getDynamoDbStorage(); - $couchbase = Bootstrap::getInstance()->getCouchbase(); - - /* hack until we can fix "default_scope" dependencies in other tests */ - $memory->defaultScope = 'defaultscope1 defaultscope2'; - - return array( - array($memory), - array($sqlite), - array($mysql), - array($postgres), - array($mongo), - array($redis), - array($cassandra), - array($dynamodb), - array($couchbase), - ); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Storage/Bootstrap.php b/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Storage/Bootstrap.php deleted file mode 100755 index efb6644..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Storage/Bootstrap.php +++ /dev/null @@ -1,884 +0,0 @@ -configDir = __DIR__.'/../../../config'; - } - - public static function getInstance() - { - if (!self::$instance) { - self::$instance = new self(); - } - - return self::$instance; - } - - public function getSqlitePdo() - { - if (!$this->sqlite) { - $this->removeSqliteDb(); - $pdo = new \PDO(sprintf('sqlite://%s', $this->getSqliteDir())); - $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $this->createSqliteDb($pdo); - - $this->sqlite = new Pdo($pdo); - } - - return $this->sqlite; - } - - public function getPostgresPdo() - { - if (!$this->postgres) { - if (in_array('pgsql', \PDO::getAvailableDrivers())) { - $this->removePostgresDb(); - $this->createPostgresDb(); - if ($pdo = $this->getPostgresDriver()) { - $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $this->populatePostgresDb($pdo); - $this->postgres = new Pdo($pdo); - } - } else { - $this->postgres = new NullStorage('Postgres', 'Missing postgres PDO extension.'); - } - } - - return $this->postgres; - } - - public function getPostgresDriver() - { - try { - $pdo = new \PDO('pgsql:host=localhost;dbname=oauth2_server_php', 'postgres'); - - return $pdo; - } catch (\PDOException $e) { - $this->postgres = new NullStorage('Postgres', $e->getMessage()); - } - } - - public function getMemoryStorage() - { - return new Memory(json_decode(file_get_contents($this->configDir. '/storage.json'), true)); - } - - public function getRedisStorage() - { - if (!$this->redis) { - if (class_exists('Predis\Client')) { - $redis = new \Predis\Client(); - if ($this->testRedisConnection($redis)) { - $redis->flushdb(); - $this->redis = new Redis($redis); - $this->createRedisDb($this->redis); - } else { - $this->redis = new NullStorage('Redis', 'Unable to connect to redis server on port 6379'); - } - } else { - $this->redis = new NullStorage('Redis', 'Missing redis library. Please run "composer.phar require predis/predis:dev-master"'); - } - } - - return $this->redis; - } - - private function testRedisConnection(\Predis\Client $redis) - { - try { - $redis->connect(); - } catch (\Predis\CommunicationException $exception) { - // we were unable to connect to the redis server - return false; - } - - return true; - } - - public function getMysqlPdo() - { - if (!$this->mysql) { - $pdo = null; - try { - $pdo = new \PDO('mysql:host=localhost;', 'root'); - } catch (\PDOException $e) { - $this->mysql = new NullStorage('MySQL', 'Unable to connect to MySQL on root@localhost'); - } - - if ($pdo) { - $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $this->removeMysqlDb($pdo); - $this->createMysqlDb($pdo); - - $this->mysql = new Pdo($pdo); - } - } - - return $this->mysql; - } - - public function getMongo() - { - if (!$this->mongo) { - $skipMongo = $this->getEnvVar('SKIP_MONGO_TESTS'); - if (!$skipMongo && class_exists('MongoClient')) { - $mongo = new \MongoClient('mongodb://localhost:27017', array('connect' => false)); - if ($this->testMongoConnection($mongo)) { - $db = $mongo->oauth2_server_php; - $this->removeMongoDb($db); - $this->createMongoDb($db); - - $this->mongo = new Mongo($db); - } else { - $this->mongo = new NullStorage('Mongo', 'Unable to connect to mongo server on "localhost:27017"'); - } - } else { - $this->mongo = new NullStorage('Mongo', 'Missing mongo php extension. Please install mongo.so'); - } - } - - return $this->mongo; - } - - private function testMongoConnection(\MongoClient $mongo) - { - try { - $mongo->connect(); - } catch (\MongoConnectionException $e) { - return false; - } - - return true; - } - - public function getCouchbase() - { - if (!$this->couchbase) { - if ($this->getEnvVar('SKIP_COUCHBASE_TESTS')) { - $this->couchbase = new NullStorage('Couchbase', 'Skipping Couchbase tests'); - } elseif (!class_exists('Couchbase')) { - $this->couchbase = new NullStorage('Couchbase', 'Missing Couchbase php extension. Please install couchbase.so'); - } else { - // round-about way to make sure couchbase is working - // this is required because it throws a "floating point exception" otherwise - $code = "new \Couchbase(array('localhost:8091'), '', '', 'auth', false);"; - $exec = sprintf('php -r "%s"', $code); - $ret = exec($exec, $test, $var); - if ($ret != 0) { - $couchbase = new \Couchbase(array('localhost:8091'), '', '', 'auth', false); - if ($this->testCouchbaseConnection($couchbase)) { - $this->clearCouchbase($couchbase); - $this->createCouchbaseDB($couchbase); - - $this->couchbase = new CouchbaseDB($couchbase); - } else { - $this->couchbase = new NullStorage('Couchbase', 'Unable to connect to Couchbase server on "localhost:8091"'); - } - } else { - $this->couchbase = new NullStorage('Couchbase', 'Error while trying to connect to Couchbase'); - } - } - } - - return $this->couchbase; - } - - private function testCouchbaseConnection(\Couchbase $couchbase) - { - try { - if (count($couchbase->getServers()) > 0) { - return true; - } - } catch (\CouchbaseException $e) { - return false; - } - - return true; - } - - public function getCassandraStorage() - { - if (!$this->cassandra) { - if (class_exists('phpcassa\ColumnFamily')) { - $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_test', array('127.0.0.1:9160')); - if ($this->testCassandraConnection($cassandra)) { - $this->removeCassandraDb(); - $this->cassandra = new Cassandra($cassandra); - $this->createCassandraDb($this->cassandra); - } else { - $this->cassandra = new NullStorage('Cassandra', 'Unable to connect to cassandra server on "127.0.0.1:9160"'); - } - } else { - $this->cassandra = new NullStorage('Cassandra', 'Missing cassandra library. Please run "composer.phar require thobbs/phpcassa:dev-master"'); - } - } - - return $this->cassandra; - } - - private function testCassandraConnection(\phpcassa\Connection\ConnectionPool $cassandra) - { - try { - new \phpcassa\SystemManager('localhost:9160'); - } catch (\Exception $e) { - return false; - } - - return true; - } - - private function removeCassandraDb() - { - $sys = new \phpcassa\SystemManager('localhost:9160'); - - try { - $sys->drop_keyspace('oauth2_test'); - } catch (\cassandra\InvalidRequestException $e) { - - } - } - - private function createCassandraDb(Cassandra $storage) - { - // create the cassandra keyspace and column family - $sys = new \phpcassa\SystemManager('localhost:9160'); - - $sys->create_keyspace('oauth2_test', array( - "strategy_class" => \phpcassa\Schema\StrategyClass::SIMPLE_STRATEGY, - "strategy_options" => array('replication_factor' => '1') - )); - - $sys->create_column_family('oauth2_test', 'auth'); - $cassandra = new \phpcassa\Connection\ConnectionPool('oauth2_test', array('127.0.0.1:9160')); - $cf = new \phpcassa\ColumnFamily($cassandra, 'auth'); - - // populate the data - $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); - $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); - $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); - - $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); - $storage->setScope('defaultscope1 defaultscope2', null, 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); - $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); - - $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); - - $cf->insert("oauth_public_keys:ClientID_One", array('__data' => json_encode(array("public_key" => "client_1_public", "private_key" => "client_1_private", "encryption_algorithm" => "RS256")))); - $cf->insert("oauth_public_keys:ClientID_Two", array('__data' => json_encode(array("public_key" => "client_2_public", "private_key" => "client_2_private", "encryption_algorithm" => "RS256")))); - $cf->insert("oauth_public_keys:", array('__data' => json_encode(array("public_key" => $this->getTestPublicKey(), "private_key" => $this->getTestPrivateKey(), "encryption_algorithm" => "RS256")))); - - $cf->insert("oauth_users:testuser", array('__data' =>json_encode(array("password" => "password", "email" => "testuser@test.com", "email_verified" => true)))); - - } - - private function createSqliteDb(\PDO $pdo) - { - $this->runPdoSql($pdo); - } - - private function removeSqliteDb() - { - if (file_exists($this->getSqliteDir())) { - unlink($this->getSqliteDir()); - } - } - - private function createMysqlDb(\PDO $pdo) - { - $pdo->exec('CREATE DATABASE oauth2_server_php'); - $pdo->exec('USE oauth2_server_php'); - $this->runPdoSql($pdo); - } - - private function removeMysqlDb(\PDO $pdo) - { - $pdo->exec('DROP DATABASE IF EXISTS oauth2_server_php'); - } - - private function createPostgresDb() - { - if (!`psql postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='postgres'"`) { - `createuser -s -r postgres`; - } - - `createdb -O postgres oauth2_server_php`; - } - - private function populatePostgresDb(\PDO $pdo) - { - $this->runPdoSql($pdo); - } - - private function removePostgresDb() - { - if (trim(`psql -l | grep oauth2_server_php | wc -l`)) { - `dropdb oauth2_server_php`; - } - } - - public function runPdoSql(\PDO $pdo) - { - $storage = new Pdo($pdo); - foreach (explode(';', $storage->getBuildSql()) as $statement) { - $result = $pdo->exec($statement); - } - - // set up scopes - $sql = 'INSERT INTO oauth_scopes (scope) VALUES (?)'; - foreach (explode(' ', 'supportedscope1 supportedscope2 supportedscope3 supportedscope4 clientscope1 clientscope2 clientscope3') as $supportedScope) { - $pdo->prepare($sql)->execute(array($supportedScope)); - } - - $sql = 'INSERT INTO oauth_scopes (scope, is_default) VALUES (?, ?)'; - foreach (array('defaultscope1', 'defaultscope2') as $defaultScope) { - $pdo->prepare($sql)->execute(array($defaultScope, true)); - } - - // set up clients - $sql = 'INSERT INTO oauth_clients (client_id, client_secret, scope, grant_types) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('Test Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); - $pdo->prepare($sql)->execute(array('Test Client ID 2', 'TestSecret', 'clientscope1 clientscope2 clientscope3', null)); - $pdo->prepare($sql)->execute(array('Test Default Scope Client ID', 'TestSecret', 'clientscope1 clientscope2', null)); - $pdo->prepare($sql)->execute(array('oauth_test_client', 'testpass', null, 'implicit password')); - - // set up misc - $sql = 'INSERT INTO oauth_access_tokens (access_token, client_id, expires, user_id) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('testtoken', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), null)); - $pdo->prepare($sql)->execute(array('accesstoken-openid-connect', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')), 'testuser')); - - $sql = 'INSERT INTO oauth_authorization_codes (authorization_code, client_id, expires) VALUES (?, ?, ?)'; - $pdo->prepare($sql)->execute(array('testcode', 'Some Client', date('Y-m-d H:i:s', strtotime('+1 hour')))); - - $sql = 'INSERT INTO oauth_users (username, password, email, email_verified) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('testuser', 'password', 'testuser@test.com', true)); - - $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array('ClientID_One', 'client_1_public', 'client_1_private', 'RS256')); - $pdo->prepare($sql)->execute(array('ClientID_Two', 'client_2_public', 'client_2_private', 'RS256')); - - $sql = 'INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (?, ?, ?, ?)'; - $pdo->prepare($sql)->execute(array(null, $this->getTestPublicKey(), $this->getTestPrivateKey(), 'RS256')); - - $sql = 'INSERT INTO oauth_jwt (client_id, subject, public_key) VALUES (?, ?, ?)'; - $pdo->prepare($sql)->execute(array('oauth_test_client', 'test_subject', $this->getTestPublicKey())); - } - - public function getSqliteDir() - { - return $this->configDir. '/test.sqlite'; - } - - public function getConfigDir() - { - return $this->configDir; - } - - private function createCouchbaseDB(\Couchbase $db) - { - $db->set('oauth_clients-oauth_test_client',json_encode(array( - 'client_id' => "oauth_test_client", - 'client_secret' => "testpass", - 'redirect_uri' => "http://example.com", - 'grant_types' => 'implicit password' - ))); - - $db->set('oauth_access_tokens-testtoken',json_encode(array( - 'access_token' => "testtoken", - 'client_id' => "Some Client" - ))); - - $db->set('oauth_authorization_codes-testcode',json_encode(array( - 'access_token' => "testcode", - 'client_id' => "Some Client" - ))); - - $db->set('oauth_users-testuser',json_encode(array( - 'username' => "testuser", - 'password' => "password" - ))); - - $db->set('oauth_jwt-oauth_test_client',json_encode(array( - 'client_id' => 'oauth_test_client', - 'key' => $this->getTestPublicKey(), - 'subject' => 'test_subject', - ))); - } - - private function clearCouchbase(\Couchbase $cb) - { - $cb->delete('oauth_authorization_codes-new-openid-code'); - $cb->delete('oauth_access_tokens-newtoken'); - $cb->delete('oauth_authorization_codes-newcode'); - $cb->delete('oauth_refresh_tokens-refreshtoken'); - } - - private function createMongoDb(\MongoDB $db) - { - $db->oauth_clients->insert(array( - 'client_id' => "oauth_test_client", - 'client_secret' => "testpass", - 'redirect_uri' => "http://example.com", - 'grant_types' => 'implicit password' - )); - - $db->oauth_access_tokens->insert(array( - 'access_token' => "testtoken", - 'client_id' => "Some Client" - )); - - $db->oauth_authorization_codes->insert(array( - 'authorization_code' => "testcode", - 'client_id' => "Some Client" - )); - - $db->oauth_users->insert(array( - 'username' => "testuser", - 'password' => "password" - )); - - $db->oauth_jwt->insert(array( - 'client_id' => 'oauth_test_client', - 'key' => $this->getTestPublicKey(), - 'subject' => 'test_subject', - )); - } - - private function createRedisDb(Redis $storage) - { - $storage->setClientDetails("oauth_test_client", "testpass", "http://example.com", 'implicit password'); - $storage->setAccessToken("testtoken", "Some Client", '', time() + 1000); - $storage->setAuthorizationCode("testcode", "Some Client", '', '', time() + 1000); - $storage->setUser("testuser", "password"); - - $storage->setScope('supportedscope1 supportedscope2 supportedscope3 supportedscope4'); - $storage->setScope('defaultscope1 defaultscope2', null, 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Client ID 2'); - $storage->setScope('clientscope1 clientscope2', 'Test Client ID 2', 'default'); - - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID'); - $storage->setScope('clientscope1 clientscope2', 'Test Default Scope Client ID', 'default'); - - $storage->setScope('clientscope1 clientscope2 clientscope3', 'Test Default Scope Client ID 2'); - $storage->setScope('clientscope3', 'Test Default Scope Client ID 2', 'default'); - - $storage->setClientKey('oauth_test_client', $this->getTestPublicKey(), 'test_subject'); - } - - public function removeMongoDb(\MongoDB $db) - { - $db->drop(); - } - - public function getTestPublicKey() - { - return file_get_contents(__DIR__.'/../../../config/keys/id_rsa.pub'); - } - - private function getTestPrivateKey() - { - return file_get_contents(__DIR__.'/../../../config/keys/id_rsa'); - } - - public function getDynamoDbStorage() - { - if (!$this->dynamodb) { - // only run once per travis build - if (true == $this->getEnvVar('TRAVIS')) { - if (self::DYNAMODB_PHP_VERSION != $this->getEnvVar('TRAVIS_PHP_VERSION')) { - $this->dynamodb = new NullStorage('DynamoDb', 'Skipping for travis.ci - only run once per build'); - - return; - } - } - if (class_exists('\Aws\DynamoDb\DynamoDbClient')) { - if ($client = $this->getDynamoDbClient()) { - // travis runs a unique set of tables per build, to avoid conflict - $prefix = ''; - if ($build_id = $this->getEnvVar('TRAVIS_JOB_NUMBER')) { - $prefix = sprintf('build_%s_', $build_id); - } else { - if (!$this->deleteDynamoDb($client, $prefix, true)) { - return $this->dynamodb = new NullStorage('DynamoDb', 'Timed out while waiting for DynamoDB deletion (30 seconds)'); - } - } - $this->createDynamoDb($client, $prefix); - $this->populateDynamoDb($client, $prefix); - $config = array( - 'client_table' => $prefix.'oauth_clients', - 'access_token_table' => $prefix.'oauth_access_tokens', - 'refresh_token_table' => $prefix.'oauth_refresh_tokens', - 'code_table' => $prefix.'oauth_authorization_codes', - 'user_table' => $prefix.'oauth_users', - 'jwt_table' => $prefix.'oauth_jwt', - 'scope_table' => $prefix.'oauth_scopes', - 'public_key_table' => $prefix.'oauth_public_keys', - ); - $this->dynamodb = new DynamoDB($client, $config); - } elseif (!$this->dynamodb) { - $this->dynamodb = new NullStorage('DynamoDb', 'unable to connect to DynamoDB'); - } - } else { - $this->dynamodb = new NullStorage('DynamoDb', 'Missing DynamoDB library. Please run "composer.phar require aws/aws-sdk-php:dev-master'); - } - } - - return $this->dynamodb; - } - - private function getDynamoDbClient() - { - $config = array(); - // check for environment variables - if (($key = $this->getEnvVar('AWS_ACCESS_KEY_ID')) && ($secret = $this->getEnvVar('AWS_SECRET_KEY'))) { - $config['key'] = $key; - $config['secret'] = $secret; - } else { - // fall back on ~/.aws/credentials file - // @see http://docs.aws.amazon.com/aws-sdk-php/guide/latest/credentials.html#credential-profiles - if (!file_exists($this->getEnvVar('HOME') . '/.aws/credentials')) { - $this->dynamodb = new NullStorage('DynamoDb', 'No aws credentials file found, and no AWS_ACCESS_KEY_ID or AWS_SECRET_KEY environment variable set'); - - return; - } - - // set profile in AWS_PROFILE environment variable, defaults to "default" - $config['profile'] = $this->getEnvVar('AWS_PROFILE', 'default'); - } - - // set region in AWS_REGION environment variable, defaults to "us-east-1" - $config['region'] = $this->getEnvVar('AWS_REGION', \Aws\Common\Enum\Region::US_EAST_1); - - return \Aws\DynamoDb\DynamoDbClient::factory($config); - } - - private function deleteDynamoDb(\Aws\DynamoDb\DynamoDbClient $client, $prefix = null, $waitForDeletion = false) - { - $tablesList = explode(' ', 'oauth_access_tokens oauth_authorization_codes oauth_clients oauth_jwt oauth_public_keys oauth_refresh_tokens oauth_scopes oauth_users'); - $nbTables = count($tablesList); - - // Delete all table. - foreach ($tablesList as $key => $table) { - try { - $client->deleteTable(array('TableName' => $prefix.$table)); - } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { - // Table does not exist : nothing to do - } - } - - // Wait for deleting - if ($waitForDeletion) { - $retries = 5; - $nbTableDeleted = 0; - while ($nbTableDeleted != $nbTables) { - $nbTableDeleted = 0; - foreach ($tablesList as $key => $table) { - try { - $result = $client->describeTable(array('TableName' => $prefix.$table)); - } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { - // Table does not exist : nothing to do - $nbTableDeleted++; - } - } - if ($nbTableDeleted != $nbTables) { - if ($retries < 0) { - // we are tired of waiting - return false; - } - sleep(5); - echo "Sleeping 5 seconds for DynamoDB ($retries more retries)...\n"; - $retries--; - } - } - } - - return true; - } - - private function createDynamoDb(\Aws\DynamoDb\DynamoDbClient $client, $prefix = null) - { - $tablesList = explode(' ', 'oauth_access_tokens oauth_authorization_codes oauth_clients oauth_jwt oauth_public_keys oauth_refresh_tokens oauth_scopes oauth_users'); - $nbTables = count($tablesList); - $client->createTable(array( - 'TableName' => $prefix.'oauth_access_tokens', - 'AttributeDefinitions' => array( - array('AttributeName' => 'access_token','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'access_token','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_authorization_codes', - 'AttributeDefinitions' => array( - array('AttributeName' => 'authorization_code','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'authorization_code','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_clients', - 'AttributeDefinitions' => array( - array('AttributeName' => 'client_id','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'client_id','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_jwt', - 'AttributeDefinitions' => array( - array('AttributeName' => 'client_id','AttributeType' => 'S'), - array('AttributeName' => 'subject','AttributeType' => 'S') - ), - 'KeySchema' => array( - array('AttributeName' => 'client_id','KeyType' => 'HASH'), - array('AttributeName' => 'subject','KeyType' => 'RANGE') - ), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_public_keys', - 'AttributeDefinitions' => array( - array('AttributeName' => 'client_id','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'client_id','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_refresh_tokens', - 'AttributeDefinitions' => array( - array('AttributeName' => 'refresh_token','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'refresh_token','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_scopes', - 'AttributeDefinitions' => array( - array('AttributeName' => 'scope','AttributeType' => 'S'), - array('AttributeName' => 'is_default','AttributeType' => 'S') - ), - 'KeySchema' => array(array('AttributeName' => 'scope','KeyType' => 'HASH')), - 'GlobalSecondaryIndexes' => array( - array( - 'IndexName' => 'is_default-index', - 'KeySchema' => array(array('AttributeName' => 'is_default', 'KeyType' => 'HASH')), - 'Projection' => array('ProjectionType' => 'ALL'), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - ), - ), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - $client->createTable(array( - 'TableName' => $prefix.'oauth_users', - 'AttributeDefinitions' => array(array('AttributeName' => 'username','AttributeType' => 'S')), - 'KeySchema' => array(array('AttributeName' => 'username','KeyType' => 'HASH')), - 'ProvisionedThroughput' => array('ReadCapacityUnits' => 1,'WriteCapacityUnits' => 1) - )); - - // Wait for creation - $nbTableCreated = 0; - while ($nbTableCreated != $nbTables) { - $nbTableCreated = 0; - foreach ($tablesList as $key => $table) { - try { - $result = $client->describeTable(array('TableName' => $prefix.$table)); - if ($result['Table']['TableStatus'] == 'ACTIVE') { - $nbTableCreated++; - } - } catch (\Aws\DynamoDb\Exception\DynamoDbException $e) { - // Table does not exist : nothing to do - $nbTableCreated++; - } - } - if ($nbTableCreated != $nbTables) { - sleep(1); - } - } - } - - private function populateDynamoDb($client, $prefix = null) - { - // set up scopes - foreach (explode(' ', 'supportedscope1 supportedscope2 supportedscope3 supportedscope4 clientscope1 clientscope2 clientscope3') as $supportedScope) { - $client->putItem(array( - 'TableName' => $prefix.'oauth_scopes', - 'Item' => array('scope' => array('S' => $supportedScope)) - )); - } - - foreach (array('defaultscope1', 'defaultscope2') as $defaultScope) { - $client->putItem(array( - 'TableName' => $prefix.'oauth_scopes', - 'Item' => array('scope' => array('S' => $defaultScope), 'is_default' => array('S' => "true")) - )); - } - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'Test Client ID'), - 'client_secret' => array('S' => 'TestSecret'), - 'scope' => array('S' => 'clientscope1 clientscope2') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'Test Client ID 2'), - 'client_secret' => array('S' => 'TestSecret'), - 'scope' => array('S' => 'clientscope1 clientscope2 clientscope3') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'Test Default Scope Client ID'), - 'client_secret' => array('S' => 'TestSecret'), - 'scope' => array('S' => 'clientscope1 clientscope2') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_clients', - 'Item' => array( - 'client_id' => array('S' => 'oauth_test_client'), - 'client_secret' => array('S' => 'testpass'), - 'grant_types' => array('S' => 'implicit password') - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_access_tokens', - 'Item' => array( - 'access_token' => array('S' => 'testtoken'), - 'client_id' => array('S' => 'Some Client'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_access_tokens', - 'Item' => array( - 'access_token' => array('S' => 'accesstoken-openid-connect'), - 'client_id' => array('S' => 'Some Client'), - 'user_id' => array('S' => 'testuser'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_authorization_codes', - 'Item' => array( - 'authorization_code' => array('S' => 'testcode'), - 'client_id' => array('S' => 'Some Client'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_users', - 'Item' => array( - 'username' => array('S' => 'testuser'), - 'password' => array('S' => 'password'), - 'email' => array('S' => 'testuser@test.com'), - 'email_verified' => array('S' => 'true'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_public_keys', - 'Item' => array( - 'client_id' => array('S' => 'ClientID_One'), - 'public_key' => array('S' => 'client_1_public'), - 'private_key' => array('S' => 'client_1_private'), - 'encryption_algorithm' => array('S' => 'RS256'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_public_keys', - 'Item' => array( - 'client_id' => array('S' => 'ClientID_Two'), - 'public_key' => array('S' => 'client_2_public'), - 'private_key' => array('S' => 'client_2_private'), - 'encryption_algorithm' => array('S' => 'RS256'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_public_keys', - 'Item' => array( - 'client_id' => array('S' => '0'), - 'public_key' => array('S' => $this->getTestPublicKey()), - 'private_key' => array('S' => $this->getTestPrivateKey()), - 'encryption_algorithm' => array('S' => 'RS256'), - ) - )); - - $client->putItem(array( - 'TableName' => $prefix.'oauth_jwt', - 'Item' => array( - 'client_id' => array('S' => 'oauth_test_client'), - 'subject' => array('S' => 'test_subject'), - 'public_key' => array('S' => $this->getTestPublicKey()), - ) - )); - } - - public function cleanupTravisDynamoDb($prefix = null) - { - if (is_null($prefix)) { - // skip this when not applicable - if (!$this->getEnvVar('TRAVIS') || self::DYNAMODB_PHP_VERSION != $this->getEnvVar('TRAVIS_PHP_VERSION')) { - return; - } - - $prefix = sprintf('build_%s_', $this->getEnvVar('TRAVIS_JOB_NUMBER')); - } - - $client = $this->getDynamoDbClient(); - $this->deleteDynamoDb($client, $prefix); - } - - private function getEnvVar($var, $default = null) - { - return isset($_SERVER[$var]) ? $_SERVER[$var] : (getenv($var) ?: $default); - } -} diff --git a/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Storage/NullStorage.php b/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Storage/NullStorage.php deleted file mode 100644 index 6caa620..0000000 --- a/vendor/bshaffer/oauth2-server-php/test/lib/OAuth2/Storage/NullStorage.php +++ /dev/null @@ -1,32 +0,0 @@ -name = $name; - $this->description = $description; - } - - public function __toString() - { - return $this->name; - } - - public function getMessage() - { - if ($this->description) { - return $this->description; - } - - return $this->name; - } -} diff --git a/vendor/composer/ClassLoader.php b/vendor/composer/ClassLoader.php index ff6ecfb..4626994 100644 --- a/vendor/composer/ClassLoader.php +++ b/vendor/composer/ClassLoader.php @@ -53,8 +53,9 @@ class ClassLoader private $useIncludePath = false; private $classMap = array(); - private $classMapAuthoritative = false; + private $missingClasses = array(); + private $apcuPrefix; public function getPrefixes() { @@ -271,6 +272,26 @@ class ClassLoader return $this->classMapAuthoritative; } + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + /** * Registers this instance as an autoloader. * @@ -313,29 +334,34 @@ class ClassLoader */ public function findFile($class) { - // work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731 - if ('\\' == $class[0]) { - $class = substr($class, 1); - } - // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } - if ($this->classMapAuthoritative) { + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM - if ($file === null && defined('HHVM_VERSION')) { + if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } - if ($file === null) { + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { // Remember that this class does not exist. - return $this->classMap[$class] = false; + $this->missingClasses[$class] = true; } return $file; @@ -399,6 +425,8 @@ class ClassLoader if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } + + return false; } } diff --git a/vendor/composer/autoload_namespaces.php b/vendor/composer/autoload_namespaces.php index 7c2cb36..afe6e66 100644 --- a/vendor/composer/autoload_namespaces.php +++ b/vendor/composer/autoload_namespaces.php @@ -11,5 +11,4 @@ return array( 'Pimple' => array($vendorDir . '/pimple/pimple/src'), 'PicoFeed' => array($vendorDir . '/fguillot/picofeed/lib'), 'Parsedown' => array($vendorDir . '/erusev/parsedown'), - 'OAuth2' => array($vendorDir . '/bshaffer/oauth2-server-php/src'), ); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php index 71d78f8..476de96 100644 --- a/vendor/composer/autoload_real.php +++ b/vendor/composer/autoload_real.php @@ -23,24 +23,35 @@ class ComposerAutoloaderInitd1db2574a85c0ba6f142743249ba228f self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInitd1db2574a85c0ba6f142743249ba228f', 'loadClassLoader')); - $map = require __DIR__ . '/autoload_namespaces.php'; - foreach ($map as $namespace => $path) { - $loader->set($namespace, $path); - } + $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); + if ($useStaticLoader) { + require_once __DIR__ . '/autoload_static.php'; - $map = require __DIR__ . '/autoload_psr4.php'; - foreach ($map as $namespace => $path) { - $loader->setPsr4($namespace, $path); - } + call_user_func(\Composer\Autoload\ComposerStaticInitd1db2574a85c0ba6f142743249ba228f::getInitializer($loader)); + } else { + $map = require __DIR__ . '/autoload_namespaces.php'; + foreach ($map as $namespace => $path) { + $loader->set($namespace, $path); + } - $classMap = require __DIR__ . '/autoload_classmap.php'; - if ($classMap) { - $loader->addClassMap($classMap); + $map = require __DIR__ . '/autoload_psr4.php'; + foreach ($map as $namespace => $path) { + $loader->setPsr4($namespace, $path); + } + + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } } $loader->register(true); - $includeFiles = require __DIR__ . '/autoload_files.php'; + if ($useStaticLoader) { + $includeFiles = Composer\Autoload\ComposerStaticInitd1db2574a85c0ba6f142743249ba228f::$files; + } else { + $includeFiles = require __DIR__ . '/autoload_files.php'; + } foreach ($includeFiles as $fileIdentifier => $file) { composerRequired1db2574a85c0ba6f142743249ba228f($fileIdentifier, $file); } diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php new file mode 100644 index 0000000..e98d270 --- /dev/null +++ b/vendor/composer/autoload_static.php @@ -0,0 +1,97 @@ + __DIR__ . '/..' . '/nikic/fast-route/src/functions.php', + ); + + public static $prefixLengthsPsr4 = array ( + 'S' => + array ( + 'Symfony\\Component\\Yaml\\' => 23, + 'Slim\\' => 5, + ), + 'P' => + array ( + 'Psr\\Http\\Message\\' => 17, + ), + 'I' => + array ( + 'Interop\\Container\\' => 18, + ), + 'F' => + array ( + 'FastRoute\\' => 10, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'Symfony\\Component\\Yaml\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/yaml', + ), + 'Slim\\' => + array ( + 0 => __DIR__ . '/..' . '/slim/slim/Slim', + ), + 'Psr\\Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-message/src', + ), + 'Interop\\Container\\' => + array ( + 0 => __DIR__ . '/..' . '/container-interop/container-interop/src/Interop/Container', + ), + 'FastRoute\\' => + array ( + 0 => __DIR__ . '/..' . '/nikic/fast-route/src', + ), + ); + + public static $prefixesPsr0 = array ( + 'Z' => + array ( + 'ZendXml\\' => + array ( + 0 => __DIR__ . '/..' . '/zendframework/zendxml/library', + ), + ), + 'U' => + array ( + 'Upload' => + array ( + 0 => __DIR__ . '/..' . '/codeguy/upload/src', + ), + ), + 'P' => + array ( + 'Pimple' => + array ( + 0 => __DIR__ . '/..' . '/pimple/pimple/src', + ), + 'PicoFeed' => + array ( + 0 => __DIR__ . '/..' . '/fguillot/picofeed/lib', + ), + 'Parsedown' => + array ( + 0 => __DIR__ . '/..' . '/erusev/parsedown', + ), + ), + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitd1db2574a85c0ba6f142743249ba228f::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitd1db2574a85c0ba6f142743249ba228f::$prefixDirsPsr4; + $loader->prefixesPsr0 = ComposerStaticInitd1db2574a85c0ba6f142743249ba228f::$prefixesPsr0; + + }, null, ClassLoader::class); + } +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json index dac54c6..d120a56 100644 --- a/vendor/composer/installed.json +++ b/vendor/composer/installed.json @@ -1,45 +1,4 @@ [ - { - "name": "erusev/parsedown", - "version": "1.6.0", - "version_normalized": "1.6.0.0", - "source": { - "type": "git", - "url": "https://github.com/erusev/parsedown.git", - "reference": "3ebbd730b5c2cf5ce78bc1bf64071407fc6674b7" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/erusev/parsedown/zipball/3ebbd730b5c2cf5ce78bc1bf64071407fc6674b7", - "reference": "3ebbd730b5c2cf5ce78bc1bf64071407fc6674b7", - "shasum": "" - }, - "time": "2015-10-04 16:44:32", - "type": "library", - "installation-source": "dist", - "autoload": { - "psr-0": { - "Parsedown": "" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Emanuil Rusev", - "email": "hello@erusev.com", - "homepage": "http://erusev.com" - } - ], - "description": "Parser for Markdown.", - "homepage": "http://parsedown.org", - "keywords": [ - "markdown", - "parser" - ] - }, { "name": "zendframework/zendxml", "version": "1.0.2", @@ -62,7 +21,7 @@ "phpunit/phpunit": "^3.7 || ^4.0", "squizlabs/php_codesniffer": "^1.5" }, - "time": "2016-02-04 21:02:08", + "time": "2016-02-04T21:02:08+00:00", "type": "library", "extra": { "branch-alias": { @@ -87,56 +46,6 @@ "zf2" ] }, - { - "name": "fguillot/picofeed", - "version": "v0.1.23", - "version_normalized": "0.1.23.0", - "source": { - "type": "git", - "url": "https://github.com/fguillot/picoFeed.git", - "reference": "a7c3d420c239fe9ffc39b0d06b6e57db39ce3797" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/fguillot/picoFeed/zipball/a7c3d420c239fe9ffc39b0d06b6e57db39ce3797", - "reference": "a7c3d420c239fe9ffc39b0d06b6e57db39ce3797", - "shasum": "" - }, - "require": { - "ext-dom": "*", - "ext-iconv": "*", - "ext-libxml": "*", - "ext-simplexml": "*", - "ext-xml": "*", - "php": ">=5.3.0", - "zendframework/zendxml": "^1.0" - }, - "suggest": { - "ext-curl": "PicoFeed will use cURL if present" - }, - "time": "2016-04-17 22:31:55", - "bin": [ - "picofeed" - ], - "type": "library", - "installation-source": "dist", - "autoload": { - "psr-0": { - "PicoFeed": "lib/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Frédéric Guillot" - } - ], - "description": "Modern library to handle RSS/Atom feeds", - "homepage": "https://github.com/fguillot/picoFeed" - }, { "name": "container-interop/container-interop", "version": "1.1.0", @@ -152,7 +61,7 @@ "reference": "fc08354828f8fd3245f77a66b9e23a6bca48297e", "shasum": "" }, - "time": "2014-12-30 15:22:37", + "time": "2014-12-30T15:22:37+00:00", "type": "library", "installation-source": "dist", "autoload": { @@ -166,102 +75,6 @@ ], "description": "Promoting the interoperability of container objects (DIC, SL, etc.)" }, - { - "name": "nikic/fast-route", - "version": "v0.6.0", - "version_normalized": "0.6.0.0", - "source": { - "type": "git", - "url": "https://github.com/nikic/FastRoute.git", - "reference": "31fa86924556b80735f98b294a7ffdfb26789f22" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/nikic/FastRoute/zipball/31fa86924556b80735f98b294a7ffdfb26789f22", - "reference": "31fa86924556b80735f98b294a7ffdfb26789f22", - "shasum": "" - }, - "require": { - "php": ">=5.4.0" - }, - "time": "2015-06-18 19:15:47", - "type": "library", - "installation-source": "dist", - "autoload": { - "psr-4": { - "FastRoute\\": "src/" - }, - "files": [ - "src/functions.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-3-Clause" - ], - "authors": [ - { - "name": "Nikita Popov", - "email": "nikic@php.net" - } - ], - "description": "Fast request router for PHP", - "keywords": [ - "router", - "routing" - ] - }, - { - "name": "psr/http-message", - "version": "1.0", - "version_normalized": "1.0.0.0", - "source": { - "type": "git", - "url": "https://github.com/php-fig/http-message.git", - "reference": "85d63699f0dbedb190bbd4b0d2b9dc707ea4c298" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/php-fig/http-message/zipball/85d63699f0dbedb190bbd4b0d2b9dc707ea4c298", - "reference": "85d63699f0dbedb190bbd4b0d2b9dc707ea4c298", - "shasum": "" - }, - "require": { - "php": ">=5.3.0" - }, - "time": "2015-05-04 20:22:00", - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - }, - "installation-source": "dist", - "autoload": { - "psr-4": { - "Psr\\Http\\Message\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" - } - ], - "description": "Common interface for HTTP messages", - "keywords": [ - "http", - "http-message", - "psr", - "psr-7", - "request", - "response" - ] - }, { "name": "pimple/pimple", "version": "v3.0.2", @@ -280,7 +93,7 @@ "require": { "php": ">=5.3.0" }, - "time": "2015-09-11 15:10:35", + "time": "2015-09-11T15:10:35+00:00", "type": "library", "extra": { "branch-alias": { @@ -311,32 +124,280 @@ ] }, { - "name": "slim/slim", - "version": "3.3.0", - "version_normalized": "3.3.0.0", + "name": "codeguy/upload", + "version": "1.3.2", + "version_normalized": "1.3.2.0", "source": { "type": "git", - "url": "https://github.com/slimphp/Slim.git", - "reference": "939f2e85d57508de9cff241d10091cd972f221c3" + "url": "https://github.com/codeguy/Upload.git", + "reference": "6a9e5e1fb58d65346d0e557db2d46fb25efd3e37" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/slimphp/Slim/zipball/939f2e85d57508de9cff241d10091cd972f221c3", - "reference": "939f2e85d57508de9cff241d10091cd972f221c3", + "url": "https://api.github.com/repos/codeguy/Upload/zipball/6a9e5e1fb58d65346d0e557db2d46fb25efd3e37", + "reference": "6a9e5e1fb58d65346d0e557db2d46fb25efd3e37", + "shasum": "" + }, + "require": { + "ext-fileinfo": "*", + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "3.7.*" + }, + "time": "2013-07-07T17:01:41+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-0": { + "Upload": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Josh Lockhart", + "email": "info@joshlockhart.com", + "homepage": "http://www.joshlockhart.com/" + } + ], + "description": "Handle file uploads with extensible validation and storage strategies", + "homepage": "http://github.com/codeguy/Upload", + "keywords": [ + "file", + "upload", + "validation" + ] + }, + { + "name": "erusev/parsedown", + "version": "1.6.1", + "version_normalized": "1.6.1.0", + "source": { + "type": "git", + "url": "https://github.com/erusev/parsedown.git", + "reference": "20ff8bbb57205368b4b42d094642a3e52dac85fb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/erusev/parsedown/zipball/20ff8bbb57205368b4b42d094642a3e52dac85fb", + "reference": "20ff8bbb57205368b4b42d094642a3e52dac85fb", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2016-11-02T15:56:58+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-0": { + "Parsedown": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Emanuil Rusev", + "email": "hello@erusev.com", + "homepage": "http://erusev.com" + } + ], + "description": "Parser for Markdown.", + "homepage": "http://parsedown.org", + "keywords": [ + "markdown", + "parser" + ] + }, + { + "name": "fguillot/picofeed", + "version": "v0.1.28", + "version_normalized": "0.1.28.0", + "source": { + "type": "git", + "url": "https://github.com/fguillot/picoFeed.git", + "reference": "9da506c308bcb40b6fc630f9123466028c03170b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fguillot/picoFeed/zipball/9da506c308bcb40b6fc630f9123466028c03170b", + "reference": "9da506c308bcb40b6fc630f9123466028c03170b", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-iconv": "*", + "ext-libxml": "*", + "ext-simplexml": "*", + "ext-xml": "*", + "php": ">=5.3.0", + "zendframework/zendxml": "^1.0" + }, + "require-dev": { + "phpdocumentor/reflection-docblock": "2.0.4", + "phpunit/phpunit": "4.8.26", + "symfony/yaml": "2.8.7" + }, + "suggest": { + "ext-curl": "PicoFeed will use cURL if present" + }, + "time": "2016-12-29T00:06:41+00:00", + "bin": [ + "picofeed" + ], + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-0": { + "PicoFeed": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frédéric Guillot" + } + ], + "description": "Modern library to handle RSS/Atom feeds", + "homepage": "https://github.com/fguillot/picoFeed" + }, + { + "name": "nikic/fast-route", + "version": "v1.1.0", + "version_normalized": "1.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/FastRoute.git", + "reference": "f3dcf5130e634b6123d40727d612ec6aa4f61fb3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/FastRoute/zipball/f3dcf5130e634b6123d40727d612ec6aa4f61fb3", + "reference": "f3dcf5130e634b6123d40727d612ec6aa4f61fb3", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "time": "2016-10-20T17:36:47+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "FastRoute\\": "src/" + }, + "files": [ + "src/functions.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov", + "email": "nikic@php.net" + } + ], + "description": "Fast request router for PHP", + "keywords": [ + "router", + "routing" + ] + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2016-08-06T14:39:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ] + }, + { + "name": "slim/slim", + "version": "3.7.0", + "version_normalized": "3.7.0.0", + "source": { + "type": "git", + "url": "https://github.com/slimphp/Slim.git", + "reference": "4254e40d81559e35cdf856bcbaca5f3af468b7ef" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slimphp/Slim/zipball/4254e40d81559e35cdf856bcbaca5f3af468b7ef", + "reference": "4254e40d81559e35cdf856bcbaca5f3af468b7ef", "shasum": "" }, "require": { "container-interop/container-interop": "^1.1", - "nikic/fast-route": "^0.6", + "nikic/fast-route": "^1.0", "php": ">=5.5.0", "pimple/pimple": "^3.0", "psr/http-message": "^1.0" }, + "provide": { + "psr/http-message-implementation": "1.0" + }, "require-dev": { "phpunit/phpunit": "^4.0", "squizlabs/php_codesniffer": "^2.5" }, - "time": "2016-03-10 21:37:40", + "time": "2016-12-20T20:30:47+00:00", "type": "library", "installation-source": "dist", "autoload": { @@ -371,7 +432,7 @@ } ], "description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs", - "homepage": "http://slimframework.com", + "homepage": "https://slimframework.com", "keywords": [ "api", "framework", @@ -381,27 +442,33 @@ }, { "name": "symfony/yaml", - "version": "v3.0.4", - "version_normalized": "3.0.4.0", + "version": "v3.2.1", + "version_normalized": "3.2.1.0", "source": { "type": "git", "url": "https://github.com/symfony/yaml.git", - "reference": "0047c8366744a16de7516622c5b7355336afae96" + "reference": "a7095af4b97a0955f85c8989106c249fa649011f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/yaml/zipball/0047c8366744a16de7516622c5b7355336afae96", - "reference": "0047c8366744a16de7516622c5b7355336afae96", + "url": "https://api.github.com/repos/symfony/yaml/zipball/a7095af4b97a0955f85c8989106c249fa649011f", + "reference": "a7095af4b97a0955f85c8989106c249fa649011f", "shasum": "" }, "require": { "php": ">=5.5.9" }, - "time": "2016-03-04 07:55:57", + "require-dev": { + "symfony/console": "~2.8|~3.0" + }, + "suggest": { + "symfony/console": "For validating YAML files using the lint command" + }, + "time": "2016-12-10T10:07:06+00:00", "type": "library", "extra": { "branch-alias": { - "dev-master": "3.0-dev" + "dev-master": "3.2-dev" } }, "installation-source": "dist", @@ -429,105 +496,5 @@ ], "description": "Symfony Yaml Component", "homepage": "https://symfony.com" - }, - { - "name": "codeguy/upload", - "version": "1.3.2", - "version_normalized": "1.3.2.0", - "source": { - "type": "git", - "url": "https://github.com/codeguy/Upload.git", - "reference": "6a9e5e1fb58d65346d0e557db2d46fb25efd3e37" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/codeguy/Upload/zipball/6a9e5e1fb58d65346d0e557db2d46fb25efd3e37", - "reference": "6a9e5e1fb58d65346d0e557db2d46fb25efd3e37", - "shasum": "" - }, - "require": { - "ext-fileinfo": "*", - "php": ">=5.3.0" - }, - "require-dev": { - "phpunit/phpunit": "3.7.*" - }, - "time": "2013-07-07 17:01:41", - "type": "library", - "installation-source": "dist", - "autoload": { - "psr-0": { - "Upload": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Josh Lockhart", - "email": "info@joshlockhart.com", - "homepage": "http://www.joshlockhart.com/" - } - ], - "description": "Handle file uploads with extensible validation and storage strategies", - "homepage": "http://github.com/codeguy/Upload", - "keywords": [ - "file", - "upload", - "validation" - ] - }, - { - "name": "bshaffer/oauth2-server-php", - "version": "v1.8.0", - "version_normalized": "1.8.0.0", - "source": { - "type": "git", - "url": "https://github.com/bshaffer/oauth2-server-php.git", - "reference": "058c98f73209f9c49495e1799d32c035196fe8b8" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/bshaffer/oauth2-server-php/zipball/058c98f73209f9c49495e1799d32c035196fe8b8", - "reference": "058c98f73209f9c49495e1799d32c035196fe8b8", - "shasum": "" - }, - "require": { - "php": ">=5.3.9" - }, - "suggest": { - "aws/aws-sdk-php": "~2.8 is required to use the DynamoDB storage engine", - "firebase/php-jwt": "~2.2 is required to use JWT features", - "predis/predis": "Required to use the Redis storage engine", - "thobbs/phpcassa": "Required to use the Cassandra storage engine" - }, - "time": "2015-09-18 18:05:10", - "type": "library", - "installation-source": "dist", - "autoload": { - "psr-0": { - "OAuth2": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Brent Shaffer", - "email": "bshafs@gmail.com", - "homepage": "http://brentertainment.com" - } - ], - "description": "OAuth2 Server for PHP", - "homepage": "http://github.com/bshaffer/oauth2-server-php", - "keywords": [ - "auth", - "oauth", - "oauth2" - ] } ] diff --git a/vendor/erusev/parsedown/.travis.yml b/vendor/erusev/parsedown/.travis.yml index 5df49dc..fa5ca98 100644 --- a/vendor/erusev/parsedown/.travis.yml +++ b/vendor/erusev/parsedown/.travis.yml @@ -1,6 +1,7 @@ language: php php: + - 7.1 - 7.0 - 5.6 - 5.5 @@ -12,5 +13,4 @@ php: matrix: fast_finish: true allow_failures: - - php: 7.0 - php: hhvm-nightly diff --git a/vendor/erusev/parsedown/Parsedown.php b/vendor/erusev/parsedown/Parsedown.php old mode 100755 new mode 100644 index c8c92a3..4737eee --- a/vendor/erusev/parsedown/Parsedown.php +++ b/vendor/erusev/parsedown/Parsedown.php @@ -115,7 +115,7 @@ class Parsedown # Blocks # - private function lines(array $lines) + protected function lines(array $lines) { $CurrentBlock = null; @@ -175,7 +175,7 @@ class Parsedown } else { - if (method_exists($this, 'block'.$CurrentBlock['type'].'Complete')) + if ($this->isBlockCompletable($CurrentBlock['type'])) { $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock); } @@ -216,7 +216,7 @@ class Parsedown $Block['identified'] = true; } - if (method_exists($this, 'block'.$blockType.'Continue')) + if ($this->isBlockContinuable($blockType)) { $Block['continuable'] = true; } @@ -245,7 +245,7 @@ class Parsedown # ~ - if (isset($CurrentBlock['continuable']) and method_exists($this, 'block'.$CurrentBlock['type'].'Complete')) + if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type'])) { $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock); } @@ -278,6 +278,16 @@ class Parsedown return $markup; } + protected function isBlockContinuable($Type) + { + return method_exists($this, 'block'.$Type.'Continue'); + } + + protected function isBlockCompletable($Type) + { + return method_exists($this, 'block'.$Type.'Complete'); + } + # # Code @@ -505,6 +515,16 @@ class Parsedown ), ); + if($name === 'ol') + { + $listStart = stristr($matches[0], '.', true); + + if($listStart !== '1') + { + $Block['element']['attributes'] = array('start' => $listStart); + } + } + $Block['li'] = array( 'name' => 'li', 'handler' => 'li', diff --git a/vendor/erusev/parsedown/README.md b/vendor/erusev/parsedown/README.md index 6f9f649..7907787 100644 --- a/vendor/erusev/parsedown/README.md +++ b/vendor/erusev/parsedown/README.md @@ -1,3 +1,5 @@ +> You might also like [Caret](http://caret.io?ref=parsedown) - our Markdown editor for Mac / Windows / Linux. + ## Parsedown [![Build Status](https://img.shields.io/travis/erusev/parsedown/master.svg?style=flat-square)](https://travis-ci.org/erusev/parsedown) @@ -12,10 +14,11 @@ Better Markdown Parser in PHP ### Features +* One File * Super Fast -* [GitHub flavored](https://help.github.com/articles/github-flavored-markdown) * Extensible -* Tested in 5.3 to 5.6 +* [GitHub flavored](https://help.github.com/articles/github-flavored-markdown) +* Tested in 5.3 to 7.1 and in HHVM * [Markdown Extra extension](https://github.com/erusev/parsedown-extra) ### Installation @@ -36,7 +39,7 @@ More examples in [the wiki](https://github.com/erusev/parsedown/wiki/) and in [t **How does Parsedown work?** -It tries to read Markdown like a human. First, it looks at the lines. It’s interested in how the lines start. This helps it recognise blocks. It knows, for example, that if a line start with a `-` then it perhaps belong to a list. Once it recognises the blocks, it continues to the content. As it reads, it watches out for special characters. This helps it recognise inline elements (or inlines). +It tries to read Markdown like a human. First, it looks at the lines. It’s interested in how the lines start. This helps it recognise blocks. It knows, for example, that if a line starts with a `-` then perhaps it belongs to a list. Once it recognises the blocks, it continues to the content. As it reads, it watches out for special characters. This helps it recognise inline elements (or inlines). We call this approach "line based". We believe that Parsedown is the first Markdown parser to use it. Since the release of Parsedown, other developers have used the same approach to develop other Markdown parsers in PHP and in other languages. @@ -46,12 +49,8 @@ It passes most of the CommonMark tests. Most of the tests that don't pass deal w **Who uses it?** -[phpDocumentor](http://www.phpdoc.org/), [October CMS](http://octobercms.com/), [Bolt CMS](http://bolt.cm/), [Kirby CMS](http://getkirby.com/), [Grav CMS](http://getgrav.org/), [Statamic CMS](http://www.statamic.com/), [RaspberryPi.org](http://www.raspberrypi.org/) and [more](https://www.versioneye.com/php/erusev:parsedown/references). +[phpDocumentor](http://www.phpdoc.org/), [October CMS](http://octobercms.com/), [Bolt CMS](http://bolt.cm/), [Kirby CMS](http://getkirby.com/), [Grav CMS](http://getgrav.org/), [Statamic CMS](http://www.statamic.com/), [Herbie CMS](http://www.getherbie.org/), [RaspberryPi.org](http://www.raspberrypi.org/) and [more](https://packagist.org/packages/erusev/parsedown/dependents). **How can I help?** Use it, star it, share it and if you feel generous, [donate](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=528P3NZQMP8N2). - ---- - -You might also like [Caret](http://caret.io) - our Markdown editor for the desktop. diff --git a/vendor/erusev/parsedown/composer.json b/vendor/erusev/parsedown/composer.json index 1439b82..28145af 100644 --- a/vendor/erusev/parsedown/composer.json +++ b/vendor/erusev/parsedown/composer.json @@ -12,7 +12,10 @@ "homepage": "http://erusev.com" } ], + "require": { + "php": ">=5.3.0" + }, "autoload": { "psr-0": {"Parsedown": ""} } -} \ No newline at end of file +} diff --git a/vendor/erusev/parsedown/test/ParsedownTest.php b/vendor/erusev/parsedown/test/ParsedownTest.php index c922ab1..323dace 100644 --- a/vendor/erusev/parsedown/test/ParsedownTest.php +++ b/vendor/erusev/parsedown/test/ParsedownTest.php @@ -139,7 +139,7 @@ EXPECTED_HTML; public function testLateStaticBinding() { - include 'test/TestParsedown.php'; + include __DIR__ . '/TestParsedown.php'; $parsedown = Parsedown::instance(); $this->assertInstanceOf('Parsedown', $parsedown); diff --git a/vendor/erusev/parsedown/test/data/ordered_list.html b/vendor/erusev/parsedown/test/data/ordered_list.html index b6c5216..c4a69db 100644 --- a/vendor/erusev/parsedown/test/data/ordered_list.html +++ b/vendor/erusev/parsedown/test/data/ordered_list.html @@ -8,6 +8,6 @@
  • two
  • large numbers:

    -
      +
      1. one
      \ No newline at end of file diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Client/Client.php b/vendor/fguillot/picofeed/lib/PicoFeed/Client/Client.php index d7f981b..809a47d 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Client/Client.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Client/Client.php @@ -2,6 +2,7 @@ namespace PicoFeed\Client; +use DateTime; use LogicException; use PicoFeed\Logging\Logger; use PicoFeed\Config\Config; @@ -55,6 +56,13 @@ abstract class Client */ protected $last_modified = ''; + /** + * Expiration DateTime + * + * @var DateTime + */ + protected $expiration = null; + /** * Proxy hostname. * @@ -214,6 +222,9 @@ abstract class Client $this->handleErrorResponse($response); $this->handleNormalResponse($response); + $this->expiration = $this->parseExpiration($response['headers']); + Logger::setMessage(get_called_class().' Expiration: '.$this->expiration->format(DATE_ISO8601)); + return $this; } @@ -241,6 +252,9 @@ abstract class Client * Handle Http Error codes * * @param array $response Client response + * @throws ForbiddenException + * @throws InvalidUrlException + * @throws UnauthorizedException */ protected function handleErrorResponse(array $response) { @@ -402,13 +416,12 @@ abstract class Client /** * Set the url. * + * @param $url * @return string - * @return \PicoFeed\Client\Client */ public function setUrl($url) { $this->url = $url; - return $this; } @@ -670,4 +683,31 @@ abstract class Client { return $code == 301 || $code == 302 || $code == 303 || $code == 307; } + + public function parseExpiration(HttpHeaders $headers) + { + if (isset($headers['Cache-Control'])) { + if (preg_match('/s-maxage=(\d+)/', $headers['Cache-Control'], $matches)) { + return new DateTime('+' . $matches[1] . ' seconds'); + } else if (preg_match('/max-age=(\d+)/', $headers['Cache-Control'], $matches)) { + return new DateTime('+' . $matches[1] . ' seconds'); + } + } + + if (! empty($headers['Expires'])) { + return new DateTime($headers['Expires']); + } + + return new DateTime(); + } + + /** + * Get expiration date time from "Expires" or "Cache-Control" headers + * + * @return DateTime + */ + public function getExpiration() + { + return $this->expiration ?: new DateTime(); + } } diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Client/Curl.php b/vendor/fguillot/picofeed/lib/PicoFeed/Client/Curl.php index dfbb024..09957ff 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Client/Curl.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Client/Curl.php @@ -11,6 +11,8 @@ use PicoFeed\Logging\Logger; */ class Curl extends Client { + protected $nbRedirects = 0; + /** * HTTP response body. * @@ -136,6 +138,7 @@ class Curl extends Client if ($this->etag) { $headers[] = 'If-None-Match: '.$this->etag; + $headers[] = 'A-IM: feed'; } if ($this->last_modified) { @@ -199,6 +202,9 @@ class Curl extends Client */ private function prepareDownloadMode($ch) { + $this->body = ''; + $this->response_headers = array(); + $this->response_headers_count = 0; $write_function = 'readBody'; $header_function = 'readHeaders'; @@ -304,12 +310,11 @@ class Curl extends Client * Handle HTTP redirects * * @param string $location Redirected URL - * * @return array + * @throws MaxRedirectException */ private function handleRedirection($location) { - $nb_redirects = 0; $result = array(); $this->url = Url::resolve($location, $this->url); $this->body = ''; @@ -318,9 +323,9 @@ class Curl extends Client $this->response_headers_count = 0; while (true) { - ++$nb_redirects; + $this->nbRedirects++; - if ($nb_redirects >= $this->max_redirects) { + if ($this->nbRedirects >= $this->max_redirects) { throw new MaxRedirectException('Maximum number of redirections reached'); } diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Client/Stream.php b/vendor/fguillot/picofeed/lib/PicoFeed/Client/Stream.php index 75a0122..2e91d47 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Client/Stream.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Client/Stream.php @@ -31,6 +31,7 @@ class Stream extends Client if ($this->etag) { $headers[] = 'If-None-Match: '.$this->etag; + $headers[] = 'A-IM: feed'; } if ($this->last_modified) { @@ -104,6 +105,9 @@ class Stream extends Client * Do the HTTP request. * * @return array HTTP response ['body' => ..., 'status' => ..., 'headers' => ...] + * @throws InvalidUrlException + * @throws MaxSizeException + * @throws TimeoutException */ public function doRequest() { diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Filter/Attribute.php b/vendor/fguillot/picofeed/lib/PicoFeed/Filter/Attribute.php index eea9574..f002153 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Filter/Attribute.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Filter/Attribute.php @@ -51,6 +51,7 @@ class Attribute 'td' => array(), 'tbody' => array(), 'thead' => array(), + 'h1' => array(), 'h2' => array(), 'h3' => array(), 'h4' => array(), diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Filter/Tag.php b/vendor/fguillot/picofeed/lib/PicoFeed/Filter/Tag.php index 5fd8d6d..84a298a 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Filter/Tag.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Filter/Tag.php @@ -42,6 +42,7 @@ class Tag extends Base 'td', 'tbody', 'thead', + 'h1', 'h2', 'h3', 'h4', @@ -67,6 +68,8 @@ class Tag extends Base 'abbr', 'iframe', 'q', + 'sup', + 'sub', ); /** diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Atom.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Atom.php index 19f841b..8e5c1c2 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Atom.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Atom.php @@ -9,6 +9,7 @@ use PicoFeed\Client\Url; /** * Atom parser. * + * @package PicoFeed\Parser * @author Frederic Guillot */ class Atom extends Parser @@ -154,30 +155,33 @@ class Atom extends Parser } /** - * Find the item date. + * Find the item published date. * * @param SimpleXMLElement $entry Feed item * @param Item $item Item object * @param \PicoFeed\Parser\Feed $feed Feed object */ - public function findItemDate(SimpleXMLElement $entry, Item $item, Feed $feed) + public function findItemPublishedDate(SimpleXMLElement $entry, Item $item, Feed $feed) { - $published = XmlParser::getXPathResult($entry, 'atom:published', $this->namespaces) - ?: XmlParser::getXPathResult($entry, 'published'); + $date = XmlParser::getXPathResult($entry, 'atom:published', $this->namespaces) + ?: XmlParser::getXPathResult($entry, 'published'); - $updated = XmlParser::getXPathResult($entry, 'atom:updated', $this->namespaces) - ?: XmlParser::getXPathResult($entry, 'updated'); + $item->setPublishedDate(!empty($date) ? $this->getDateParser()->getDateTime((string) current($date)) : null); + } - $published = !empty($published) ? $this->getDateParser()->getDateTime((string) current($published)) : null; - $updated = !empty($updated) ? $this->getDateParser()->getDateTime((string) current($updated)) : null; + /** + * Find the item updated date. + * + * @param SimpleXMLElement $entry Feed item + * @param Item $item Item object + * @param \PicoFeed\Parser\Feed $feed Feed object + */ + public function findItemUpdatedDate(SimpleXMLElement $entry, Item $item, Feed $feed) + { + $date = XmlParser::getXPathResult($entry, 'atom:updated', $this->namespaces) + ?: XmlParser::getXPathResult($entry, 'updated'); - if ($published === null && $updated === null) { - $item->setDate($feed->getDate()); // We use the feed date if there is no date for the item - } elseif ($published !== null && $updated !== null) { - $item->setDate(max($published, $updated)); // We use the most recent date between published and updated - } else { - $item->setDate($updated ?: $published); - } + $item->setUpdatedDate(!empty($date) ? $this->getDateParser()->getDateTime((string) current($date)) : null); } /** diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/DateParser.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/DateParser.php index 4ad0078..1a17cd3 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/DateParser.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/DateParser.php @@ -9,6 +9,7 @@ use PicoFeed\Base; /** * Date Parser. * + * @package PicoFeed\Parser * @author Frederic Guillot */ class DateParser extends Base diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Feed.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Feed.php index 7095728..a56e71c 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Feed.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Feed.php @@ -5,6 +5,7 @@ namespace PicoFeed\Parser; /** * Feed. * + * @package PicoFeed\Parser * @author Frederic Guillot */ class Feed @@ -12,7 +13,7 @@ class Feed /** * Feed items. * - * @var array + * @var Item[] */ public $items = array(); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Item.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Item.php index a2a966c..bda046c 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Item.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Item.php @@ -5,6 +5,7 @@ namespace PicoFeed\Parser; /** * Feed Item. * + * @package PicoFeed\Parser * @author Frederic Guillot */ class Item @@ -60,6 +61,20 @@ class Item */ public $date = null; + /** + * Item published date. + * + * @var \DateTime + */ + public $publishedDate = null; + + /** + * Item updated date. + * + * @var \DateTime + */ + public $updatedDate = null; + /** * Item content. * @@ -151,7 +166,12 @@ class Item $output .= 'Item::'.$property.' = '.$this->$property.PHP_EOL; } + $publishedDate = $this->publishedDate != null ? $this->publishedDate->format(DATE_RFC822) : null; + $updatedDate = $this->updatedDate != null ? $this->updatedDate->format(DATE_RFC822) : null; + $output .= 'Item::date = '.$this->date->format(DATE_RFC822).PHP_EOL; + $output .= 'Item::publishedDate = '.$publishedDate.PHP_EOL; + $output .= 'Item::updatedDate = '.$updatedDate.PHP_EOL; $output .= 'Item::isRTL() = '.($this->isRTL() ? 'true' : 'false').PHP_EOL; $output .= 'Item::content = '.strlen($this->content).' bytes'.PHP_EOL; @@ -212,6 +232,26 @@ class Item return $this->date; } + /** + * Get published date. + * + * @return \DateTime + */ + public function getPublishedDate() + { + return $this->publishedDate; + } + + /** + * Get updated date. + * + * @return \DateTime + */ + public function getUpdatedDate() + { + return $this->updatedDate; + } + /** * Get content. * @@ -333,6 +373,30 @@ class Item return $this; } + /** + * Set item published date. + * + * @param \DateTime $publishedDate + * @return Item + */ + public function setPublishedDate($publishedDate) + { + $this->publishedDate = $publishedDate; + return $this; + } + + /** + * Set item updated date. + * + * @param \DateTime $updatedDate + * @return Item + */ + public function setUpdatedDate($updatedDate) + { + $this->updatedDate = $updatedDate; + return $this; + } + /** * Set enclosure url. * diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/MalformedXmlException.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/MalformedXmlException.php index 05b0387..efaf0ff 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/MalformedXmlException.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/MalformedXmlException.php @@ -5,6 +5,7 @@ namespace PicoFeed\Parser; /** * MalformedXmlException Exception. * + * @package PicoFeed\Parser * @author Frederic Guillot */ class MalformedXmlException extends ParserException diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Parser.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Parser.php index 9e09058..588d93f 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Parser.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Parser.php @@ -15,9 +15,10 @@ use PicoFeed\Logging\Logger; /** * Base parser class. * + * @package PicoFeed\Parser * @author Frederic Guillot */ -abstract class Parser +abstract class Parser implements ParserInterface { /** * Config object. @@ -211,6 +212,32 @@ abstract class Parser $item->url = Url::resolve($item->getUrl(), $feed->getSiteUrl()); } + /** + * Find the item date. + * + * @param SimpleXMLElement $entry Feed item + * @param Item $item Item object + * @param \PicoFeed\Parser\Feed $feed Feed object + */ + public function findItemDate(SimpleXMLElement $entry, Item $item, Feed $feed) + { + $this->findItemPublishedDate($entry, $item, $feed); + $this->findItemUpdatedDate($entry, $item, $feed); + + if ($item->getPublishedDate() === null) { + // Use the updated date if available, otherwise use the feed date + $item->setPublishedDate($item->getUpdatedDate() ?: $feed->getDate()); + } + + if ($item->getUpdatedDate() === null) { + // Use the published date as fallback + $item->setUpdatedDate($item->getPublishedDate()); + } + + // Use the most recent of published and updated dates + $item->setDate(max($item->getPublishedDate(), $item->getUpdatedDate())); + } + /** * Get Item Post Processor instance * @@ -371,153 +398,5 @@ abstract class Parser return $xml; } - /** - * Find the feed url. - * - * @param SimpleXMLElement $xml Feed xml - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findFeedUrl(SimpleXMLElement $xml, Feed $feed); - /** - * Find the site url. - * - * @param SimpleXMLElement $xml Feed xml - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findSiteUrl(SimpleXMLElement $xml, Feed $feed); - - /** - * Find the feed title. - * - * @param SimpleXMLElement $xml Feed xml - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findFeedTitle(SimpleXMLElement $xml, Feed $feed); - - /** - * Find the feed description. - * - * @param SimpleXMLElement $xml Feed xml - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findFeedDescription(SimpleXMLElement $xml, Feed $feed); - - /** - * Find the feed language. - * - * @param SimpleXMLElement $xml Feed xml - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findFeedLanguage(SimpleXMLElement $xml, Feed $feed); - - /** - * Find the feed id. - * - * @param SimpleXMLElement $xml Feed xml - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findFeedId(SimpleXMLElement $xml, Feed $feed); - - /** - * Find the feed date. - * - * @param SimpleXMLElement $xml Feed xml - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findFeedDate(SimpleXMLElement $xml, Feed $feed); - - /** - * Find the feed logo url. - * - * @param SimpleXMLElement $xml Feed xml - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findFeedLogo(SimpleXMLElement $xml, Feed $feed); - - /** - * Find the feed icon. - * - * @param SimpleXMLElement $xml Feed xml - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findFeedIcon(SimpleXMLElement $xml, Feed $feed); - - /** - * Get the path to the items XML tree. - * - * @param SimpleXMLElement $xml Feed xml - * - * @return SimpleXMLElement - */ - abstract public function getItemsTree(SimpleXMLElement $xml); - - /** - * Find the item author. - * - * @param SimpleXMLElement $xml Feed - * @param SimpleXMLElement $entry Feed item - * @param \PicoFeed\Parser\Item $item Item object - */ - abstract public function findItemAuthor(SimpleXMLElement $xml, SimpleXMLElement $entry, Item $item); - - /** - * Find the item URL. - * - * @param SimpleXMLElement $entry Feed item - * @param \PicoFeed\Parser\Item $item Item object - */ - abstract public function findItemUrl(SimpleXMLElement $entry, Item $item); - - /** - * Find the item title. - * - * @param SimpleXMLElement $entry Feed item - * @param \PicoFeed\Parser\Item $item Item object - */ - abstract public function findItemTitle(SimpleXMLElement $entry, Item $item); - - /** - * Genereate the item id. - * - * @param SimpleXMLElement $entry Feed item - * @param \PicoFeed\Parser\Item $item Item object - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findItemId(SimpleXMLElement $entry, Item $item, Feed $feed); - - /** - * Find the item date. - * - * @param SimpleXMLElement $entry Feed item - * @param Item $item Item object - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findItemDate(SimpleXMLElement $entry, Item $item, Feed $feed); - - /** - * Find the item content. - * - * @param SimpleXMLElement $entry Feed item - * @param \PicoFeed\Parser\Item $item Item object - */ - abstract public function findItemContent(SimpleXMLElement $entry, Item $item); - - /** - * Find the item enclosure. - * - * @param SimpleXMLElement $entry Feed item - * @param \PicoFeed\Parser\Item $item Item object - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findItemEnclosure(SimpleXMLElement $entry, Item $item, Feed $feed); - - /** - * Find the item language. - * - * @param SimpleXMLElement $entry Feed item - * @param \PicoFeed\Parser\Item $item Item object - * @param \PicoFeed\Parser\Feed $feed Feed object - */ - abstract public function findItemLanguage(SimpleXMLElement $entry, Item $item, Feed $feed); } diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/ParserException.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/ParserException.php index cfd102b..b5fbb69 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/ParserException.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/ParserException.php @@ -7,6 +7,7 @@ use PicoFeed\PicoFeedException; /** * ParserException Exception. * + * @package PicoFeed\Parser * @author Frederic Guillot */ abstract class ParserException extends PicoFeedException diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/ParserInterface.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/ParserInterface.php new file mode 100644 index 0000000..045ebee --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/ParserInterface.php @@ -0,0 +1,173 @@ +namespaces); - $item->setDate(empty($date) ? $feed->getDate() : $this->getDateParser()->getDateTime(XmlParser::getValue($date))); + $item->setPublishedDate(!empty($date) ? $this->getDateParser()->getDateTime(XmlParser::getValue($date)) : null); + } + + /** + * Find the item updated date. + * + * @param SimpleXMLElement $entry Feed item + * @param Item $item Item object + * @param \PicoFeed\Parser\Feed $feed Feed object + */ + public function findItemUpdatedDate(SimpleXMLElement $entry, Item $item, Feed $feed) + { + if ($item->publishedDate === null) { + $this->findItemPublishedDate($entry, $item, $feed); + } + $item->setUpdatedDate($item->getPublishedDate()); // No updated date in RSS 1.0 specifications } /** diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss20.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss20.php index 77f797d..3e35b86 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss20.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss20.php @@ -9,6 +9,7 @@ use PicoFeed\Client\Url; /** * RSS 2.0 Parser. * + * @package PicoFeed\Parser * @author Frederic Guillot */ class Rss20 extends Parser @@ -152,17 +153,32 @@ class Rss20 extends Parser } /** - * Find the item date. + * Find the item published date. * * @param SimpleXMLElement $entry Feed item * @param Item $item Item object * @param \PicoFeed\Parser\Feed $feed Feed object */ - public function findItemDate(SimpleXMLElement $entry, Item $item, Feed $feed) + public function findItemPublishedDate(SimpleXMLElement $entry, Item $item, Feed $feed) { $date = XmlParser::getXPathResult($entry, 'pubDate'); - $item->setDate(empty($date) ? $feed->getDate() : $this->getDateParser()->getDateTime(XmlParser::getValue($date))); + $item->setPublishedDate(!empty($date) ? $this->getDateParser()->getDateTime(XmlParser::getValue($date)) : null); + } + + /** + * Find the item updated date. + * + * @param SimpleXMLElement $entry Feed item + * @param Item $item Item object + * @param \PicoFeed\Parser\Feed $feed Feed object + */ + public function findItemUpdatedDate(SimpleXMLElement $entry, Item $item, Feed $feed) + { + if ($item->publishedDate === null) { + $this->findItemPublishedDate($entry, $item, $feed); + } + $item->setUpdatedDate($item->getPublishedDate()); // No updated date in RSS 2.0 specifications } /** diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss91.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss91.php index fe195e8..058fca1 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss91.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss91.php @@ -5,6 +5,7 @@ namespace PicoFeed\Parser; /** * RSS 0.91 Parser. * + * @package PicoFeed\Parser * @author Frederic Guillot */ class Rss91 extends Rss20 diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss92.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss92.php index 0999bc0..e3df3c8 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss92.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/Rss92.php @@ -5,6 +5,7 @@ namespace PicoFeed\Parser; /** * RSS 0.92 Parser. * + * @package PicoFeed\Parser * @author Frederic Guillot */ class Rss92 extends Rss20 diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/XmlEntityException.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/XmlEntityException.php index f3f914d..1188217 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/XmlEntityException.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/XmlEntityException.php @@ -5,6 +5,7 @@ namespace PicoFeed\Parser; /** * XmlEntityException Exception. * + * @package PicoFeed\Parser * @author Bernhard Posselt */ class XmlEntityException extends MalformedXmlException diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/XmlParser.php b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/XmlParser.php index 8247c99..ea42949 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Parser/XmlParser.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Parser/XmlParser.php @@ -2,9 +2,9 @@ namespace PicoFeed\Parser; -use DomDocument; -use SimpleXmlElement; - +use DOMDocument; +use SimpleXMLElement; +use ZendXml\Exception\RuntimeException; use ZendXml\Security; /** @@ -12,6 +12,7 @@ use ZendXml\Security; * * Checks for XML eXternal Entity (XXE) and XML Entity Expansion (XEE) attacks on XML documents * + * @package PicoFeed\Parser * @author Frederic Guillot */ class XmlParser @@ -33,7 +34,7 @@ class XmlParser * * @static * @param string $input XML content - * @return \DOMDocument + * @return DOMDocument */ public static function getDomDocument($input) { @@ -52,18 +53,20 @@ class XmlParser } /** - * Small wrapper around ZendXml to turn their exceptions into picoFeed - * exceptions + * Small wrapper around ZendXml to turn their exceptions into PicoFeed exceptions * - * @param $input the xml to load - * @param $dom pass in a dom document or use null/omit if simpleXml should - * be used + * @static + * @access private + * @param string $input + * @param DOMDocument $dom + * @throws XmlEntityException + * @return SimpleXMLElement|DomDocument|boolean */ private static function scan($input, $dom = null) { try { return Security::scan($input, $dom); - } catch(\ZendXml\Exception\RuntimeException $e) { + } catch(RuntimeException $e) { throw new XmlEntityException($e->getMessage()); } } @@ -72,8 +75,9 @@ class XmlParser * Load HTML document by using a DomDocument instance or return false on failure. * * @static - * @param string $input XML content - * @return \DOMDocument + * @access public + * @param string $input XML content + * @return DOMDocument */ public static function getHtmlDocument($input) { @@ -98,9 +102,8 @@ class XmlParser * Convert a HTML document to XML. * * @static - * - * @param string $html HTML document - * + * @access public + * @param string $html HTML document * @return string */ public static function htmlToXml($html) @@ -113,6 +116,7 @@ class XmlParser * Get XML parser errors. * * @static + * @access public * @return string */ public static function getErrors() @@ -135,7 +139,8 @@ class XmlParser * Get the encoding from a xml tag. * * @static - * @param string $data Input data + * @access public + * @param string $data Input data * @return string */ public static function getEncodingFromXmlTag($data) @@ -162,7 +167,8 @@ class XmlParser * Get the charset from a meta tag. * * @static - * @param string $data Input data + * @access public + * @param string $data Input data * @return string */ public static function getEncodingFromMetaTag($data) @@ -179,6 +185,8 @@ class XmlParser /** * Rewrite XPath query to use namespace-uri and local-name derived from prefix. * + * @static + * @access public * @param string $query XPath query * @param array $ns Prefix to namespace URI mapping * @return string @@ -199,10 +207,12 @@ class XmlParser /** * Get the result elements of a XPath query. * - * @param \SimpleXMLElement $xml XML element - * @param string $query XPath query - * @param array $ns Prefix to namespace URI mapping - * @return \SimpleXMLElement[] + * @static + * @access public + * @param SimpleXMLElement $xml XML element + * @param string $query XPath query + * @param array $ns Prefix to namespace URI mapping + * @return SimpleXMLElement[] */ public static function getXPathResult(SimpleXMLElement $xml, $query, array $ns = array()) { diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/adventuregamers.com.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/adventuregamers.com.php new file mode 100644 index 0000000..21ff75b --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/adventuregamers.com.php @@ -0,0 +1,24 @@ + array( + '%^/news.*%' => array( + 'test_url' => 'http://www.adventuregamers.com/news/view/31079', + 'body' => array( + '//div[@class="bodytext"]', + ) + ), + '%^/videos.*%' => array( + 'test_url' => 'http://www.adventuregamers.com/videos/view/31056', + 'body' => array( + '//iframe', + ) + ), + '%^/articles.*%' => array( + 'test_url' => 'http://www.adventuregamers.com/articles/view/31049', + 'body' => array( + '//div[@class="cleft"]', + ) + ) + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/bigpicture.ru.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/bigpicture.ru.php new file mode 100755 index 0000000..55c4089 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/bigpicture.ru.php @@ -0,0 +1,31 @@ + array( + '%.*%' => array( + 'test_url' => 'http://bigpicture.ru/?p=556658', + 'body' => array( + '//div[@class="article container"]', + ), + 'strip' => array( + '//script', + '//form', + '//style', + '//h1', + '//*[@class="wp-smiley"]', + '//div[@class="ipmd"]', + '//div[@class="tags"]', + '//div[@class="social-button"]', + '//div[@class="bottom-share"]', + '//div[@class="raccoonbox"]', + '//div[@class="yndadvert"]', + '//div[@class="we-recommend"]', + '//div[@class="relap-bigpicture_ru-wrapper"]', + '//div[@id="mmail"]', + '//div[@id="mobile-ads-cut"]', + '//div[@id="liquidstorm-alt-html"]', + '//div[contains(@class, "post-tags")]', + '//*[contains(text(),"Смотрите также")]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/e-w-e.ru.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/e-w-e.ru.php new file mode 100755 index 0000000..8139cc9 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/e-w-e.ru.php @@ -0,0 +1,22 @@ + array( + '%.*%' => array( + 'test_url' => 'http://e-w-e.ru/16-prekrasnyx-izobretenij-zhenshhin/', + 'body' => array( + '//div[contains(@class, "post_text")]', + ), + 'strip' => array( + '//script', + '//form', + '//style', + '//*[@class="views_post"]', + '//*[@class="adman_mobile"]', + '//*[@class="adman_desctop"]', + '//*[contains(@rel, "nofollow")]', + '//*[contains(@class, "wp-smiley")]', + '//*[contains(text(),"Источник:")]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/factroom.ru.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/factroom.ru.php new file mode 100755 index 0000000..a572061 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/factroom.ru.php @@ -0,0 +1,27 @@ + array( + '%.*%' => array( + 'test_url' => 'http://www.factroom.ru/life/20-facts-about-oil', + 'body' => array( + '//div[@class="post"]', + ), + 'strip' => array( + '//script', + '//form', + '//style', + '//h1', + '//div[@id="yandex_ad2"]', + '//*[@class="jp-relatedposts"]', + '//div[contains(@class, "likely-desktop")]', + '//div[contains(@class, "likely-mobile")]', + '//p[last()]', + '//div[contains(@class, "facebook")]', + '//div[contains(@class, "desktop-underpost-direct")]', + '//div[contains(@class, "source-box")]', + '//div[contains(@class, "under-likely-desktop")]', + '//div[contains(@class, "mobile-down-post")]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/fototelegraf.ru.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/fototelegraf.ru.php new file mode 100755 index 0000000..ca2f85a --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/fototelegraf.ru.php @@ -0,0 +1,19 @@ + array( + '%.*%' => array( + 'test_url' => 'http://fototelegraf.ru/?p=348232', + 'body' => array( + '//div[@class="post-content"]', + ), + 'strip' => array( + '//script', + '//form', + '//style', + '//div[@class="imageButtonsBlock"]', + '//div[@class="adOnPostBtwImg"]', + '//div[contains(@class, "post-tags")]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/golem.de.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/golem.de.php index ea1af87..7386827 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/golem.de.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/golem.de.php @@ -6,7 +6,15 @@ return array( 'test_url' => 'http://www.golem.de/news/breko-telekom-verzoegert-gezielt-den-vectoring-ausbau-1311-102974.html', 'body' => array( '//header[@class="cluster-header"]', + '//header[@class="paged-cluster-header"]', '//div[@class="formatted"]', + ), + 'next_page' => array( + '//a[@id="atoc_next"]' + ), + 'strip' => array( + '//header[@class="cluster-header"]/a', + '//div[@id="iqadtile4"]', ), ), ), diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/gorabbit.ru.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/gorabbit.ru.php new file mode 100755 index 0000000..4e43248 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/gorabbit.ru.php @@ -0,0 +1,19 @@ + array( + '%.*%' => array( + 'test_url' => 'http://gorabbit.ru/article/10-oshchushcheniy-za-rulem-kogda-tolko-poluchil-voditelskie-prava', + 'body' => array( + '//div[@class="detail_text"]', + ), + 'strip' => array( + '//script', + '//form', + '//style', + '//div[@class="socials"]', + '//div[@id="cr_1"]', + '//div[@class="related_items"]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/hardware.fr.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/hardware.fr.php new file mode 100644 index 0000000..fa07427 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/hardware.fr.php @@ -0,0 +1,12 @@ + array( + '%^/news.*%' => array( + 'test_url' => 'http://www.hardware.fr/news/14760/intel-lance-nouveaux-ssd-nand-3d.html', + 'body' => array( + '//div[@class="content_actualite"]/div[@class="md"]', + ) + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/hotshowlife.com.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/hotshowlife.com.php new file mode 100755 index 0000000..faf01f3 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/hotshowlife.com.php @@ -0,0 +1,23 @@ + array( + '%.*%' => array( + 'test_url' => 'https://hotshowlife.com/top-10-chempionov-produktov-po-szhiganiyu-kalorij/', + 'body' => array( + '//div[@class="entry-content"]', + ), + 'strip' => array( + '//script', + '//form', + '//style', + '//div[@class="ads2"]', + '//div[@class="mistape_caption"]', + '//div[contains(@class, "et_social_media_hidden")]', + '//div[contains(@class, "et_social_inline_bottom")]', + '//div[contains(@class, "avatar")]', + '//ul[contains(@class, "entry-tags")]', + '//div[contains(@class, "entry-meta")]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/indiehaven.com.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/indiehaven.com.php new file mode 100644 index 0000000..bed22ea --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/indiehaven.com.php @@ -0,0 +1,12 @@ + array( + '%.*%' => array( + 'test_url' => 'http://indiehaven.com/no-mans-sky-is-a-solo-space-adventure-and-im-ok-with-that/', + 'body' => array( + '//section[contains(@class, "entry-content")]', + ) + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/justcoolidea.ru.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/justcoolidea.ru.php new file mode 100755 index 0000000..089ff29 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/justcoolidea.ru.php @@ -0,0 +1,19 @@ + array( + '%.*%' => array( + 'test_url' => 'http://justcoolidea.ru/idealnyj-sad-samodelnye-proekty-dlya-berezhlivogo-domovladeltsa/', + 'body' => array( + '//section[@class="entry-content"]', + ), + 'strip' => array( + '//script', + '//form', + '//style', + '//*[contains(@class, "essb_links")]', + '//*[contains(@rel, "nofollow")]', + '//*[contains(@class, "ads")]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/legorafi.fr.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/legorafi.fr.php new file mode 100644 index 0000000..715bde6 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/legorafi.fr.php @@ -0,0 +1,23 @@ + array( + '%.*%' => array( + 'test_url' => array( + 'http://www.legorafi.fr/2016/12/16/gorafi-magazine-bravo-vous-avez-bientot-presque-survecu-a-2016/', + 'http://www.legorafi.fr/2016/12/15/manuel-valls-promet-quune-fois-elu-il-debarrassera-la-france-de-manuel-valls/', + ), + 'body' => array( + '//section[@id="banner_magazine"]', + '//figure[@class="main_picture"]', + '//div[@class="content"]', + ), + 'strip' => array( + '//figcaption', + '//div[@class="sharebox"]', + '//div[@class="tags"]', + '//section[@class="taboola_article"]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/lifehacker.ru.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/lifehacker.ru.php new file mode 100755 index 0000000..bc140f6 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/lifehacker.ru.php @@ -0,0 +1,22 @@ + array( + '%.*%' => array( + 'test_url' => 'http://lifehacker.ru/2016/03/03/polymail/', + 'body' => array( + '//div[@class="post-content"]', + ), + 'strip' => array( + '//script', + '//form', + '//style', + '//*[@class="wp-thumbnail-caption"]', + '//*[contains(@class, "social-likes")]', + '//*[@class="jp-relatedposts"]', + '//*[contains(@class, "wpappbox")]', + '//*[contains(@class, "icon__image")]', + '//div[@id="hypercomments_widget"]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/medium.com.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/medium.com.php index 880a42c..64a6b89 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/medium.com.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/medium.com.php @@ -6,6 +6,7 @@ return array( 'test_url' => 'https://medium.com/lessons-learned/917b8b63ae3e', 'body' => array( '//div[contains(@class, "post-field body")]', + '//div[contains(@class, "section-inner layoutSingleColumn")]', ), 'strip' => array( ), diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/monandroid.com.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/monandroid.com.php new file mode 100644 index 0000000..149bf9f --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/monandroid.com.php @@ -0,0 +1,14 @@ + array( + '%.*%' => array( + 'test_url' => 'http://www.monandroid.com/blog/tutoriel-avance-activer-le-stockage-fusionne-sur-android-6-marshamallow-t12.html', + 'body' => array( + '//div[@class="blog-post-body"]', + ), + 'strip' => array( + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/monwindowsphone.com.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/monwindows.com.php similarity index 64% rename from vendor/fguillot/picofeed/lib/PicoFeed/Rules/monwindowsphone.com.php rename to vendor/fguillot/picofeed/lib/PicoFeed/Rules/monwindows.com.php index 47c93d7..060f369 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/monwindowsphone.com.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/monwindows.com.php @@ -3,7 +3,7 @@ return array( 'grabber' => array( '%.*%' => array( - 'test_url' => 'http://www.monwindowsphone.com/tout-savoir-sur-le-centre-d-action-de-windows-phone-8-1-t40574.html', + 'test_url' => 'http://www.monwindows.com/tout-savoir-sur-le-centre-d-action-de-windows-phone-8-1-t40574.html', 'body' => array( '//div[@class="blog-post-body"]', ), diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/moya-planeta.ru.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/moya-planeta.ru.php new file mode 100755 index 0000000..dd84284 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/moya-planeta.ru.php @@ -0,0 +1,21 @@ + array( + '%.*%' => array( + 'test_url' => 'http://www.moya-planeta.ru/travel/view/chto_yaponcu_horosho_russkomu_ne_ponyat_20432/', + 'body' => array( + '//div[@class="full_object"]', + ), + 'strip' => array( + '//div[@class="full_object_panel object_panel"]', + '//div[@class="full_object_panel_geo object_panel"]', + '//div[@class="full_object_title"]', + '//div[@class="full_object_social_likes"]', + '//div[@class="full_object_planeta_likes"]', + '//div[@class="full_object_go2comments"]', + '//div[@id="yandex_ad_R-163191-3"]', + '//div[@class="full_object_shop_article_recommend"]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/nat-geo.ru.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/nat-geo.ru.php new file mode 100755 index 0000000..1a42d99 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/nat-geo.ru.php @@ -0,0 +1,11 @@ + array( + '%.*%' => array( + 'test_url' => 'http://www.nat-geo.ru/fact/868093-knidos-antichnyy-naukograd/', + 'body' => array( + '//div[@class="article-inner-text"]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/nextinpact.com.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/nextinpact.com.php new file mode 100644 index 0000000..64e1272 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/nextinpact.com.php @@ -0,0 +1,19 @@ + array( + '%.*%' => array( + 'test_url' => 'http://www.nextinpact.com/news/101122-3d-nand-intel-lance-six-nouvelles-gammes-ssd-pour-tous-usages.htm', + 'body' => array( + '//div[@class="container_article"]', + ), + 'strip' => array( + '//div[@class="infos_article"]', + '//div[@id="actu_auteur"]', + '//div[@id="soutenir_journaliste"]', + '//section[@id="bandeau_abonnez_vous"]', + '//br' + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/publy.ru.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/publy.ru.php new file mode 100755 index 0000000..bcfeeb9 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/publy.ru.php @@ -0,0 +1,24 @@ + array( + '%.*%' => array( + 'test_url' => 'http://www.publy.ru/post/19988', + 'body' => array( + '//div[@class="singlepost"]', + ), + 'strip' => array( + '//script', + '//form', + '//style', + '//*[@class="featured"]', + '//*[@class="toc_white no_bullets"]', + '//*[@class="toc_title"]', + '//*[@class="pba"]', + '//*[@class="comments"]', + '//*[contains(@class, "g-single")]', + '//*[@class="ts-fab-wrapper"]', + '//*[contains(@class, "wp_rp_wrap")]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/rockpapershotgun.com.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/rockpapershotgun.com.php new file mode 100644 index 0000000..c7c230c --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/rockpapershotgun.com.php @@ -0,0 +1,12 @@ + array( + '%.*%' => array( + 'test_url' => 'https://www.rockpapershotgun.com/2016/08/26/the-divisions-expansions-delayed-to-improve-the-game/', + 'body' => array( + '//div[@class="entry"]', + ) + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/rugbyrama.fr.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/rugbyrama.fr.php index 2280b66..9915c23 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/rugbyrama.fr.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/rugbyrama.fr.php @@ -3,15 +3,15 @@ return array( 'grabber' => array( '%.*%' => array( 'test_url' => 'http://www.rugbyrama.fr/rugby/top-14/2015-2016/top-14-hayman-coupe-du-monde-finale-2012-lutte.-voici-levan-chilachava-toulon_sto5283863/story.shtml', - 'body' => array( - '//div[@class="story-simple-content"]', + 'body' => array( + '//div[@class="storyfull__content"]', ), 'strip' => array( '//script', '//form', '//style', '//*[@class="share-buttons"]', - '//*[@class="show-mobile-block"]', + '//*[@class="ad"]', '//*[@class="hide-desktop"]', '//*[@id="tracking_img"]', ) diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/smbc-comics.com.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/smbc-comics.com.php index cbf6c99..e97493c 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/smbc-comics.com.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/smbc-comics.com.php @@ -1,9 +1,15 @@ array( + 'grabber' => array( '%.*%' => array( - '%()%' => '$1$2$1after$2', + 'test_url' => 'http://www.smbc-comics.com/comic/the-troll-toll', + 'body' => array( + '//div[@id="cc-comicbody"]', + '//div[@id="aftercomic"]', + ), + 'strip' => array( + ), ), ), ); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/takprosto.cc.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/takprosto.cc.php new file mode 100755 index 0000000..624ef90 --- /dev/null +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/takprosto.cc.php @@ -0,0 +1,21 @@ + array( + '%.*%' => array( + 'test_url' => 'http://takprosto.cc/kokteyl-dlya-pohudeniya-v-domashnih-usloviyah/', + 'body' => array( + '//div[contains(@class, "entry-contentt")]', + ), + 'strip' => array( + '//script', + '//form', + '//style', + '//*[@class="views_post"]', + '//*[contains(@class, "mailchimp-box")]', + '//*[contains(@class, "essb_links")]', + '//*[contains(@rel, "nofollow")]', + '//*[contains(@class, "ads")]', + ), + ), + ), +); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/thelocal.se.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/thelocal.se.php index 4e6051e..c3ec250 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/thelocal.se.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/thelocal.se.php @@ -2,20 +2,16 @@ return array( 'grabber' => array( '%.*%' => array( - 'test_url' => 'http://www.thelocal.se/20151018/swedish-moderates-tighten-focus-on-begging-ban', + 'test_url' => 'www.thelocal.se/20161219/this-swede-can-memorize-hundreds-of-numbers-in-only-five-minutes', 'body' => array( - '//article', + '//div[@id="article-photo"]', + '//div[@id="article-description"]', + '//div[@id="article-body"]', ), 'strip' => array( - '//p[@id="mobile-signature"]', - '//article/div[4]', - '//article/ul[1]', - '//div[@class="clr"]', - '//p[@class="small"]', - '//p[@style="font-weight: bold; font-size: 14px;"]', - '//div[@class="author"]', - '//div[@class="ad_container"]', + '//div[@id="article-info-middle"]', ) ) ) ); + diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/www.geekculture.com.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/www.geekculture.com.php index 7f03a1d..3d0b6c7 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/www.geekculture.com.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/www.geekculture.com.php @@ -4,7 +4,7 @@ return array( '%.*%' => array( 'test_url' => 'http://www.geekculture.com/joyoftech/joyarchives/2180.html', 'body' => array( - '//p[contains(@class,"Maintext")][2]/img', + '//p[contains(@class,"Maintext")][2]/a/img[contains(@src,"joyimages")]', ), 'strip' => array(), ), diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/www.pcinpact.com.php b/vendor/fguillot/picofeed/lib/PicoFeed/Rules/www.pcinpact.com.php deleted file mode 100644 index 24e9a2f..0000000 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Rules/www.pcinpact.com.php +++ /dev/null @@ -1,14 +0,0 @@ - array( - '%.*%' => array( - 'test_url' => 'http://www.pcinpact.com/news/85954-air-france-ne-vous-demande-plus-deteindre-vos-appareils-electroniques.htm?utm_source=PCi_RSS_Feed&utm_medium=news&utm_campaign=pcinpact', - 'body' => array( - '//div[contains(@id, "actu_content")]', - ), - 'strip' => array( - ), - ), - ), -); diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/CandidateParser.php b/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/CandidateParser.php index 802b01b..6c53a28 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/CandidateParser.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/CandidateParser.php @@ -243,6 +243,16 @@ class CandidateParser implements ParserInterface } } + /** + * Find link for next page of the article. + * + * @return string + */ + public function findNextLink() + { + return null; + } + /** * Return false if the node should not be removed. * diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/ParserInterface.php b/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/ParserInterface.php index a33fefc..3ded4b1 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/ParserInterface.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/ParserInterface.php @@ -10,4 +10,11 @@ interface ParserInterface * @return string */ public function execute(); + + /** + * Find link for next page of the article. + * + * @return string + */ + public function findNextLink(); } diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/RuleParser.php b/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/RuleParser.php index 95665bf..9beb59c 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/RuleParser.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/RuleParser.php @@ -65,7 +65,6 @@ class RuleParser implements ParserInterface public function findContent() { $content = ''; - if (isset($this->rules['body']) && is_array($this->rules['body'])) { foreach ($this->rules['body'] as $pattern) { $nodes = $this->xpath->query($pattern); @@ -80,4 +79,24 @@ class RuleParser implements ParserInterface return $content; } + + /** + * Fetch next link based on Xpath rules. + * + * @return string + */ + public function findNextLink() + { + if (isset($this->rules['next_page']) && is_array($this->rules['next_page'])) { + foreach ($this->rules['next_page'] as $pattern) { + $nodes = $this->xpath->query($pattern); + if ($nodes !== false && $nodes->length > 0) { + foreach ($nodes as $node) { + return $node->getAttribute('href'); + } + } + } + } + return null; + } } diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/Scraper.php b/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/Scraper.php index 980a88d..e5b9817 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/Scraper.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/Scraper.php @@ -206,19 +206,31 @@ class Scraper extends Base /** * Execute the scraper. */ - public function execute() + public function execute($pageContent = '', $recursionDepth = 0) { - $this->content = ''; $this->html = ''; $this->encoding = ''; - + $this->content = ''; $this->download(); $this->prepareHtml(); $parser = $this->getParser(); if ($parser !== null) { - $this->content = $parser->execute(); + $maxRecursions = $this->config->getMaxRecursions(); + if(!isset($maxRecursions)){ + $maxRecursions = 25; + } + $pageContent .= $parser->execute(); + // check if there is a link to next page and recursively get content (max 25 pages) + if((($nextLink = $parser->findNextLink()) !== null) && $recursionDepth < $maxRecursions){ + $nextLink = Url::resolve($nextLink,$this->url); + $this->setUrl($nextLink); + $this->execute($pageContent,$recursionDepth+1); + } + else{ + $this->content = $pageContent; + } Logger::setMessage(get_called_class().': Content length: '.strlen($this->content).' bytes'); } } diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Syndication/FeedBuilder.php b/vendor/fguillot/picofeed/lib/PicoFeed/Syndication/FeedBuilder.php index e7bdbc7..cf9d024 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Syndication/FeedBuilder.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Syndication/FeedBuilder.php @@ -56,7 +56,7 @@ abstract class FeedBuilder /** * @var ItemBuilder[] */ - protected $items; + protected $items = array(); /** * Constructor diff --git a/vendor/fguillot/picofeed/lib/PicoFeed/Syndication/Rss20Helper.php b/vendor/fguillot/picofeed/lib/PicoFeed/Syndication/Rss20Helper.php index c99688a..72a19e5 100644 --- a/vendor/fguillot/picofeed/lib/PicoFeed/Syndication/Rss20Helper.php +++ b/vendor/fguillot/picofeed/lib/PicoFeed/Syndication/Rss20Helper.php @@ -36,7 +36,7 @@ class Rss20Helper * @param DOMElement $element * @param string $tag * @param string $value - * @return AtomHelper + * @return $this */ public function buildNode(DOMElement $element, $tag, $value) { @@ -52,7 +52,7 @@ class Rss20Helper * @access public * @param DOMElement $element * @param string $title - * @return AtomHelper + * @return $this */ public function buildTitle(DOMElement $element, $title) { @@ -66,7 +66,7 @@ class Rss20Helper * @param DOMElement $element * @param DateTime $date * @param string $type - * @return AtomHelper + * @return $this */ public function buildDate(DOMElement $element, DateTime $date, $type = 'pubDate') { @@ -79,7 +79,7 @@ class Rss20Helper * @access public * @param DOMElement $element * @param string $url - * @return AtomHelper + * @return $this */ public function buildLink(DOMElement $element, $url) { @@ -94,7 +94,7 @@ class Rss20Helper * @param string $tag * @param string $authorName * @param string $authorEmail - * @return AtomHelper + * @return $this */ public function buildAuthor(DOMElement $element, $tag, $authorName, $authorEmail) { diff --git a/vendor/nikic/fast-route/.gitignore b/vendor/nikic/fast-route/.gitignore new file mode 100644 index 0000000..57b06e2 --- /dev/null +++ b/vendor/nikic/fast-route/.gitignore @@ -0,0 +1,4 @@ +/vendor/ + +# ignore lock file since we have no extra dependencies +composer.lock diff --git a/vendor/nikic/fast-route/.hhconfig b/vendor/nikic/fast-route/.hhconfig new file mode 100644 index 0000000..0c2153c --- /dev/null +++ b/vendor/nikic/fast-route/.hhconfig @@ -0,0 +1 @@ +assume_php=false diff --git a/vendor/nikic/fast-route/FastRoute.hhi b/vendor/nikic/fast-route/FastRoute.hhi new file mode 100644 index 0000000..c34bb8e --- /dev/null +++ b/vendor/nikic/fast-route/FastRoute.hhi @@ -0,0 +1,126 @@ +; + } + + class RouteCollector { + public function __construct(RouteParser $routeParser, DataGenerator $dataGenerator); + public function addRoute(mixed $httpMethod, string $route, mixed $handler): void; + public function getData(): array; + } + + class Route { + public function __construct(string $httpMethod, mixed $handler, string $regex, array $variables); + public function matches(string $str): bool; + } + + interface DataGenerator { + public function addRoute(string $httpMethod, array $routeData, mixed $handler); + public function getData(): array; + } + + interface Dispatcher { + const int NOT_FOUND = 0; + const int FOUND = 1; + const int METHOD_NOT_ALLOWED = 2; + public function dispatch(string $httpMethod, string $uri): array; + } + + function simpleDispatcher( + (function(RouteCollector): void) $routeDefinitionCallback, + shape( + 'routeParser' => ?classname, + 'dataGenerator' => ?classname, + 'dispatcher' => ?classname, + 'routeCollector' => ?classname, + ) $options = shape()): Dispatcher; + + function cachedDispatcher( + (function(RouteCollector): void) $routeDefinitionCallback, + shape( + 'routeParser' => ?classname, + 'dataGenerator' => ?classname, + 'dispatcher' => ?classname, + 'routeCollector' => ?classname, + 'cacheDisabled' => ?bool, + 'cacheFile' => ?string, + ) $options = shape()): Dispatcher; +} + +namespace FastRoute\DataGenerator { + abstract class RegexBasedAbstract implements \FastRoute\DataGenerator { + protected abstract function getApproxChunkSize(); + protected abstract function processChunk($regexToRoutesMap); + + public function addRoute(string $httpMethod, array $routeData, mixed $handler): void; + public function getData(): array; + } + + class CharCountBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array $regexToRoutesMap): array; + } + + class GroupCountBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array $regexToRoutesMap): array; + } + + class GroupPosBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array $regexToRoutesMap): array; + } + + class MarkBased extends RegexBasedAbstract { + protected function getApproxChunkSize(): int; + protected function processChunk(array $regexToRoutesMap): array; + } +} + +namespace FastRoute\Dispatcher { + abstract class RegexBasedAbstract implements \FastRoute\Dispatcher { + protected abstract function dispatchVariableRoute(array $routeData, string $uri): array; + + public function dispatch(string $httpMethod, string $uri): array; + } + + class GroupPosBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array $routeData, string $uri): array; + } + + class GroupCountBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array $routeData, string $uri): array; + } + + class CharCountBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array $routeData, string $uri): array; + } + + class MarkBased extends RegexBasedAbstract { + public function __construct(array $data); + protected function dispatchVariableRoute(array $routeData, string $uri): array; + } +} + +namespace FastRoute\RouteParser { + class Std implements \FastRoute\RouteParser { + const string VARIABLE_REGEX = <<<'REGEX' +\{ + \s* ([a-zA-Z][a-zA-Z0-9_]*) \s* + (?: + : \s* ([^{}]*(?:\{(?-1)\}[^{}]*)*) + )? +\} +REGEX; + const string DEFAULT_DISPATCH_REGEX = '[^/]+'; + public function parse(string $route): array; + } +} diff --git a/vendor/nikic/fast-route/README.md b/vendor/nikic/fast-route/README.md index ede20c5..f812a2a 100644 --- a/vendor/nikic/fast-route/README.md +++ b/vendor/nikic/fast-route/README.md @@ -4,6 +4,17 @@ FastRoute - Fast request router for PHP This library provides a fast implementation of a regular expression based router. [Blog post explaining how the implementation works and why it is fast.][blog_post] +Install +------- + +To install with composer: + +```sh +composer require nikic/fast-route +``` + +Requires PHP 5.4 or newer. + Usage ----- @@ -12,15 +23,26 @@ Here's a basic usage example: ```php addRoute('GET', '/user/{id:\d+}', 'handler1'); - $r->addRoute('GET', '/user/{id:\d+}/{name}', 'handler2'); - // Or alternatively - $r->addRoute('GET', '/user/{id:\d+}[/{name}]', 'common_handler'); + $r->addRoute('GET', '/users', 'get_all_users_handler'); + // {id} must be a number (\d+) + $r->addRoute('GET', '/user/{id:\d+}', 'get_user_handler'); + // The /{title} suffix is optional + $r->addRoute('GET', '/articles/{id:\d+}[/{title}]', 'get_article_handler'); }); +// Fetch method and URI from somewhere +$httpMethod = $_SERVER['REQUEST_METHOD']; +$uri = $_SERVER['REQUEST_URI']; + +// Strip query string (?foo=bar) and decode URI +if (false !== $pos = strpos($uri, '?')) { + $uri = substr($uri, 0, $pos); +} +$uri = rawurldecode($uri); + $routeInfo = $dispatcher->dispatch($httpMethod, $uri); switch ($routeInfo[0]) { case FastRoute\Dispatcher::NOT_FOUND: @@ -40,25 +62,67 @@ switch ($routeInfo[0]) { ### Defining routes -The routes are defined by calling the `FastRoute\simpleDispatcher` function, which accepts +The routes are defined by calling the `FastRoute\simpleDispatcher()` function, which accepts a callable taking a `FastRoute\RouteCollector` instance. The routes are added by calling -`addRoute()` on the collector instance. +`addRoute()` on the collector instance: -This method accepts the HTTP method the route must match, the route pattern and an associated -handler. The handler does not necessarily have to be a callback (it could also be a controller -class name or any other kind of data you wish to associate with the route). +```php +$r->addRoute($method, $routePattern, $handler); +``` -By default a route pattern syntax is used where `{foo}` specified a placeholder with name `foo` -and matching the string `[^/]+`. To adjust the pattern the placeholder matches, you can specify -a custom pattern by writing `{bar:[0-9]+}`. +The `$method` is an uppercase HTTP method string for which a certain route should match. It +is possible to specify multiple valid methods using an array: + +```php +// These two calls +$r->addRoute('GET', '/test', 'handler'); +$r->addRoute('POST', '/test', 'handler'); +// Are equivalent to this one call +$r->addRoute(['GET', 'POST'], '/test', 'handler'); +``` + +By default the `$routePattern` uses a syntax where `{foo}` specifies a placeholder with name `foo` +and matching the regex `[^/]+`. To adjust the pattern the placeholder matches, you can specify +a custom pattern by writing `{bar:[0-9]+}`. Some examples: + +```php +// Matches /user/42, but not /user/xyz +$r->addRoute('GET', '/user/{id:\d+}', 'handler'); + +// Matches /user/foobar, but not /user/foo/bar +$r->addRoute('GET', '/user/{name}', 'handler'); + +// Matches /user/foo/bar as well +$r->addRoute('GET', '/user/{name:.+}', 'handler'); +``` + +Custom patterns for route placeholders cannot use capturing groups. For example `{lang:(en|de)}` +is not a valid placeholder, because `()` is a capturing group. Instead you can use either +`{lang:en|de}` or `{lang:(?:en|de)}`. Furthermore parts of the route enclosed in `[...]` are considered optional, so that `/foo[bar]` will match both `/foo` and `/foobar`. Optional parts are only supported in a trailing position, not in the middle of a route. -A custom pattern for a route placeholder must not use capturing groups. For example `{lang:(en|de)}` -is not a valid placeholder, because `()` is a capturing group. Instead you can use either -`{lang:en|de}` or `{lang:(?:en|de)}`. +```php +// This route +$r->addRoute('GET', '/user/{id:\d+}[/{name}]', 'handler'); +// Is equivalent to these two routes +$r->addRoute('GET', '/user/{id:\d+}', 'handler'); +$r->addRoute('GET', '/user/{id:\d+}/{name}', 'handler'); + +// Multiple nested optional parts are possible as well +$r->addRoute('GET', '/user[/{id:\d+}[/{name}]]', 'handler'); + +// This route is NOT valid, because optional parts can only occur at the end +$r->addRoute('GET', '/user[/{id:\d+}]/{name}', 'handler'); +``` + +The `$handler` parameter does not necessarily have to be a callback, it could also be a controller +class name or any other kind of data you wish to associate with the route. FastRoute only tells you +which handler corresponds to your URI, how you interpret it is up to you. + +### Caching The reason `simpleDispatcher` accepts a callback for defining the routes is to allow seamless caching. By using `cachedDispatcher` instead of `simpleDispatcher` you can cache the generated @@ -137,13 +201,13 @@ each route info is again an array of it's parts. The structure is best understoo [ [ '/user/', - ['name', '[^/]+'], + ['id', '\d+'], ], [ '/user/', - ['name', '[^/]+'], + ['id', '\d+'], '/', - ['id', '[0-9]+'], + ['name', '[^/]+'], ], ] @@ -189,7 +253,7 @@ To avoid forcing users to manually register HEAD routes for each resource we fal available GET route for a given resource. The PHP web SAPI transparently removes the entity body from HEAD responses so this behavior has no effect on the vast majority of users. -However, implementors using FastRoute outside the web SAPI environment (e.g. a custom server) MUST +However, implementers using FastRoute outside the web SAPI environment (e.g. a custom server) MUST NOT send entity bodies generated in response to HEAD requests. If you are a non-SAPI user this is *your responsibility*; FastRoute has no purview to prevent you from breaking HTTP in such cases. diff --git a/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php b/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php index 7ba75a6..713d897 100644 --- a/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php +++ b/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php @@ -45,7 +45,7 @@ abstract class RegexBasedAbstract implements DataGenerator { } private function isStaticRoute($routeData) { - return count($routeData) == 1 && is_string($routeData[0]); + return count($routeData) === 1 && is_string($routeData[0]); } private function addStaticRoute($httpMethod, $routeData, $handler) { diff --git a/vendor/nikic/fast-route/src/Dispatcher/RegexBasedAbstract.php b/vendor/nikic/fast-route/src/Dispatcher/RegexBasedAbstract.php index 20b8aae..8823b9b 100644 --- a/vendor/nikic/fast-route/src/Dispatcher/RegexBasedAbstract.php +++ b/vendor/nikic/fast-route/src/Dispatcher/RegexBasedAbstract.php @@ -14,9 +14,6 @@ abstract class RegexBasedAbstract implements Dispatcher { if (isset($this->staticRouteMap[$httpMethod][$uri])) { $handler = $this->staticRouteMap[$httpMethod][$uri]; return [self::FOUND, $handler, []]; - } else if ($httpMethod === 'HEAD' && isset($this->staticRouteMap['GET'][$uri])) { - $handler = $this->staticRouteMap['GET'][$uri]; - return [self::FOUND, $handler, []]; } $varRouteData = $this->variableRouteData; @@ -25,8 +22,29 @@ abstract class RegexBasedAbstract implements Dispatcher { if ($result[0] === self::FOUND) { return $result; } - } else if ($httpMethod === 'HEAD' && isset($varRouteData['GET'])) { - $result = $this->dispatchVariableRoute($varRouteData['GET'], $uri); + } + + // For HEAD requests, attempt fallback to GET + if ($httpMethod === 'HEAD') { + if (isset($this->staticRouteMap['GET'][$uri])) { + $handler = $this->staticRouteMap['GET'][$uri]; + return [self::FOUND, $handler, []]; + } + if (isset($varRouteData['GET'])) { + $result = $this->dispatchVariableRoute($varRouteData['GET'], $uri); + if ($result[0] === self::FOUND) { + return $result; + } + } + } + + // If nothing else matches, try fallback routes + if (isset($this->staticRouteMap['*'][$uri])) { + $handler = $this->staticRouteMap['*'][$uri]; + return [self::FOUND, $handler, []]; + } + if (isset($varRouteData['*'])) { + $result = $this->dispatchVariableRoute($varRouteData['*'], $uri); if ($result[0] === self::FOUND) { return $result; } diff --git a/vendor/nikic/fast-route/src/RouteCollector.php b/vendor/nikic/fast-route/src/RouteCollector.php index 4386bbf..74b1f8c 100644 --- a/vendor/nikic/fast-route/src/RouteCollector.php +++ b/vendor/nikic/fast-route/src/RouteCollector.php @@ -34,6 +34,78 @@ class RouteCollector { } } } + + /** + * Adds a GET route to the collection + * + * This is simply an alias of $this->addRoute('GET', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function get($route, $handler) { + $this->addRoute('GET', $route, $handler); + } + + /** + * Adds a POST route to the collection + * + * This is simply an alias of $this->addRoute('POST', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function post($route, $handler) { + $this->addRoute('POST', $route, $handler); + } + + /** + * Adds a PUT route to the collection + * + * This is simply an alias of $this->addRoute('PUT', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function put($route, $handler) { + $this->addRoute('PUT', $route, $handler); + } + + /** + * Adds a DELETE route to the collection + * + * This is simply an alias of $this->addRoute('DELETE', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function delete($route, $handler) { + $this->addRoute('DELETE', $route, $handler); + } + + /** + * Adds a PATCH route to the collection + * + * This is simply an alias of $this->addRoute('PATCH', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function patch($route, $handler) { + $this->addRoute('PATCH', $route, $handler); + } + + /** + * Adds a HEAD route to the collection + * + * This is simply an alias of $this->addRoute('HEAD', $route, $handler) + * + * @param string $route + * @param mixed $handler + */ + public function head($route, $handler) { + $this->addRoute('HEAD', $route, $handler); + } /** * Returns the collected route data, as provided by the data generator. diff --git a/vendor/nikic/fast-route/src/RouteParser/Std.php b/vendor/nikic/fast-route/src/RouteParser/Std.php index 2370f00..a6c21bd 100644 --- a/vendor/nikic/fast-route/src/RouteParser/Std.php +++ b/vendor/nikic/fast-route/src/RouteParser/Std.php @@ -13,7 +13,7 @@ use FastRoute\RouteParser; class Std implements RouteParser { const VARIABLE_REGEX = <<<'REGEX' \{ - \s* ([a-zA-Z][a-zA-Z0-9_]*) \s* + \s* ([a-zA-Z_][a-zA-Z0-9_-]*) \s* (?: : \s* ([^{}]*(?:\{(?-1)\}[^{}]*)*) )? @@ -28,13 +28,17 @@ REGEX; // Split on [ while skipping placeholders $segments = preg_split('~' . self::VARIABLE_REGEX . '(*SKIP)(*F) | \[~x', $routeWithoutClosingOptionals); if ($numOptionals !== count($segments) - 1) { + // If there are any ] in the middle of the route, throw a more specific error message + if (preg_match('~' . self::VARIABLE_REGEX . '(*SKIP)(*F) | \]~x', $routeWithoutClosingOptionals)) { + throw new BadRouteException("Optional segments can only occur at the end of a route"); + } throw new BadRouteException("Number of opening '[' and closing ']' does not match"); } $currentRoute = ''; $routeDatas = []; - foreach ($segments as $segment) { - if ($segment === '') { + foreach ($segments as $n => $segment) { + if ($segment === '' && $n !== 0) { throw new BadRouteException("Empty optional part"); } diff --git a/vendor/nikic/fast-route/src/functions.php b/vendor/nikic/fast-route/src/functions.php index 3af6779..46bc805 100644 --- a/vendor/nikic/fast-route/src/functions.php +++ b/vendor/nikic/fast-route/src/functions.php @@ -60,10 +60,12 @@ if (!function_exists('FastRoute\simpleDispatcher')) { /** @var RouteCollector $routeCollector */ $dispatchData = $routeCollector->getData(); - file_put_contents( - $options['cacheFile'], - ' 'user']]; + // 16 ---- + + $callback = function(RouteCollector $r) { + $r->addRoute('GET', '', 'handler0'); + }; + + $cases[] = ['GET', '', $callback, 'handler0', []]; + + // 17 ---- + + $callback = function(RouteCollector $r) { + $r->addRoute('HEAD', '/a/{foo}', 'handler0'); + $r->addRoute('GET', '/b/{foo}', 'handler1'); + }; + + $cases[] = ['HEAD', '/b/bar', $callback, 'handler1', ['foo' => 'bar']]; + + // 18 ---- + + $callback = function(RouteCollector $r) { + $r->addRoute('HEAD', '/a', 'handler0'); + $r->addRoute('GET', '/b', 'handler1'); + }; + + $cases[] = ['HEAD', '/b', $callback, 'handler1', []]; + + // 19 ---- + + $callback = function(RouteCollector $r) { + $r->addRoute('GET', '/foo', 'handler0'); + $r->addRoute('HEAD', '/{bar}', 'handler1'); + }; + + $cases[] = ['HEAD', '/foo', $callback, 'handler1', ['bar' => 'foo']]; + + // 20 ---- + + $callback = function(RouteCollector $r) { + $r->addRoute('*', '/user', 'handler0'); + $r->addRoute('*', '/{user}', 'handler1'); + $r->addRoute('GET', '/user', 'handler2'); + }; + + $cases[] = ['GET', '/user', $callback, 'handler2', []]; + + // 21 ---- + + $callback = function(RouteCollector $r) { + $r->addRoute('*', '/user', 'handler0'); + $r->addRoute('GET', '/user', 'handler1'); + }; + + $cases[] = ['POST', '/user', $callback, 'handler0', []]; + + // 22 ---- + + $cases[] = ['HEAD', '/user', $callback, 'handler1', []]; + + // 23 ---- + + $callback = function(RouteCollector $r) { + $r->addRoute('GET', '/{bar}', 'handler0'); + $r->addRoute('*', '/foo', 'handler1'); + }; + + $cases[] = ['GET', '/foo', $callback, 'handler0', ['bar' => 'foo']]; // x --------------------------------------------------------------------------------------> @@ -430,6 +496,7 @@ abstract class DispatcherTest extends \PHPUnit_Framework_TestCase { $r->addRoute('GET', '/resource/123/456', 'handler0'); $r->addRoute('POST', '/resource/123/456', 'handler1'); $r->addRoute('PUT', '/resource/123/456', 'handler2'); + $r->addRoute('*', '/', 'handler3'); }; $method = 'DELETE'; diff --git a/vendor/nikic/fast-route/test/HackTypechecker/HackTypecheckerTest.php b/vendor/nikic/fast-route/test/HackTypechecker/HackTypecheckerTest.php new file mode 100644 index 0000000..7bc6ebb --- /dev/null +++ b/vendor/nikic/fast-route/test/HackTypechecker/HackTypecheckerTest.php @@ -0,0 +1,39 @@ +markTestSkipped("HHVM only"); + } + if (!version_compare(HHVM_VERSION, '3.9.0', '>=')) { + $this->markTestSkipped('classname requires HHVM 3.9+'); + } + + // The typechecker recurses the whole tree, so it makes sure + // that everything in fixtures/ is valid when this runs. + + $output = array(); + $exit_code = null; + exec( + 'hh_server --check '.escapeshellarg(__DIR__.'/../../').' 2>&1', + $output, + $exit_code + ); + if ($exit_code === self::SERVER_ALREADY_RUNNING_CODE) { + $this->assertTrue( + $recurse, + "Typechecker still running after running hh_client stop" + ); + // Server already running - 3.10 => 3.11 regression: + // https://github.com/facebook/hhvm/issues/6646 + exec('hh_client stop 2>/dev/null'); + $this->testTypechecks(/* recurse = */ false); + return; + + } + $this->assertSame(0, $exit_code, implode("\n", $output)); + } +} diff --git a/vendor/nikic/fast-route/test/HackTypechecker/fixtures/all_options.php b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/all_options.php new file mode 100644 index 0000000..05a9af2 --- /dev/null +++ b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/all_options.php @@ -0,0 +1,29 @@ + {}, + shape( + 'routeParser' => \FastRoute\RouteParser\Std::class, + 'dataGenerator' => \FastRoute\DataGenerator\GroupCountBased::class, + 'dispatcher' => \FastRoute\Dispatcher\GroupCountBased::class, + 'routeCollector' => \FastRoute\RouteCollector::class, + ), + ); +} + +function all_options_cached(): \FastRoute\Dispatcher { + return \FastRoute\cachedDispatcher( + $collector ==> {}, + shape( + 'routeParser' => \FastRoute\RouteParser\Std::class, + 'dataGenerator' => \FastRoute\DataGenerator\GroupCountBased::class, + 'dispatcher' => \FastRoute\Dispatcher\GroupCountBased::class, + 'routeCollector' => \FastRoute\RouteCollector::class, + 'cacheFile' => '/dev/null', + 'cacheDisabled' => false, + ), + ); +} diff --git a/vendor/nikic/fast-route/test/HackTypechecker/fixtures/empty_options.php b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/empty_options.php new file mode 100644 index 0000000..61eb541 --- /dev/null +++ b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/empty_options.php @@ -0,0 +1,11 @@ + {}, shape()); +} + +function empty_options_cached(): \FastRoute\Dispatcher { + return \FastRoute\cachedDispatcher($collector ==> {}, shape()); +} diff --git a/vendor/nikic/fast-route/test/HackTypechecker/fixtures/no_options.php b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/no_options.php new file mode 100644 index 0000000..44b5422 --- /dev/null +++ b/vendor/nikic/fast-route/test/HackTypechecker/fixtures/no_options.php @@ -0,0 +1,11 @@ + {}); +} + +function no_options_cached(): \FastRoute\Dispatcher { + return \FastRoute\cachedDispatcher($collector ==> {}); +} diff --git a/vendor/nikic/fast-route/test/RouteCollectorTest.php b/vendor/nikic/fast-route/test/RouteCollectorTest.php new file mode 100644 index 0000000..53fd1b6 --- /dev/null +++ b/vendor/nikic/fast-route/test/RouteCollectorTest.php @@ -0,0 +1,35 @@ +delete('/delete', 'delete'); + $r->get('/get', 'get'); + $r->head('/head', 'head'); + $r->patch('/patch', 'patch'); + $r->post('/post', 'post'); + $r->put('/put', 'put'); + + $expected = [ + ['DELETE', '/delete', 'delete'], + ['GET', '/get', 'get'], + ['HEAD', '/head', 'head'], + ['PATCH', '/patch', 'patch'], + ['POST', '/post', 'post'], + ['PUT', '/put', 'put'], + ]; + + $this->assertSame($expected, $r->routes); + } +} + +class DummyRouteCollector extends RouteCollector { + public $routes = []; + public function __construct() {} + public function addRoute($method, $route, $handler) { + $this->routes[] = [$method, $route, $handler]; + } +} \ No newline at end of file diff --git a/vendor/nikic/fast-route/test/RouteParser/StdTest.php b/vendor/nikic/fast-route/test/RouteParser/StdTest.php index 9a25e1f..41f194b 100644 --- a/vendor/nikic/fast-route/test/RouteParser/StdTest.php +++ b/vendor/nikic/fast-route/test/RouteParser/StdTest.php @@ -84,6 +84,31 @@ class StdTest extends \PhpUnit_Framework_TestCase { ['/test/', ['name', '[^/]+'], '/', ['id', '[0-9]+']], ] ], + [ + '', + [ + [''], + ] + ], + [ + '[test]', + [ + [''], + ['test'], + ] + ], + [ + '/{foo-bar}', + [ + ['/', ['foo-bar', '[^/]+']] + ] + ], + [ + '/{_foo:.*}', + [ + ['/', ['_foo', '.*']] + ] + ], ]; } @@ -109,6 +134,14 @@ class StdTest extends \PhpUnit_Framework_TestCase { '/test[[opt]]', "Empty optional part" ], + [ + '[[test]]', + "Empty optional part" + ], + [ + '/test[/opt]/required', + "Optional segments can only occur at the end of a route" + ], ]; } } diff --git a/vendor/psr/http-message/CHANGELOG.md b/vendor/psr/http-message/CHANGELOG.md new file mode 100644 index 0000000..74b1ef9 --- /dev/null +++ b/vendor/psr/http-message/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.0.1 - 2016-08-06 + +### Added + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Updated all `@return self` annotation references in interfaces to use + `@return static`, which more closelly follows the semantics of the + specification. +- Updated the `MessageInterface::getHeaders()` return annotation to use the + value `string[][]`, indicating the format is a nested array of strings. +- Updated the `@link` annotation for `RequestInterface::withRequestTarget()` + to point to the correct section of RFC 7230. +- Updated the `ServerRequestInterface::withUploadedFiles()` parameter annotation + to add the parameter name (`$uploadedFiles`). +- Updated a `@throws` annotation for the `UploadedFileInterface::moveTo()` + method to correctly reference the method parameter (it was referencing an + incorrect parameter name previously). + +## 1.0.0 - 2016-05-18 + +Initial stable release; reflects accepted PSR-7 specification. diff --git a/vendor/psr/http-message/composer.json b/vendor/psr/http-message/composer.json index 4774b61..b0d2937 100644 --- a/vendor/psr/http-message/composer.json +++ b/vendor/psr/http-message/composer.json @@ -2,6 +2,7 @@ "name": "psr/http-message", "description": "Common interface for HTTP messages", "keywords": ["psr", "psr-7", "http", "http-message", "request", "response"], + "homepage": "https://github.com/php-fig/http-message", "license": "MIT", "authors": [ { diff --git a/vendor/psr/http-message/src/MessageInterface.php b/vendor/psr/http-message/src/MessageInterface.php index 8f67a05..dd46e5e 100644 --- a/vendor/psr/http-message/src/MessageInterface.php +++ b/vendor/psr/http-message/src/MessageInterface.php @@ -36,7 +36,7 @@ interface MessageInterface * new protocol version. * * @param string $version HTTP protocol version - * @return self + * @return static */ public function withProtocolVersion($version); @@ -61,7 +61,7 @@ interface MessageInterface * While header names are not case-sensitive, getHeaders() will preserve the * exact case in which headers were originally specified. * - * @return array Returns an associative array of the message's headers. Each + * @return string[][] Returns an associative array of the message's headers. Each * key MUST be a header name, and each value MUST be an array of strings * for that header. */ @@ -126,7 +126,7 @@ interface MessageInterface * * @param string $name Case-insensitive header field name. * @param string|string[] $value Header value(s). - * @return self + * @return static * @throws \InvalidArgumentException for invalid header names or values. */ public function withHeader($name, $value); @@ -144,7 +144,7 @@ interface MessageInterface * * @param string $name Case-insensitive header field name to add. * @param string|string[] $value Header value(s). - * @return self + * @return static * @throws \InvalidArgumentException for invalid header names or values. */ public function withAddedHeader($name, $value); @@ -159,7 +159,7 @@ interface MessageInterface * the named header. * * @param string $name Case-insensitive header field name to remove. - * @return self + * @return static */ public function withoutHeader($name); @@ -180,7 +180,7 @@ interface MessageInterface * new body stream. * * @param StreamInterface $body Body. - * @return self + * @return static * @throws \InvalidArgumentException When the body is not valid. */ public function withBody(StreamInterface $body); diff --git a/vendor/psr/http-message/src/RequestInterface.php b/vendor/psr/http-message/src/RequestInterface.php index 75c802e..a96d4fd 100644 --- a/vendor/psr/http-message/src/RequestInterface.php +++ b/vendor/psr/http-message/src/RequestInterface.php @@ -53,10 +53,10 @@ interface RequestInterface extends MessageInterface * immutability of the message, and MUST return an instance that has the * changed request target. * - * @link http://tools.ietf.org/html/rfc7230#section-2.7 (for the various + * @link http://tools.ietf.org/html/rfc7230#section-5.3 (for the various * request-target forms allowed in request messages) * @param mixed $requestTarget - * @return self + * @return static */ public function withRequestTarget($requestTarget); @@ -79,7 +79,7 @@ interface RequestInterface extends MessageInterface * changed request method. * * @param string $method Case-sensitive method. - * @return self + * @return static * @throws \InvalidArgumentException for invalid HTTP methods. */ public function withMethod($method); @@ -107,7 +107,7 @@ interface RequestInterface extends MessageInterface * setting `$preserveHost` to `true`. When `$preserveHost` is set to * `true`, this method interacts with the Host header in the following ways: * - * - If the the Host header is missing or empty, and the new URI contains + * - If the Host header is missing or empty, and the new URI contains * a host component, this method MUST update the Host header in the returned * request. * - If the Host header is missing or empty, and the new URI does not contain a @@ -123,7 +123,7 @@ interface RequestInterface extends MessageInterface * @link http://tools.ietf.org/html/rfc3986#section-4.3 * @param UriInterface $uri New request URI to use. * @param bool $preserveHost Preserve the original state of the Host header. - * @return self + * @return static */ public function withUri(UriInterface $uri, $preserveHost = false); } diff --git a/vendor/psr/http-message/src/ResponseInterface.php b/vendor/psr/http-message/src/ResponseInterface.php index 6724809..c306514 100644 --- a/vendor/psr/http-message/src/ResponseInterface.php +++ b/vendor/psr/http-message/src/ResponseInterface.php @@ -46,7 +46,7 @@ interface ResponseInterface extends MessageInterface * @param string $reasonPhrase The reason phrase to use with the * provided status code; if none is provided, implementations MAY * use the defaults as suggested in the HTTP specification. - * @return self + * @return static * @throws \InvalidArgumentException For invalid status code arguments. */ public function withStatus($code, $reasonPhrase = ''); diff --git a/vendor/psr/http-message/src/ServerRequestInterface.php b/vendor/psr/http-message/src/ServerRequestInterface.php index 916e065..0251234 100644 --- a/vendor/psr/http-message/src/ServerRequestInterface.php +++ b/vendor/psr/http-message/src/ServerRequestInterface.php @@ -80,7 +80,7 @@ interface ServerRequestInterface extends RequestInterface * updated cookie values. * * @param array $cookies Array of key/value pairs representing cookies. - * @return self + * @return static */ public function withCookieParams(array $cookies); @@ -118,7 +118,7 @@ interface ServerRequestInterface extends RequestInterface * * @param array $query Array of query string arguments, typically from * $_GET. - * @return self + * @return static */ public function withQueryParams(array $query); @@ -143,8 +143,8 @@ interface ServerRequestInterface extends RequestInterface * immutability of the message, and MUST return an instance that has the * updated body parameters. * - * @param array An array tree of UploadedFileInterface instances. - * @return self + * @param array $uploadedFiles An array tree of UploadedFileInterface instances. + * @return static * @throws \InvalidArgumentException if an invalid structure is provided. */ public function withUploadedFiles(array $uploadedFiles); @@ -190,7 +190,7 @@ interface ServerRequestInterface extends RequestInterface * * @param null|array|object $data The deserialized body data. This will * typically be in an array or object. - * @return self + * @return static * @throws \InvalidArgumentException if an unsupported argument type is * provided. */ @@ -239,7 +239,7 @@ interface ServerRequestInterface extends RequestInterface * @see getAttributes() * @param string $name The attribute name. * @param mixed $value The value of the attribute. - * @return self + * @return static */ public function withAttribute($name, $value); @@ -255,7 +255,7 @@ interface ServerRequestInterface extends RequestInterface * * @see getAttributes() * @param string $name The attribute name. - * @return self + * @return static */ public function withoutAttribute($name); } diff --git a/vendor/psr/http-message/src/UploadedFileInterface.php b/vendor/psr/http-message/src/UploadedFileInterface.php index 5ad288d..f8a6901 100644 --- a/vendor/psr/http-message/src/UploadedFileInterface.php +++ b/vendor/psr/http-message/src/UploadedFileInterface.php @@ -58,7 +58,7 @@ interface UploadedFileInterface * @see http://php.net/is_uploaded_file * @see http://php.net/move_uploaded_file * @param string $targetPath Path to which to move the uploaded file. - * @throws \InvalidArgumentException if the $path specified is invalid. + * @throws \InvalidArgumentException if the $targetPath specified is invalid. * @throws \RuntimeException on any error during the move operation, or on * the second or subsequent call to the method. */ diff --git a/vendor/psr/http-message/src/UriInterface.php b/vendor/psr/http-message/src/UriInterface.php index 1ff5bf0..9d7ab9e 100644 --- a/vendor/psr/http-message/src/UriInterface.php +++ b/vendor/psr/http-message/src/UriInterface.php @@ -185,7 +185,7 @@ interface UriInterface * An empty scheme is equivalent to removing the scheme. * * @param string $scheme The scheme to use with the new instance. - * @return self A new instance with the specified scheme. + * @return static A new instance with the specified scheme. * @throws \InvalidArgumentException for invalid or unsupported schemes. */ public function withScheme($scheme); @@ -202,7 +202,7 @@ interface UriInterface * * @param string $user The user name to use for authority. * @param null|string $password The password associated with $user. - * @return self A new instance with the specified user information. + * @return static A new instance with the specified user information. */ public function withUserInfo($user, $password = null); @@ -215,7 +215,7 @@ interface UriInterface * An empty host value is equivalent to removing the host. * * @param string $host The hostname to use with the new instance. - * @return self A new instance with the specified host. + * @return static A new instance with the specified host. * @throws \InvalidArgumentException for invalid hostnames. */ public function withHost($host); @@ -234,7 +234,7 @@ interface UriInterface * * @param null|int $port The port to use with the new instance; a null value * removes the port information. - * @return self A new instance with the specified port. + * @return static A new instance with the specified port. * @throws \InvalidArgumentException for invalid ports. */ public function withPort($port); @@ -258,7 +258,7 @@ interface UriInterface * Implementations ensure the correct encoding as outlined in getPath(). * * @param string $path The path to use with the new instance. - * @return self A new instance with the specified path. + * @return static A new instance with the specified path. * @throws \InvalidArgumentException for invalid paths. */ public function withPath($path); @@ -275,7 +275,7 @@ interface UriInterface * An empty query string value is equivalent to removing the query string. * * @param string $query The query string to use with the new instance. - * @return self A new instance with the specified query string. + * @return static A new instance with the specified query string. * @throws \InvalidArgumentException for invalid query strings. */ public function withQuery($query); @@ -292,7 +292,7 @@ interface UriInterface * An empty fragment value is equivalent to removing the fragment. * * @param string $fragment The fragment to use with the new instance. - * @return self A new instance with the specified fragment. + * @return static A new instance with the specified fragment. */ public function withFragment($fragment); diff --git a/vendor/slim/slim/CONTRIBUTING.md b/vendor/slim/slim/CONTRIBUTING.md deleted file mode 100644 index 9bbb6b1..0000000 --- a/vendor/slim/slim/CONTRIBUTING.md +++ /dev/null @@ -1,20 +0,0 @@ -# How to Contribute - -## Pull Requests - -1. Fork the Slim Framework repository -2. Create a new branch for each feature or improvement -3. Send a pull request from each feature branch to the **develop** branch - -It is very important to separate new features or improvements into separate feature branches, and to send a -pull request for each branch. This allows me to review and pull in new features or improvements individually. - -## Style Guide - -All pull requests must adhere to the [PSR-2 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md). - -## Unit Testing - -All pull requests must be accompanied by passing unit tests and complete code coverage. The Slim Framework uses phpunit for testing. - -[Learn about PHPUnit](https://github.com/sebastianbergmann/phpunit/) diff --git a/vendor/slim/slim/README.md b/vendor/slim/slim/README.md deleted file mode 100644 index 2333614..0000000 --- a/vendor/slim/slim/README.md +++ /dev/null @@ -1,84 +0,0 @@ -# Slim Framework - -[![Build Status](https://travis-ci.org/slimphp/Slim.svg?branch=develop)](https://travis-ci.org/slimphp/Slim) -[![Coverage Status](https://coveralls.io/repos/slimphp/Slim/badge.svg?branch=develop)](https://coveralls.io/r/slimphp/Slim?branch=develop) -[![Total Downloads](https://poser.pugx.org/slim/slim/downloads)](https://packagist.org/packages/slim/slim) -[![License](https://poser.pugx.org/slim/slim/license)](https://packagist.org/packages/slim/slim) - -Slim is a PHP micro-framework that helps you quickly write simple yet powerful web applications and APIs. - -## Installation - -It's recommended that you use [Composer](https://getcomposer.org/) to install Slim. - -```bash -$ composer require slim/slim "^3.0" -``` - -This will install Slim and all required dependencies. Slim requires PHP 5.5.0 or newer. - -## Usage - -Create an index.php file with the following contents: - -```php -get('/hello/{name}', function ($request, $response, $args) { - $response->write("Hello, " . $args['name']); - return $response; -}); - -$app->run(); -``` - -You may quickly test this using the built-in PHP server: -```bash -$ php -S localhost:8000 -``` - -Going to http://localhost:8000/hello/world will now display "Hello, world". - -For more information on how to configure your web server, see the [Documentation](http://www.slimframework.com/docs/start/web-servers.html). - -## Tests - -To execute the test suite, you'll need phpunit. - -```bash -$ phpunit -``` - -## Contributing - -Please see [CONTRIBUTING](CONTRIBUTING.md) for details. - -## Learn More - -Learn more at these links: - -- [Website](http://www.slimframework.com) -- [Documentation](http://www.slimframework.com/docs/start/installation.html) -- [Support Forum](http://help.slimframework.com) -- [Twitter](https://twitter.com/slimphp) -- [Resources](https://github.com/xssc/awesome-slim) - -## Security - -If you discover security related issues, please email security@slimframework.com instead of using the issue tracker. - -## Credits - -- [Josh Lockhart](https://github.com/codeguy) -- [Andrew Smith](https://github.com/silentworks) -- [Rob Allen](https://github.com/akrabat) -- [Gabriel Manricks](https://github.com/gmanricks) -- [All Contributors](../../contributors) - -## License - -The Slim Framework is licensed under the MIT license. See [License File](LICENSE.md) for more information. diff --git a/vendor/slim/slim/Slim/App.php b/vendor/slim/slim/Slim/App.php index 0bfac94..7bf900d 100644 --- a/vendor/slim/slim/Slim/App.php +++ b/vendor/slim/slim/Slim/App.php @@ -1,6 +1,6 @@ container->get('settings'); $chunkSize = $settings['responseChunkSize']; + $contentLength = $response->getHeaderLine('Content-Length'); if (!$contentLength) { $contentLength = $body->getSize(); } + + if (isset($contentLength)) { - $totalChunks = ceil($contentLength / $chunkSize); - $lastChunkSize = $contentLength % $chunkSize; - $currentChunk = 0; - while (!$body->eof() && $currentChunk < $totalChunks) { - if (++$currentChunk == $totalChunks && $lastChunkSize > 0) { - $chunkSize = $lastChunkSize; - } - echo $body->read($chunkSize); + $amountToRead = $contentLength; + while ($amountToRead > 0 && !$body->eof()) { + $data = $body->read(min($chunkSize, $amountToRead)); + echo $data; + + $amountToRead -= strlen($data); + if (connection_status() != CONNECTION_NORMAL) { break; } @@ -543,9 +540,17 @@ class App return $response->withoutHeader('Content-Type')->withoutHeader('Content-Length'); } - $size = $response->getBody()->getSize(); - if ($size !== null && !$response->hasHeader('Content-Length')) { - $response = $response->withHeader('Content-Length', (string) $size); + // Add Content-Length header if `addContentLengthHeader` setting is set + if (isset($this->container->get('settings')['addContentLengthHeader']) && + $this->container->get('settings')['addContentLengthHeader'] == true) { + if (ob_get_length() > 0) { + throw new \RuntimeException("Unexpected data in output buffer. " . + "Maybe you have characters before an opening getBody()->getSize(); + if ($size !== null && !$response->hasHeader('Content-Length')) { + $response = $response->withHeader('Content-Length', (string) $size); + } } return $response; @@ -587,7 +592,7 @@ class App $params = [$e->getRequest(), $e->getResponse(), $e->getAllowedMethods()]; } elseif ($e instanceof NotFoundException) { $handler = 'notFoundHandler'; - $params = [$e->getRequest(), $e->getResponse()]; + $params = [$e->getRequest(), $e->getResponse(), $e]; } elseif ($e instanceof SlimException) { // This is a Stop exception and contains the response return $e->getResponse(); @@ -614,9 +619,8 @@ class App * @param Throwable $e * @param ServerRequestInterface $request * @param ResponseInterface $response - * * @return ResponseInterface - * @throws Exception if a handler is needed and not found + * @throws Throwable */ protected function handlePhpError(Throwable $e, ServerRequestInterface $request, ResponseInterface $response) { diff --git a/vendor/slim/slim/Slim/CallableResolver.php b/vendor/slim/slim/Slim/CallableResolver.php index 705a9f2..8c8eb64 100644 --- a/vendor/slim/slim/Slim/CallableResolver.php +++ b/vendor/slim/slim/Slim/CallableResolver.php @@ -1,6 +1,6 @@ $value) { - $this->set($key, $value); - } + $this->replace($items); } /******************************************************************************** @@ -68,7 +66,7 @@ class Collection implements CollectionInterface } /** - * Add item to collection + * Add item to collection, replacing existing items with the same data key * * @param array $items Key-value array of data to append to this collection */ diff --git a/vendor/slim/slim/Slim/Container.php b/vendor/slim/slim/Slim/Container.php index ff95b28..41ef31c 100644 --- a/vendor/slim/slim/Slim/Container.php +++ b/vendor/slim/slim/Slim/Container.php @@ -1,6 +1,6 @@ 'append', 'determineRouteBeforeAppMiddleware' => false, 'displayErrorDetails' => false, + 'addContentLengthHeader' => true, + 'routerCacheFile' => false, ]; /** @@ -94,7 +95,7 @@ class Container extends PimpleContainer implements ContainerInterface $this['settings'] = function () use ($userSettings, $defaultSettings) { return new Collection(array_merge($defaultSettings, $userSettings)); }; - + $defaultProvider = new DefaultServicesProvider(); $defaultProvider->register($this); } @@ -118,7 +119,34 @@ class Container extends PimpleContainer implements ContainerInterface if (!$this->offsetExists($id)) { throw new ContainerValueNotFoundException(sprintf('Identifier "%s" is not defined.', $id)); } - return $this->offsetGet($id); + try { + return $this->offsetGet($id); + } catch (\InvalidArgumentException $exception) { + if ($this->exceptionThrownByContainer($exception)) { + throw new SlimContainerException( + sprintf('Container error while retrieving "%s"', $id), + null, + $exception + ); + } else { + throw $exception; + } + } + } + + /** + * Tests whether an exception needs to be recast for compliance with Container-Interop. This will be if the + * exception was thrown by Pimple. + * + * @param \InvalidArgumentException $exception + * + * @return bool + */ + private function exceptionThrownByContainer(\InvalidArgumentException $exception) + { + $trace = $exception->getTrace()[0]; + + return $trace['class'] === PimpleContainer::class && $trace['function'] === 'offsetGet'; } /** diff --git a/vendor/slim/slim/Slim/DefaultServicesProvider.php b/vendor/slim/slim/Slim/DefaultServicesProvider.php index e41831b..6b23738 100644 --- a/vendor/slim/slim/Slim/DefaultServicesProvider.php +++ b/vendor/slim/slim/Slim/DefaultServicesProvider.php @@ -1,6 +1,6 @@ get('settings')['routerCacheFile'])) { + $routerCacheFile = $container->get('settings')['routerCacheFile']; + } + + + $router = (new Router)->setCacheFile($routerCacheFile); + if (method_exists($router, 'setContainer')) { + $router->setContainer($container); + } + + return $router; }; } diff --git a/vendor/slim/slim/Slim/DeferredCallable.php b/vendor/slim/slim/Slim/DeferredCallable.php index def58ab..b79b948 100644 --- a/vendor/slim/slim/Slim/DeferredCallable.php +++ b/vendor/slim/slim/Slim/DeferredCallable.php @@ -1,5 +1,11 @@ displayErrorDetails = (bool) $displayErrorDetails; + } + + /** + * Write to the error log if displayErrorDetails is false + * + * @param \Exception|\Throwable $throwable + * + * @return void + */ + protected function writeToErrorLog($throwable) + { + if ($this->displayErrorDetails) { + return; + } + + $message = 'Slim Application Error:' . PHP_EOL; + $message .= $this->renderThrowableAsText($throwable); + while ($throwable = $throwable->getPrevious()) { + $message .= PHP_EOL . 'Previous error:' . PHP_EOL; + $message .= $this->renderThrowableAsText($throwable); + } + + $message .= PHP_EOL . 'View in rendered output by enabling the "displayErrorDetails" setting.' . PHP_EOL; + + $this->logError($message); + } + + /** + * Render error as Text. + * + * @param \Exception|\Throwable $throwable + * + * @return string + */ + protected function renderThrowableAsText($throwable) + { + $text = sprintf('Type: %s' . PHP_EOL, get_class($throwable)); + + if ($code = $throwable->getCode()) { + $text .= sprintf('Code: %s' . PHP_EOL, $code); + } + + if ($message = $throwable->getMessage()) { + $text .= sprintf('Message: %s' . PHP_EOL, htmlentities($message)); + } + + if ($file = $throwable->getFile()) { + $text .= sprintf('File: %s' . PHP_EOL, $file); + } + + if ($line = $throwable->getLine()) { + $text .= sprintf('Line: %s' . PHP_EOL, $line); + } + + if ($trace = $throwable->getTraceAsString()) { + $text .= sprintf('Trace: %s', $trace); + } + + return $text; + } + + /** + * Wraps the error_log function so that this can be easily tested + * + * @param $message + */ + protected function logError($message) + { + error_log($message); + } +} diff --git a/vendor/slim/slim/Slim/Handlers/AbstractHandler.php b/vendor/slim/slim/Slim/Handlers/AbstractHandler.php new file mode 100644 index 0000000..46e4ceb --- /dev/null +++ b/vendor/slim/slim/Slim/Handlers/AbstractHandler.php @@ -0,0 +1,59 @@ +getHeaderLine('Accept'); + $selectedContentTypes = array_intersect(explode(',', $acceptHeader), $this->knownContentTypes); + + if (count($selectedContentTypes)) { + return current($selectedContentTypes); + } + + // handle +json and +xml specially + if (preg_match('/\+(json|xml)/', $acceptHeader, $matches)) { + $mediaType = 'application/' . $matches[1]; + if (in_array($mediaType, $this->knownContentTypes)) { + return $mediaType; + } + } + + return 'text/html'; + } +} diff --git a/vendor/slim/slim/Slim/Handlers/Error.php b/vendor/slim/slim/Slim/Handlers/Error.php index c34e3c8..3bd53c9 100644 --- a/vendor/slim/slim/Slim/Handlers/Error.php +++ b/vendor/slim/slim/Slim/Handlers/Error.php @@ -1,6 +1,6 @@ displayErrorDetails = (bool)$displayErrorDetails; - } - /** * Invoke error handler * * @param ServerRequestInterface $request The most recent Request object * @param ResponseInterface $response The most recent Response object - * @param Exception $exception The caught Exception object + * @param \Exception $exception The caught Exception object * * @return ResponseInterface + * @throws UnexpectedValueException */ - public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Exception $exception) + public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Exception $exception) { $contentType = $this->determineContentType($request); switch ($contentType) { @@ -70,6 +47,9 @@ class Error case 'text/html': $output = $this->renderHtmlErrorMessage($exception); break; + + default: + throw new UnexpectedValueException('Cannot render unknown content type ' . $contentType); } $this->writeToErrorLog($exception); @@ -83,72 +63,14 @@ class Error ->withBody($body); } - - /** - * Write to the error log if displayErrorDetails is false - * - * @param Exception $exception - * @return void - */ - protected function writeToErrorLog($exception) - { - if ($this->displayErrorDetails) { - return; - } - - $message = 'Slim Application Error:' . PHP_EOL; - $message .= $this->renderTextException($exception); - while ($exception = $exception->getPrevious()) { - $message .= PHP_EOL . 'Previous exception:' . PHP_EOL; - $message .= $this->renderTextException($exception); - } - - $message .= PHP_EOL . 'View in rendered output by enabling the "displayErrorDetails" setting.' . PHP_EOL; - - error_log($message); - } - - /** - * Render exception as Text. - * - * @param Exception $exception - * - * @return string - */ - protected function renderTextException(Exception $exception) - { - $text = sprintf('Type: %s' . PHP_EOL, get_class($exception)); - - if (($code = $exception->getCode())) { - $text .= sprintf('Code: %s' . PHP_EOL, $code); - } - - if (($message = $exception->getMessage())) { - $text .= sprintf('Message: %s' . PHP_EOL, htmlentities($message)); - } - - if (($file = $exception->getFile())) { - $text .= sprintf('File: %s' . PHP_EOL, $file); - } - - if (($line = $exception->getLine())) { - $text .= sprintf('Line: %s' . PHP_EOL, $line); - } - - if (($trace = $exception->getTraceAsString())) { - $text .= sprintf('Trace: %s', $trace); - } - - return $text; - } - /** * Render HTML error page * - * @param Exception $exception + * @param \Exception $exception + * * @return string */ - protected function renderHtmlErrorMessage(Exception $exception) + protected function renderHtmlErrorMessage(\Exception $exception) { $title = 'Slim Application Error'; @@ -181,11 +103,11 @@ class Error /** * Render exception as HTML. * - * @param Exception $exception + * @param \Exception $exception * * @return string */ - protected function renderHtmlException(Exception $exception) + protected function renderHtmlException(\Exception $exception) { $html = sprintf('
      Type: %s
      ', get_class($exception)); @@ -216,10 +138,11 @@ class Error /** * Render JSON error * - * @param Exception $exception + * @param \Exception $exception + * * @return string */ - protected function renderJsonErrorMessage(Exception $exception) + protected function renderJsonErrorMessage(\Exception $exception) { $error = [ 'message' => 'Slim Application Error', @@ -246,10 +169,11 @@ class Error /** * Render XML error * - * @param Exception $exception + * @param \Exception $exception + * * @return string */ - protected function renderXmlErrorMessage(Exception $exception) + protected function renderXmlErrorMessage(\Exception $exception) { $xml = "\n Slim Application Error\n"; if ($this->displayErrorDetails) { @@ -279,22 +203,4 @@ class Error { return sprintf('', str_replace(']]>', ']]]]>', $content)); } - - /** - * Determine which content type we know about is wanted using Accept header - * - * @param ServerRequestInterface $request - * @return string - */ - private function determineContentType(ServerRequestInterface $request) - { - $acceptHeader = $request->getHeaderLine('Accept'); - $selectedContentTypes = array_intersect(explode(',', $acceptHeader), $this->knownContentTypes); - - if (count($selectedContentTypes)) { - return $selectedContentTypes[0]; - } - - return 'text/html'; - } } diff --git a/vendor/slim/slim/Slim/Handlers/NotAllowed.php b/vendor/slim/slim/Slim/Handlers/NotAllowed.php index c018dc6..92c308a 100644 --- a/vendor/slim/slim/Slim/Handlers/NotAllowed.php +++ b/vendor/slim/slim/Slim/Handlers/NotAllowed.php @@ -1,6 +1,6 @@ renderHtmlNotAllowedMessage($methods); break; + default: + throw new UnexpectedValueException('Cannot render unknown content type ' . $contentType); } } @@ -77,24 +69,6 @@ class NotAllowed ->withBody($body); } - /** - * Determine which content type we know about is wanted using Accept header - * - * @param ServerRequestInterface $request - * @return string - */ - private function determineContentType(ServerRequestInterface $request) - { - $acceptHeader = $request->getHeaderLine('Accept'); - $selectedContentTypes = array_intersect(explode(',', $acceptHeader), $this->knownContentTypes); - - if (count($selectedContentTypes)) { - return $selectedContentTypes[0]; - } - - return 'text/html'; - } - /** * Render PLAIN not allowed message * diff --git a/vendor/slim/slim/Slim/Handlers/NotFound.php b/vendor/slim/slim/Slim/Handlers/NotFound.php index d668199..cf7421d 100644 --- a/vendor/slim/slim/Slim/Handlers/NotFound.php +++ b/vendor/slim/slim/Slim/Handlers/NotFound.php @@ -1,6 +1,6 @@ determineContentType($request); switch ($contentType) { case 'application/json': - $output = $this->renderJsonNotFoundOutput($request, $response); + $output = $this->renderJsonNotFoundOutput(); break; case 'text/xml': case 'application/xml': - $output = $this->renderXmlNotFoundOutput($request, $response); + $output = $this->renderXmlNotFoundOutput(); break; case 'text/html': - $output = $this->renderHtmlNotFoundOutput($request, $response); + $output = $this->renderHtmlNotFoundOutput($request); + break; + + default: + throw new UnexpectedValueException('Cannot render unknown content type ' . $contentType); } $body = new Body(fopen('php://temp', 'r+')); @@ -65,33 +59,12 @@ class NotFound ->withBody($body); } - /** - * Determine which content type we know about is wanted using Accept header - * - * @param ServerRequestInterface $request - * @return string - */ - private function determineContentType(ServerRequestInterface $request) - { - $acceptHeader = $request->getHeaderLine('Accept'); - $selectedContentTypes = array_intersect(explode(',', $acceptHeader), $this->knownContentTypes); - - if (count($selectedContentTypes)) { - return $selectedContentTypes[0]; - } - - return 'text/html'; - } - /** * Return a response for application/json content not found * - * @param ServerRequestInterface $request The most recent Request object - * @param ResponseInterface $response The most recent Response object - * * @return ResponseInterface */ - protected function renderJsonNotFoundOutput(ServerRequestInterface $request, ResponseInterface $response) + protected function renderJsonNotFoundOutput() { return '{"message":"Not found"}'; } @@ -99,12 +72,9 @@ class NotFound /** * Return a response for xml content not found * - * @param ServerRequestInterface $request The most recent Request object - * @param ResponseInterface $response The most recent Response object - * * @return ResponseInterface */ - protected function renderXmlNotFoundOutput(ServerRequestInterface $request, ResponseInterface $response) + protected function renderXmlNotFoundOutput() { return 'Not found'; } @@ -113,11 +83,10 @@ class NotFound * Return a response for text/html content not found * * @param ServerRequestInterface $request The most recent Request object - * @param ResponseInterface $response The most recent Response object * * @return ResponseInterface */ - protected function renderHtmlNotFoundOutput(ServerRequestInterface $request, ResponseInterface $response) + protected function renderHtmlNotFoundOutput(ServerRequestInterface $request) { $homeUrl = (string)($request->getUri()->withPath('')->withQuery('')->withFragment('')); return <<displayErrorDetails = (bool)$displayErrorDetails; - } - /** * Invoke error handler * * @param ServerRequestInterface $request The most recent Request object * @param ResponseInterface $response The most recent Response object - * @param Throwable $error The caught Throwable object + * @param \Throwable $error The caught Throwable object * * @return ResponseInterface + * @throws UnexpectedValueException */ - public function __invoke(ServerRequestInterface $request, ResponseInterface $response, Throwable $error) + public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Throwable $error) { $contentType = $this->determineContentType($request); switch ($contentType) { @@ -70,6 +47,8 @@ class PhpError case 'text/html': $output = $this->renderHtmlErrorMessage($error); break; + default: + throw new UnexpectedValueException('Cannot render unknown content type ' . $contentType); } $this->writeToErrorLog($error); @@ -83,74 +62,14 @@ class PhpError ->withBody($body); } - - /** - * Write to the error log if displayErrorDetails is false - * - * @param Throwable $error - * - * @return void - */ - protected function writeToErrorLog($error) - { - if ($this->displayErrorDetails) { - return; - } - - $message = 'Slim Application Error:' . PHP_EOL; - $message .= $this->renderTextError($error); - while ($error = $error->getPrevious()) { - $message .= PHP_EOL . 'Previous error:' . PHP_EOL; - $message .= $this->renderTextError($error); - } - - $message .= PHP_EOL . 'View in rendered output by enabling the "displayErrorDetails" setting.' . PHP_EOL; - - error_log($message); - } - - /** - * Render error as Text. - * - * @param Throwable $error - * - * @return string - */ - protected function renderTextError(Throwable $error) - { - $text = sprintf('Type: %s' . PHP_EOL, get_class($error)); - - if (($code = $error->getCode())) { - $text .= sprintf('Code: %s' . PHP_EOL, $code); - } - - if (($message = $error->getMessage())) { - $text .= sprintf('Message: %s' . PHP_EOL, htmlentities($message)); - } - - if (($file = $error->getFile())) { - $text .= sprintf('File: %s' . PHP_EOL, $file); - } - - if (($line = $error->getLine())) { - $text .= sprintf('Line: %s' . PHP_EOL, $line); - } - - if (($trace = $error->getTraceAsString())) { - $text .= sprintf('Trace: %s', $trace); - } - - return $text; - } - /** * Render HTML error page * - * @param Throwable $error + * @param \Throwable $error * * @return string */ - protected function renderHtmlErrorMessage(Throwable $error) + protected function renderHtmlErrorMessage(\Throwable $error) { $title = 'Slim Application Error'; @@ -183,11 +102,11 @@ class PhpError /** * Render error as HTML. * - * @param Throwable $error + * @param \Throwable $error * * @return string */ - protected function renderHtmlError(Throwable $error) + protected function renderHtmlError(\Throwable $error) { $html = sprintf('
      Type: %s
      ', get_class($error)); @@ -218,11 +137,11 @@ class PhpError /** * Render JSON error * - * @param Throwable $error + * @param \Throwable $error * * @return string */ - protected function renderJsonErrorMessage(Throwable $error) + protected function renderJsonErrorMessage(\Throwable $error) { $json = [ 'message' => 'Slim Application Error', @@ -249,10 +168,11 @@ class PhpError /** * Render XML error * - * @param Throwable $error + * @param \Throwable $error + * * @return string */ - protected function renderXmlErrorMessage(Throwable $error) + protected function renderXmlErrorMessage(\Throwable $error) { $xml = "\n Slim Application Error\n"; if ($this->displayErrorDetails) { @@ -282,22 +202,4 @@ class PhpError { return sprintf('', str_replace(']]>', ']]]]>', $content)); } - - /** - * Determine which content type we know about is wanted using Accept header - * - * @param ServerRequestInterface $request - * @return string - */ - private function determineContentType(ServerRequestInterface $request) - { - $acceptHeader = $request->getHeaderLine('Accept'); - $selectedContentTypes = array_intersect(explode(',', $acceptHeader), $this->knownContentTypes); - - if (count($selectedContentTypes)) { - return $selectedContentTypes[0]; - } - - return 'text/html'; - } } diff --git a/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php b/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php index 157bdeb..2d99a4a 100644 --- a/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php +++ b/vendor/slim/slim/Slim/Handlers/Strategies/RequestResponse.php @@ -1,6 +1,6 @@ $value) { $key = strtoupper($key); if (isset(static::$special[$key]) || strpos($key, 'HTTP_') === 0) { @@ -63,6 +64,30 @@ class Headers extends Collection implements HeadersInterface return new static($data); } + /** + * If HTTP_AUTHORIZATION does not exist tries to get it from + * getallheaders() when available. + * + * @param Environment $environment The Slim application Environment + * + * @return Environment + */ + + public static function determineAuthorization(Environment $environment) + { + $authorization = $environment->get('HTTP_AUTHORIZATION'); + + if (null === $authorization && is_callable('getallheaders')) { + $headers = getallheaders(); + $headers = array_change_key_case($headers, CASE_LOWER); + if (isset($headers['authorization'])) { + $environment->set('HTTP_AUTHORIZATION', $headers['authorization']); + } + } + + return $environment; + } + /** * Return array of HTTP header names and values. * This method returns the _original_ header name diff --git a/vendor/slim/slim/Slim/Http/Message.php b/vendor/slim/slim/Slim/Http/Message.php index d0e832d..69377e9 100644 --- a/vendor/slim/slim/Slim/Http/Message.php +++ b/vendor/slim/slim/Slim/Http/Message.php @@ -1,6 +1,6 @@ true, + '1.1' => true, + '2.0' => true, + ]; + /** * Headers * @@ -86,13 +97,11 @@ abstract class Message implements MessageInterface */ public function withProtocolVersion($version) { - static $valid = [ - '1.0' => true, - '1.1' => true, - '2.0' => true, - ]; - if (!isset($valid[$version])) { - throw new InvalidArgumentException('Invalid HTTP version. Must be one of: 1.0, 1.1, 2.0'); + if (!isset(self::$validProtocolVersions[$version])) { + throw new InvalidArgumentException( + 'Invalid HTTP version. Must be one of: ' + . implode(', ', array_keys(self::$validProtocolVersions)) + ); } $clone = clone $this; $clone->protocolVersion = $version; diff --git a/vendor/slim/slim/Slim/Http/Request.php b/vendor/slim/slim/Slim/Http/Request.php index 67585d6..d9d4dee 100644 --- a/vendor/slim/slim/Slim/Http/Request.php +++ b/vendor/slim/slim/Slim/Http/Request.php @@ -1,6 +1,6 @@ method = $this->filterMethod($customMethod); } elseif ($this->originalMethod === 'POST') { - $body = $this->getParsedBody(); - - if (is_object($body) && property_exists($body, '_METHOD')) { - $this->method = $this->filterMethod((string)$body->_METHOD); - } elseif (is_array($body) && isset($body['_METHOD'])) { - $this->method = $this->filterMethod((string)$body['_METHOD']); + $overrideMethod = $this->filterMethod($this->getParsedBodyParam('_METHOD')); + if ($overrideMethod !== null) { + $this->method = $overrideMethod; } if ($this->getBody()->eof()) { @@ -684,6 +681,27 @@ class Request extends Message implements ServerRequestInterface return $this->cookies; } + /** + * Fetch cookie value from cookies sent by the client to the server. + * + * Note: This method is not part of the PSR-7 standard. + * + * @param string $key The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * + * @return mixed + */ + public function getCookieParam($key, $default = null) + { + $cookies = $this->getCookieParams(); + $result = $default; + if (isset($cookies[$key])) { + $result = $cookies[$key]; + } + + return $result; + } + /** * Return an instance with the specified cookies. * @@ -828,6 +846,22 @@ class Request extends Message implements ServerRequestInterface return $this->serverParams; } + /** + * Retrieve a server parameter. + * + * Note: This method is not part of the PSR-7 standard. + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function getServerParam($key, $default = null) + { + $serverParams = $this->getServerParams(); + + return isset($serverParams[$key]) ? $serverParams[$key] : $default; + } + /******************************************************************************* * Attributes ******************************************************************************/ @@ -967,9 +1001,15 @@ class Request extends Message implements ServerRequestInterface } $mediaType = $this->getMediaType(); - $body = (string)$this->getBody(); + + // look for a media type with a structured syntax suffix (RFC 6839) + $parts = explode('+', $mediaType); + if (count($parts) >= 2) { + $mediaType = 'application/' . $parts[count($parts)-1]; + } if (isset($this->bodyParsers[$mediaType]) === true) { + $body = (string)$this->getBody(); $parsed = $this->bodyParsers[$mediaType]($body); if (!is_null($parsed) && !is_object($parsed) && !is_array($parsed)) { @@ -1091,10 +1131,10 @@ class Request extends Message implements ServerRequestInterface * * Note: This method is not part of the PSR-7 standard. * - * @param $key - * @param null $default + * @param string $key + * @param mixed $default * - * @return null + * @return mixed */ public function getParsedBodyParam($key, $default = null) { @@ -1114,10 +1154,10 @@ class Request extends Message implements ServerRequestInterface * * Note: This method is not part of the PSR-7 standard. * - * @param $key - * @param null $default + * @param string $key + * @param mixed $default * - * @return null + * @return mixed */ public function getQueryParam($key, $default = null) { diff --git a/vendor/slim/slim/Slim/Http/RequestBody.php b/vendor/slim/slim/Slim/Http/RequestBody.php index 2345fe4..95429bd 100644 --- a/vendor/slim/slim/Slim/Http/RequestBody.php +++ b/vendor/slim/slim/Slim/Http/RequestBody.php @@ -1,6 +1,6 @@ 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', + 421 => 'Misdirected Request', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', @@ -98,7 +99,9 @@ class Response extends Message implements ResponseInterface 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', + 444 => 'Connection Closed Without Response', 451 => 'Unavailable For Legal Reasons', + 499 => 'Client Closed Request', //Server Error 5xx 500 => 'Internal Server Error', 501 => 'Not Implemented', @@ -111,6 +114,7 @@ class Response extends Message implements ResponseInterface 508 => 'Loop Detected', 510 => 'Not Extended', 511 => 'Network Authentication Required', + 599 => 'Network Connect Timeout Error', ]; /** @@ -136,7 +140,6 @@ class Response extends Message implements ResponseInterface public function __clone() { $this->headers = clone $this->headers; - $this->body = clone $this->body; } /******************************************************************************* @@ -273,12 +276,22 @@ class Response extends Message implements ResponseInterface * response to the client. * * @param string|UriInterface $url The redirect destination. - * @param int $status The redirect HTTP status code. + * @param int|null $status The redirect HTTP status code. * @return self */ - public function withRedirect($url, $status = 302) + public function withRedirect($url, $status = null) { - return $this->withStatus($status)->withHeader('Location', (string)$url); + $responseWithRedirect = $this->withHeader('Location', (string)$url); + + if (is_null($status) && $this->getStatusCode() === 200) { + $status = 302; + } + + if (!is_null($status)) { + return $responseWithRedirect->withStatus($status); + } + + return $responseWithRedirect; } /** @@ -297,16 +310,15 @@ class Response extends Message implements ResponseInterface */ public function withJson($data, $status = null, $encodingOptions = 0) { - $body = $this->getBody(); - $body->rewind(); - $body->write($json = json_encode($data, $encodingOptions)); + $response = $this->withBody(new Body(fopen('php://temp', 'r+'))); + $response->body->write($json = json_encode($data, $encodingOptions)); // Ensure that the json encoding passed successfully if ($json === false) { throw new \RuntimeException(json_last_error_msg(), json_last_error()); } - $responseWithJson = $this->withHeader('Content-Type', 'application/json;charset=utf-8'); + $responseWithJson = $response->withHeader('Content-Type', 'application/json;charset=utf-8'); if (isset($status)) { return $responseWithJson->withStatus($status); } diff --git a/vendor/slim/slim/Slim/Http/Stream.php b/vendor/slim/slim/Slim/Http/Stream.php index 97de9ac..0f294a0 100644 --- a/vendor/slim/slim/Slim/Http/Stream.php +++ b/vendor/slim/slim/Slim/Http/Stream.php @@ -1,6 +1,6 @@ writable = null; $this->seekable = null; $this->size = null; + $this->isPipe = null; return $oldResource; } @@ -196,7 +211,11 @@ class Stream implements StreamInterface public function close() { if ($this->isAttached() === true) { - fclose($this->stream); + if ($this->isPipe()) { + pclose($this->stream); + } else { + fclose($this->stream); + } } $this->detach(); @@ -211,7 +230,7 @@ class Stream implements StreamInterface { if (!$this->size && $this->isAttached() === true) { $stats = fstat($this->stream); - $this->size = isset($stats['size']) ? $stats['size'] : null; + $this->size = isset($stats['size']) && !$this->isPipe() ? $stats['size'] : null; } return $this->size; @@ -226,7 +245,7 @@ class Stream implements StreamInterface */ public function tell() { - if (!$this->isAttached() || ($position = ftell($this->stream)) === false) { + if (!$this->isAttached() || ($position = ftell($this->stream)) === false || $this->isPipe()) { throw new RuntimeException('Could not get the position of the pointer in stream'); } @@ -251,13 +270,17 @@ class Stream implements StreamInterface public function isReadable() { if ($this->readable === null) { - $this->readable = false; - if ($this->isAttached()) { - $meta = $this->getMetadata(); - foreach (self::$modes['readable'] as $mode) { - if (strpos($meta['mode'], $mode) === 0) { - $this->readable = true; - break; + if ($this->isPipe()) { + $this->readable = true; + } else { + $this->readable = false; + if ($this->isAttached()) { + $meta = $this->getMetadata(); + foreach (self::$modes['readable'] as $mode) { + if (strpos($meta['mode'], $mode) === 0) { + $this->readable = true; + break; + } } } } @@ -300,7 +323,7 @@ class Stream implements StreamInterface $this->seekable = false; if ($this->isAttached()) { $meta = $this->getMetadata(); - $this->seekable = $meta['seekable']; + $this->seekable = !$this->isPipe() && $meta['seekable']; } } @@ -406,4 +429,22 @@ class Stream implements StreamInterface return $contents; } + + /** + * Returns whether or not the stream is a pipe. + * + * @return bool + */ + public function isPipe() + { + if ($this->isPipe === null) { + $this->isPipe = false; + if ($this->isAttached()) { + $mode = fstat($this->stream)['mode']; + $this->isPipe = ($mode & self::FSTAT_MODE_S_IFIFO) !== 0; + } + } + + return $this->isPipe; + } } diff --git a/vendor/slim/slim/Slim/Http/UploadedFile.php b/vendor/slim/slim/Slim/Http/UploadedFile.php index ff97027..3f97be8 100644 --- a/vendor/slim/slim/Slim/Http/UploadedFile.php +++ b/vendor/slim/slim/Slim/Http/UploadedFile.php @@ -1,6 +1,6 @@ 0; + if (!$targetIsStream && !is_writable(dirname($targetPath))) { throw new InvalidArgumentException('Upload target path is not writable'); } - $targetIsStream = strpos($targetPath, '://') > 0; if ($targetIsStream) { if (!copy($this->file, $targetPath)) { throw new RuntimeException(sprintf('Error moving uploaded file %1s to %2s', $this->name, $targetPath)); diff --git a/vendor/slim/slim/Slim/Http/Uri.php b/vendor/slim/slim/Slim/Http/Uri.php index 27b1d0d..17248a2 100644 --- a/vendor/slim/slim/Slim/Http/Uri.php +++ b/vendor/slim/slim/Slim/Http/Uri.php @@ -1,6 +1,6 @@ get('QUERY_STRING', ''); + if ($queryString === '') { + $queryString = parse_url('http://example.com' . $env->get('REQUEST_URI'), PHP_URL_QUERY); + } // Fragment $fragment = ''; diff --git a/vendor/slim/slim/Slim/Interfaces/CallableResolverInterface.php b/vendor/slim/slim/Slim/Interfaces/CallableResolverInterface.php index 9bde59a..f5b8ce4 100644 --- a/vendor/slim/slim/Slim/Interfaces/CallableResolverInterface.php +++ b/vendor/slim/slim/Slim/Interfaces/CallableResolverInterface.php @@ -1,6 +1,6 @@ middleware[] = new DeferredCallable($callable, $this->container); return $this; } + + /** + * Set the route pattern + * + * @set string + */ + public function setPattern($newPattern) + { + $this->pattern = $newPattern; + } } diff --git a/vendor/slim/slim/Slim/Route.php b/vendor/slim/slim/Slim/Route.php index 3cb4a0e..ac4435c 100644 --- a/vendor/slim/slim/Slim/Route.php +++ b/vendor/slim/slim/Slim/Route.php @@ -1,6 +1,6 @@ methods = $methods; + $this->methods = is_string($methods) ? [$methods] : $methods; $this->pattern = $pattern; $this->callable = $callable; $this->groups = $groups; @@ -120,6 +129,16 @@ class Route extends Routable implements RouteInterface return $this->callable; } + /** + * This method enables you to override the Route's callable + * + * @param string|\Closure $callable + */ + public function setCallable($callable) + { + $this->callable = $callable; + } + /** * Get route methods * @@ -324,6 +343,11 @@ class Route extends Routable implements RouteInterface ob_start(); $newResponse = $handler($this->callable, $request, $response, $this->arguments); $output = ob_get_clean(); + // @codeCoverageIgnoreStart + } catch (Throwable $e) { + ob_end_clean(); + throw $e; + // @codeCoverageIgnoreEnd } catch (Exception $e) { ob_end_clean(); throw $e; diff --git a/vendor/slim/slim/Slim/RouteGroup.php b/vendor/slim/slim/Slim/RouteGroup.php index a0cdf4d..daf72bd 100644 --- a/vendor/slim/slim/Slim/RouteGroup.php +++ b/vendor/slim/slim/Slim/RouteGroup.php @@ -1,6 +1,6 @@ cacheFile = $cacheFile; + + if ($cacheFile !== false && !is_writable(dirname($cacheFile))) { + throw new RuntimeException('Router cacheFile directory must be writable'); + } + + + return $this; + } + + /** + * @param ContainerInterface $container + */ + public function setContainer(ContainerInterface $container) + { + $this->container = $container; + } + /** * Add route * @@ -123,7 +168,7 @@ class Router implements RouterInterface $methods = array_map("strtoupper", $methods); // Add route - $route = new Route($methods, $pattern, $handler, $this->routeGroups, $this->routeCounter); + $route = $this->createRoute($methods, $pattern, $handler); $this->routes[$route->getIdentifier()] = $route; $this->routeCounter++; @@ -142,25 +187,59 @@ class Router implements RouterInterface public function dispatch(ServerRequestInterface $request) { $uri = '/' . ltrim($request->getUri()->getPath(), '/'); - + return $this->createDispatcher()->dispatch( $request->getMethod(), $uri ); } + /** + * Create a new Route object + * + * @param string[] $methods Array of HTTP methods + * @param string $pattern The route pattern + * @param callable $handler The route callable + * + * @return \Slim\Interfaces\RouteInterface + */ + protected function createRoute($methods, $pattern, $callable) + { + $route = new Route($methods, $pattern, $callable, $this->routeGroups, $this->routeCounter); + if (!empty($this->container)) { + $route->setContainer($this->container); + } + + return $route; + } + /** * @return \FastRoute\Dispatcher */ protected function createDispatcher() { - return $this->dispatcher ?: \FastRoute\simpleDispatcher(function (RouteCollector $r) { + if ($this->dispatcher) { + return $this->dispatcher; + } + + $routeDefinitionCallback = function (RouteCollector $r) { foreach ($this->getRoutes() as $route) { $r->addRoute($route->getMethods(), $route->getPattern(), $route->getIdentifier()); } - }, [ - 'routeParser' => $this->routeParser - ]); + }; + + if ($this->cacheFile) { + $this->dispatcher = \FastRoute\cachedDispatcher($routeDefinitionCallback, [ + 'routeParser' => $this->routeParser, + 'cacheFile' => $this->cacheFile, + ]); + } else { + $this->dispatcher = \FastRoute\simpleDispatcher($routeDefinitionCallback, [ + 'routeParser' => $this->routeParser, + ]); + } + + return $this->dispatcher; } /** @@ -200,6 +279,21 @@ class Router implements RouterInterface throw new RuntimeException('Named route does not exist for name: ' . $name); } + /** + * Remove named route + * + * @param string $name Route name + * + * @throws RuntimeException If named route does not exist + */ + public function removeNamedRoute($name) + { + $route = $this->getNamedRoute($name); + + // no exception, route exists, now remove by id + unset($this->routes[$route->getIdentifier()]); + } + /** * Process route groups * diff --git a/vendor/slim/slim/composer.json b/vendor/slim/slim/composer.json index df18901..ed19202 100644 --- a/vendor/slim/slim/composer.json +++ b/vendor/slim/slim/composer.json @@ -3,7 +3,7 @@ "type": "library", "description": "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs", "keywords": ["framework","micro","api","router"], - "homepage": "http://slimframework.com", + "homepage": "https://slimframework.com", "license": "MIT", "authors": [ { @@ -31,13 +31,16 @@ "php": ">=5.5.0", "pimple/pimple": "^3.0", "psr/http-message": "^1.0", - "nikic/fast-route": "^0.6", + "nikic/fast-route": "^1.0", "container-interop/container-interop": "^1.1" }, "require-dev": { "squizlabs/php_codesniffer": "^2.5", "phpunit/phpunit": "^4.0" }, + "provide": { + "psr/http-message-implementation": "1.0" + }, "autoload": { "psr-4": { "Slim\\": "Slim" @@ -45,8 +48,8 @@ }, "scripts": { "test": [ - "php vendor/bin/phpcs", - "php vendor/bin/phpunit" + "@phpunit", + "@phpcs" ], "phpunit": "php vendor/bin/phpunit", "phpcs": "php vendor/bin/phpcs" diff --git a/vendor/slim/slim/example/.htaccess b/vendor/slim/slim/example/.htaccess deleted file mode 100644 index 0784bd2..0000000 --- a/vendor/slim/slim/example/.htaccess +++ /dev/null @@ -1,12 +0,0 @@ -# Note: see https://httpd.apache.org/docs/current/howto/htaccess.html: -# -# "You should avoid using .htaccess files completely if you have access to -# httpd main server config file. Using .htaccess files slows down your Apache -# http server. Any directive that you can include in a .htaccess file is -# better set in a Directory block, as it will have the same effect with -# better performance." - -RewriteEngine On -RewriteCond %{REQUEST_FILENAME} !-f -RewriteCond %{REQUEST_FILENAME} !-d -RewriteRule ^ index.php [QSA,L] diff --git a/vendor/slim/slim/example/index.php b/vendor/slim/slim/example/index.php deleted file mode 100644 index ef895f8..0000000 --- a/vendor/slim/slim/example/index.php +++ /dev/null @@ -1,45 +0,0 @@ -get('/', function ($request, $response, $args) { - $response->write("Welcome to Slim!"); - return $response; -}); - -$app->get('/hello[/{name}]', function ($request, $response, $args) { - $response->write("Hello, " . $args['name']); - return $response; -})->setArgument('name', 'World!'); - -/** - * Step 4: Run the Slim application - * - * This method should be called last. This executes the Slim application - * and returns the HTTP response to the HTTP client. - */ -$app->run(); diff --git a/vendor/symfony/yaml/CHANGELOG.md b/vendor/symfony/yaml/CHANGELOG.md index fe77de7..45c331f 100644 --- a/vendor/symfony/yaml/CHANGELOG.md +++ b/vendor/symfony/yaml/CHANGELOG.md @@ -1,6 +1,55 @@ CHANGELOG ========= +3.2.0 +----- + + * Mappings with a colon (`:`) that is not followed by a whitespace are deprecated + and will lead to a `ParseException` in Symfony 4.0 (e.g. `foo:bar` must be + `foo: bar`). + + * Added support for parsing PHP constants: + + ```php + Yaml::parse('!php/const:PHP_INT_MAX', Yaml::PARSE_CONSTANT); + ``` + + * Support for silently ignoring duplicate mapping keys in YAML has been + deprecated and will lead to a `ParseException` in Symfony 4.0. + +3.1.0 +----- + + * Strings that are not UTF-8 encoded will be dumped as base64 encoded binary + data. + + * Added support for dumping multi line strings as literal blocks. + + * Added support for parsing base64 encoded binary data when they are tagged + with the `!!binary` tag. + + * Added support for parsing timestamps as `\DateTime` objects: + + ```php + Yaml::parse('2001-12-15 21:59:43.10 -5', Yaml::PARSE_DATETIME); + ``` + + * `\DateTime` and `\DateTimeImmutable` objects are dumped as YAML timestamps. + + * Deprecated usage of `%` at the beginning of an unquoted string. + + * Added support for customizing the YAML parser behavior through an optional bit field: + + ```php + Yaml::parse('{ "foo": "bar", "fiz": "cat" }', Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE | Yaml::PARSE_OBJECT | Yaml::PARSE_OBJECT_FOR_MAP); + ``` + + * Added support for customizing the dumped YAML string through an optional bit field: + + ```php + Yaml::dump(array('foo' => new A(), 'bar' => 1), 0, 0, Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE | Yaml::DUMP_OBJECT); + ``` + 3.0.0 ----- diff --git a/vendor/symfony/yaml/Command/LintCommand.php b/vendor/symfony/yaml/Command/LintCommand.php new file mode 100644 index 0000000..ea86a1f --- /dev/null +++ b/vendor/symfony/yaml/Command/LintCommand.php @@ -0,0 +1,234 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml\Command; + +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Symfony\Component\Yaml\Exception\ParseException; +use Symfony\Component\Yaml\Parser; + +/** + * Validates YAML files syntax and outputs encountered errors. + * + * @author Grégoire Pineau + * @author Robin Chalas + */ +class LintCommand extends Command +{ + private $parser; + private $format; + private $displayCorrectFiles; + private $directoryIteratorProvider; + private $isReadableProvider; + + public function __construct($name = null, $directoryIteratorProvider = null, $isReadableProvider = null) + { + parent::__construct($name); + + $this->directoryIteratorProvider = $directoryIteratorProvider; + $this->isReadableProvider = $isReadableProvider; + } + + /** + * {@inheritdoc} + */ + protected function configure() + { + $this + ->setName('lint:yaml') + ->setDescription('Lints a file and outputs encountered errors') + ->addArgument('filename', null, 'A file or a directory or STDIN') + ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'txt') + ->setHelp(<<%command.name% command lints a YAML file and outputs to STDOUT +the first encountered syntax error. + +You can validates YAML contents passed from STDIN: + + cat filename | php %command.full_name% + +You can also validate the syntax of a file: + + php %command.full_name% filename + +Or of a whole directory: + + php %command.full_name% dirname + php %command.full_name% dirname --format=json + +EOF + ) + ; + } + + protected function execute(InputInterface $input, OutputInterface $output) + { + $io = new SymfonyStyle($input, $output); + $filename = $input->getArgument('filename'); + $this->format = $input->getOption('format'); + $this->displayCorrectFiles = $output->isVerbose(); + + if (!$filename) { + if (!$stdin = $this->getStdin()) { + throw new \RuntimeException('Please provide a filename or pipe file content to STDIN.'); + } + + return $this->display($io, array($this->validate($stdin))); + } + + if (!$this->isReadable($filename)) { + throw new \RuntimeException(sprintf('File or directory "%s" is not readable.', $filename)); + } + + $filesInfo = array(); + foreach ($this->getFiles($filename) as $file) { + $filesInfo[] = $this->validate(file_get_contents($file), $file); + } + + return $this->display($io, $filesInfo); + } + + private function validate($content, $file = null) + { + try { + $this->getParser()->parse($content); + } catch (ParseException $e) { + return array('file' => $file, 'valid' => false, 'message' => $e->getMessage()); + } + + return array('file' => $file, 'valid' => true); + } + + private function display(SymfonyStyle $io, array $files) + { + switch ($this->format) { + case 'txt': + return $this->displayTxt($io, $files); + case 'json': + return $this->displayJson($io, $files); + default: + throw new \InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format)); + } + } + + private function displayTxt(SymfonyStyle $io, array $filesInfo) + { + $countFiles = count($filesInfo); + $erroredFiles = 0; + + foreach ($filesInfo as $info) { + if ($info['valid'] && $this->displayCorrectFiles) { + $io->comment('OK'.($info['file'] ? sprintf(' in %s', $info['file']) : '')); + } elseif (!$info['valid']) { + ++$erroredFiles; + $io->text(' ERROR '.($info['file'] ? sprintf(' in %s', $info['file']) : '')); + $io->text(sprintf(' >> %s', $info['message'])); + } + } + + if ($erroredFiles === 0) { + $io->success(sprintf('All %d YAML files contain valid syntax.', $countFiles)); + } else { + $io->warning(sprintf('%d YAML files have valid syntax and %d contain errors.', $countFiles - $erroredFiles, $erroredFiles)); + } + + return min($erroredFiles, 1); + } + + private function displayJson(SymfonyStyle $io, array $filesInfo) + { + $errors = 0; + + array_walk($filesInfo, function (&$v) use (&$errors) { + $v['file'] = (string) $v['file']; + if (!$v['valid']) { + ++$errors; + } + }); + + $io->writeln(json_encode($filesInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + + return min($errors, 1); + } + + private function getFiles($fileOrDirectory) + { + if (is_file($fileOrDirectory)) { + yield new \SplFileInfo($fileOrDirectory); + + return; + } + + foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) { + if (!in_array($file->getExtension(), array('yml', 'yaml'))) { + continue; + } + + yield $file; + } + } + + private function getStdin() + { + if (0 !== ftell(STDIN)) { + return; + } + + $inputs = ''; + while (!feof(STDIN)) { + $inputs .= fread(STDIN, 1024); + } + + return $inputs; + } + + private function getParser() + { + if (!$this->parser) { + $this->parser = new Parser(); + } + + return $this->parser; + } + + private function getDirectoryIterator($directory) + { + $default = function ($directory) { + return new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS), + \RecursiveIteratorIterator::LEAVES_ONLY + ); + }; + + if (null !== $this->directoryIteratorProvider) { + return call_user_func($this->directoryIteratorProvider, $directory, $default); + } + + return $default($directory); + } + + private function isReadable($fileOrDirectory) + { + $default = function ($fileOrDirectory) { + return is_readable($fileOrDirectory); + }; + + if (null !== $this->isReadableProvider) { + return call_user_func($this->isReadableProvider, $fileOrDirectory, $default); + } + + return $default($fileOrDirectory); + } +} diff --git a/vendor/symfony/yaml/Dumper.php b/vendor/symfony/yaml/Dumper.php index 21351a5..98d8243 100644 --- a/vendor/symfony/yaml/Dumper.php +++ b/vendor/symfony/yaml/Dumper.php @@ -23,18 +23,28 @@ class Dumper * * @var int */ - protected $indentation = 4; + protected $indentation; + + /** + * @param int $indentation + */ + public function __construct($indentation = 4) + { + if ($indentation < 1) { + throw new \InvalidArgumentException('The indentation must be greater than zero.'); + } + + $this->indentation = $indentation; + } /** * Sets the indentation. * - * @param int $num The amount of spaces to use for indentation of nested nodes. + * @param int $num The amount of spaces to use for indentation of nested nodes */ public function setIndentation($num) { - if ($num < 1) { - throw new \InvalidArgumentException('The indentation must be greater than zero.'); - } + @trigger_error('The '.__METHOD__.' method is deprecated since version 3.1 and will be removed in 4.0. Pass the indentation to the constructor instead.', E_USER_DEPRECATED); $this->indentation = (int) $num; } @@ -42,32 +52,59 @@ class Dumper /** * Dumps a PHP value to YAML. * - * @param mixed $input The PHP value - * @param int $inline The level where you switch to inline YAML - * @param int $indent The level of indentation (used internally) - * @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise - * @param bool $objectSupport true if object support is enabled, false otherwise + * @param mixed $input The PHP value + * @param int $inline The level where you switch to inline YAML + * @param int $indent The level of indentation (used internally) + * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string * * @return string The YAML representation of the PHP value */ - public function dump($input, $inline = 0, $indent = 0, $exceptionOnInvalidType = false, $objectSupport = false) + public function dump($input, $inline = 0, $indent = 0, $flags = 0) { + if (is_bool($flags)) { + @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED); + + if ($flags) { + $flags = Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE; + } else { + $flags = 0; + } + } + + if (func_num_args() >= 5) { + @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::DUMP_OBJECT flag instead.', E_USER_DEPRECATED); + + if (func_get_arg(4)) { + $flags |= Yaml::DUMP_OBJECT; + } + } + $output = ''; $prefix = $indent ? str_repeat(' ', $indent) : ''; if ($inline <= 0 || !is_array($input) || empty($input)) { - $output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport); + $output .= $prefix.Inline::dump($input, $flags); } else { - $isAHash = array_keys($input) !== range(0, count($input) - 1); + $isAHash = Inline::isHash($input); foreach ($input as $key => $value) { + if ($inline >= 1 && Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK & $flags && is_string($value) && false !== strpos($value, "\n")) { + $output .= sprintf("%s%s%s |\n", $prefix, $isAHash ? Inline::dump($key, $flags).':' : '-', ''); + + foreach (preg_split('/\n|\r\n/', $value) as $row) { + $output .= sprintf("%s%s%s\n", $prefix, str_repeat(' ', $this->indentation), $row); + } + + continue; + } + $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value); $output .= sprintf('%s%s%s%s', $prefix, - $isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport).':' : '-', + $isAHash ? Inline::dump($key, $flags).':' : '-', $willBeInlined ? ' ' : "\n", - $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport) + $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $flags) ).($willBeInlined ? "\n" : ''); } } diff --git a/vendor/symfony/yaml/Escaper.php b/vendor/symfony/yaml/Escaper.php index 7bac8dd..a74f14d 100644 --- a/vendor/symfony/yaml/Escaper.php +++ b/vendor/symfony/yaml/Escaper.php @@ -46,7 +46,7 @@ class Escaper * * @param string $value A PHP value * - * @return bool True if the value would require double quotes. + * @return bool True if the value would require double quotes */ public static function requiresDoubleQuoting($value) { @@ -70,7 +70,7 @@ class Escaper * * @param string $value A PHP value * - * @return bool True if the value would require single quotes. + * @return bool True if the value would require single quotes */ public static function requiresSingleQuoting($value) { diff --git a/vendor/symfony/yaml/Inline.php b/vendor/symfony/yaml/Inline.php index 10fbd89..8ad3b1e 100644 --- a/vendor/symfony/yaml/Inline.php +++ b/vendor/symfony/yaml/Inline.php @@ -18,33 +18,69 @@ use Symfony\Component\Yaml\Exception\DumpException; * Inline implements a YAML parser/dumper for the YAML inline syntax. * * @author Fabien Potencier + * + * @internal */ class Inline { const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')'; + public static $parsedLineNumber; + private static $exceptionOnInvalidType = false; private static $objectSupport = false; private static $objectForMap = false; + private static $constantSupport = false; /** - * Converts a YAML string to a PHP array. + * Converts a YAML string to a PHP value. * - * @param string $value A YAML string - * @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise - * @param bool $objectSupport true if object support is enabled, false otherwise - * @param bool $objectForMap true if maps should return a stdClass instead of array() - * @param array $references Mapping of variable names to values + * @param string $value A YAML string + * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior + * @param array $references Mapping of variable names to values * - * @return array A PHP array representing the YAML string + * @return mixed A PHP value * * @throws ParseException */ - public static function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false, $references = array()) + public static function parse($value, $flags = 0, $references = array()) { - self::$exceptionOnInvalidType = $exceptionOnInvalidType; - self::$objectSupport = $objectSupport; - self::$objectForMap = $objectForMap; + if (is_bool($flags)) { + @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED); + + if ($flags) { + $flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE; + } else { + $flags = 0; + } + } + + if (func_num_args() >= 3 && !is_array($references)) { + @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED); + + if ($references) { + $flags |= Yaml::PARSE_OBJECT; + } + + if (func_num_args() >= 4) { + @trigger_error('Passing a boolean flag to toggle object for map support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED); + + if (func_get_arg(3)) { + $flags |= Yaml::PARSE_OBJECT_FOR_MAP; + } + } + + if (func_num_args() >= 5) { + $references = func_get_arg(4); + } else { + $references = array(); + } + } + + self::$exceptionOnInvalidType = (bool) (Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE & $flags); + self::$objectSupport = (bool) (Yaml::PARSE_OBJECT & $flags); + self::$objectForMap = (bool) (Yaml::PARSE_OBJECT_FOR_MAP & $flags); + self::$constantSupport = (bool) (Yaml::PARSE_CONSTANT & $flags); $value = trim($value); @@ -60,15 +96,15 @@ class Inline $i = 0; switch ($value[0]) { case '[': - $result = self::parseSequence($value, $i, $references); + $result = self::parseSequence($value, $flags, $i, $references); ++$i; break; case '{': - $result = self::parseMapping($value, $i, $references); + $result = self::parseMapping($value, $flags, $i, $references); ++$i; break; default: - $result = self::parseScalar($value, null, array('"', "'"), $i, true, $references); + $result = self::parseScalar($value, $flags, null, array('"', "'"), $i, true, $references); } // some comments are allowed at the end @@ -86,35 +122,58 @@ class Inline /** * Dumps a given PHP variable to a YAML string. * - * @param mixed $value The PHP variable to convert - * @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise - * @param bool $objectSupport true if object support is enabled, false otherwise + * @param mixed $value The PHP variable to convert + * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string * - * @return string The YAML string representing the PHP array + * @return string The YAML string representing the PHP value * * @throws DumpException When trying to dump PHP resource */ - public static function dump($value, $exceptionOnInvalidType = false, $objectSupport = false) + public static function dump($value, $flags = 0) { + if (is_bool($flags)) { + @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED); + + if ($flags) { + $flags = Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE; + } else { + $flags = 0; + } + } + + if (func_num_args() >= 3) { + @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::DUMP_OBJECT flag instead.', E_USER_DEPRECATED); + + if (func_get_arg(2)) { + $flags |= Yaml::DUMP_OBJECT; + } + } + switch (true) { case is_resource($value): - if ($exceptionOnInvalidType) { + if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) { throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value))); } return 'null'; + case $value instanceof \DateTimeInterface: + return $value->format('c'); case is_object($value): - if ($objectSupport) { + if (Yaml::DUMP_OBJECT & $flags) { return '!php/object:'.serialize($value); } - if ($exceptionOnInvalidType) { + if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) { + return self::dumpArray((array) $value, $flags); + } + + if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) { throw new DumpException('Object support when dumping a YAML file has been disabled.'); } return 'null'; case is_array($value): - return self::dumpArray($value, $exceptionOnInvalidType, $objectSupport); + return self::dumpArray($value, $flags); case null === $value: return 'null'; case true === $value: @@ -146,9 +205,12 @@ class Inline return $repr; case '' == $value: return "''"; + case self::isBinaryString($value): + return '!!binary '.base64_encode($value); case Escaper::requiresDoubleQuoting($value): return Escaper::escapeWithDoubleQuotes($value); case Escaper::requiresSingleQuoting($value): + case preg_match('{^[0-9]+[_0-9]*$}', $value): case preg_match(self::getHexRegex(), $value): case preg_match(self::getTimestampRegex(), $value): return Escaper::escapeWithSingleQuotes($value); @@ -157,57 +219,75 @@ class Inline } } + /** + * Check if given array is hash or just normal indexed array. + * + * @internal + * + * @param array $value The PHP array to check + * + * @return bool true if value is hash array, false otherwise + */ + public static function isHash(array $value) + { + $expectedKey = 0; + + foreach ($value as $key => $val) { + if ($key !== $expectedKey++) { + return true; + } + } + + return false; + } + /** * Dumps a PHP array to a YAML string. * - * @param array $value The PHP array to dump - * @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise - * @param bool $objectSupport true if object support is enabled, false otherwise + * @param array $value The PHP array to dump + * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string * * @return string The YAML string representing the PHP array */ - private static function dumpArray($value, $exceptionOnInvalidType, $objectSupport) + private static function dumpArray($value, $flags) { // array - $keys = array_keys($value); - $keysCount = count($keys); - if ((1 === $keysCount && '0' == $keys[0]) - || ($keysCount > 1 && array_reduce($keys, function ($v, $w) { return (int) $v + $w; }, 0) === $keysCount * ($keysCount - 1) / 2) - ) { + if ($value && !self::isHash($value)) { $output = array(); foreach ($value as $val) { - $output[] = self::dump($val, $exceptionOnInvalidType, $objectSupport); + $output[] = self::dump($val, $flags); } return sprintf('[%s]', implode(', ', $output)); } - // mapping + // hash $output = array(); foreach ($value as $key => $val) { - $output[] = sprintf('%s: %s', self::dump($key, $exceptionOnInvalidType, $objectSupport), self::dump($val, $exceptionOnInvalidType, $objectSupport)); + $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags)); } return sprintf('{ %s }', implode(', ', $output)); } /** - * Parses a scalar to a YAML string. + * Parses a YAML scalar. * * @param string $scalar + * @param int $flags * @param string $delimiters * @param array $stringDelimiters * @param int &$i * @param bool $evaluate * @param array $references * - * @return string A YAML string + * @return string * * @throws ParseException When malformed inline YAML string is parsed * * @internal */ - public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array()) + public static function parseScalar($scalar, $flags = 0, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array()) { if (in_array($scalar[$i], $stringDelimiters)) { // quoted scalar @@ -233,7 +313,7 @@ class Inline $output = $match[1]; $i += strlen($output); } else { - throw new ParseException(sprintf('Malformed inline YAML string (%s).', $scalar)); + throw new ParseException(sprintf('Malformed inline YAML string: %s.', $scalar)); } // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >) @@ -241,8 +321,12 @@ class Inline throw new ParseException(sprintf('The reserved indicator "%s" cannot start a plain scalar; you need to quote the scalar.', $output[0])); } + if ($output && '%' === $output[0]) { + @trigger_error(sprintf('Not quoting the scalar "%s" starting with the "%%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0.', $output), E_USER_DEPRECATED); + } + if ($evaluate) { - $output = self::evaluateScalar($output, $references); + $output = self::evaluateScalar($output, $flags, $references); } } @@ -250,19 +334,19 @@ class Inline } /** - * Parses a quoted scalar to YAML. + * Parses a YAML quoted scalar. * * @param string $scalar * @param int &$i * - * @return string A YAML string + * @return string * * @throws ParseException When malformed inline YAML string is parsed */ private static function parseQuotedScalar($scalar, &$i) { if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) { - throw new ParseException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i))); + throw new ParseException(sprintf('Malformed inline YAML string: %s.', substr($scalar, $i))); } $output = substr($match[0], 1, strlen($match[0]) - 2); @@ -280,17 +364,18 @@ class Inline } /** - * Parses a sequence to a YAML string. + * Parses a YAML sequence. * * @param string $sequence + * @param int $flags * @param int &$i * @param array $references * - * @return string A YAML string + * @return array * * @throws ParseException When malformed inline YAML string is parsed */ - private static function parseSequence($sequence, &$i = 0, $references = array()) + private static function parseSequence($sequence, $flags, &$i = 0, $references = array()) { $output = array(); $len = strlen($sequence); @@ -301,11 +386,11 @@ class Inline switch ($sequence[$i]) { case '[': // nested sequence - $output[] = self::parseSequence($sequence, $i, $references); + $output[] = self::parseSequence($sequence, $flags, $i, $references); break; case '{': // nested mapping - $output[] = self::parseMapping($sequence, $i, $references); + $output[] = self::parseMapping($sequence, $flags, $i, $references); break; case ']': return $output; @@ -314,14 +399,14 @@ class Inline break; default: $isQuoted = in_array($sequence[$i], array('"', "'")); - $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i, true, $references); + $value = self::parseScalar($sequence, $flags, array(',', ']'), array('"', "'"), $i, true, $references); // the value can be an array if a reference has been resolved to an array var - if (!is_array($value) && !$isQuoted && false !== strpos($value, ': ')) { + if (is_string($value) && !$isQuoted && false !== strpos($value, ': ')) { // embedded mapping? try { $pos = 0; - $value = self::parseMapping('{'.$value.'}', $pos, $references); + $value = self::parseMapping('{'.$value.'}', $flags, $pos, $references); } catch (\InvalidArgumentException $e) { // no, it's not } @@ -335,21 +420,22 @@ class Inline ++$i; } - throw new ParseException(sprintf('Malformed inline YAML string %s', $sequence)); + throw new ParseException(sprintf('Malformed inline YAML string: %s.', $sequence)); } /** - * Parses a mapping to a YAML string. + * Parses a YAML mapping. * * @param string $mapping + * @param int $flags * @param int &$i * @param array $references * - * @return string A YAML string + * @return array|\stdClass * * @throws ParseException When malformed inline YAML string is parsed */ - private static function parseMapping($mapping, &$i = 0, $references = array()) + private static function parseMapping($mapping, $flags, &$i = 0, $references = array()) { $output = array(); $len = strlen($mapping); @@ -371,7 +457,15 @@ class Inline } // key - $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false); + $key = self::parseScalar($mapping, $flags, array(':', ' '), array('"', "'"), $i, false); + + if (false === $i = strpos($mapping, ':', $i)) { + break; + } + + if (!isset($mapping[$i + 1]) || !in_array($mapping[$i + 1], array(' ', '[', ']', '{', '}'), true)) { + @trigger_error('Using a colon that is not followed by an indication character (i.e. " ", ",", "[", "]", "{", "}" is deprecated since version 3.2 and will throw a ParseException in 4.0.', E_USER_DEPRECATED); + } // value $done = false; @@ -380,23 +474,27 @@ class Inline switch ($mapping[$i]) { case '[': // nested sequence - $value = self::parseSequence($mapping, $i, $references); + $value = self::parseSequence($mapping, $flags, $i, $references); // Spec: Keys MUST be unique; first one wins. // Parser cannot abort this mapping earlier, since lines // are processed sequentially. if (!isset($output[$key])) { $output[$key] = $value; + } else { + @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, self::$parsedLineNumber + 1), E_USER_DEPRECATED); } $done = true; break; case '{': // nested mapping - $value = self::parseMapping($mapping, $i, $references); + $value = self::parseMapping($mapping, $flags, $i, $references); // Spec: Keys MUST be unique; first one wins. // Parser cannot abort this mapping earlier, since lines // are processed sequentially. if (!isset($output[$key])) { $output[$key] = $value; + } else { + @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, self::$parsedLineNumber + 1), E_USER_DEPRECATED); } $done = true; break; @@ -404,12 +502,14 @@ class Inline case ' ': break; default: - $value = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i, true, $references); + $value = self::parseScalar($mapping, $flags, array(',', '}'), array('"', "'"), $i, true, $references); // Spec: Keys MUST be unique; first one wins. // Parser cannot abort this mapping earlier, since lines // are processed sequentially. if (!isset($output[$key])) { $output[$key] = $value; + } else { + @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, self::$parsedLineNumber + 1), E_USER_DEPRECATED); } $done = true; --$i; @@ -423,20 +523,21 @@ class Inline } } - throw new ParseException(sprintf('Malformed inline YAML string %s', $mapping)); + throw new ParseException(sprintf('Malformed inline YAML string: %s.', $mapping)); } /** * Evaluates scalars and replaces magic values. * * @param string $scalar + * @param int $flags * @param array $references * * @return string A YAML string * * @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved */ - private static function evaluateScalar($scalar, $references = array()) + private static function evaluateScalar($scalar, $flags, $references = array()) { $scalar = trim($scalar); $scalarLower = strtolower($scalar); @@ -475,7 +576,7 @@ class Inline case 0 === strpos($scalar, '!str'): return (string) substr($scalar, 5); case 0 === strpos($scalar, '! '): - return (int) self::parseScalar(substr($scalar, 2)); + return (int) self::parseScalar(substr($scalar, 2), $flags); case 0 === strpos($scalar, '!php/object:'): if (self::$objectSupport) { return unserialize(substr($scalar, 12)); @@ -488,6 +589,8 @@ class Inline return; case 0 === strpos($scalar, '!!php/object:'): if (self::$objectSupport) { + @trigger_error('The !!php/object tag to indicate dumped PHP objects is deprecated since version 3.1 and will be removed in 4.0. Use the !php/object tag instead.', E_USER_DEPRECATED); + return unserialize(substr($scalar, 13)); } @@ -495,9 +598,25 @@ class Inline throw new ParseException('Object support when parsing a YAML file has been disabled.'); } + return; + case 0 === strpos($scalar, '!php/const:'): + if (self::$constantSupport) { + if (defined($const = substr($scalar, 11))) { + return constant($const); + } + + throw new ParseException(sprintf('The constant "%s" is not defined.', $const)); + } + if (self::$exceptionOnInvalidType) { + throw new ParseException(sprintf('The string "%s" could not be parsed as a constant. Have you forgotten to pass the "Yaml::PARSE_CONSTANT" flag to the parser?', $scalar)); + } + return; case 0 === strpos($scalar, '!!float '): return (float) substr($scalar, 8); + case preg_match('{^[+-]?[0-9][0-9_]*$}', $scalar): + $scalar = str_replace('_', '', (string) $scalar); + // omitting the break / return as integers are handled in the next case case ctype_digit($scalar): $raw = $scalar; $cast = (int) $scalar; @@ -510,15 +629,29 @@ class Inline return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw === (string) $cast) ? $cast : $raw); case is_numeric($scalar): case preg_match(self::getHexRegex(), $scalar): + $scalar = str_replace('_', '', $scalar); + return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar; case '.inf' === $scalarLower: case '.nan' === $scalarLower: return -log(0); case '-.inf' === $scalarLower: return log(0); - case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar): - return (float) str_replace(',', '', $scalar); + case 0 === strpos($scalar, '!!binary '): + return self::evaluateBinaryScalar(substr($scalar, 9)); + case preg_match('/^(-|\+)?[0-9][0-9,]*(\.[0-9_]+)?$/', $scalar): + case preg_match('/^(-|\+)?[0-9][0-9_]*(\.[0-9_]+)?$/', $scalar): + if (false !== strpos($scalar, ',')) { + @trigger_error('Using the comma as a group separator for floats is deprecated since version 3.2 and will be removed in 4.0.', E_USER_DEPRECATED); + } + + return (float) str_replace(array(',', '_'), '', $scalar); case preg_match(self::getTimestampRegex(), $scalar): + if (Yaml::PARSE_DATETIME & $flags) { + // When no timezone is provided in the parsed date, YAML spec says we must assume UTC. + return new \DateTime($scalar, new \DateTimeZone('UTC')); + } + $timeZone = date_default_timezone_get(); date_default_timezone_set('UTC'); $time = strtotime($scalar); @@ -531,6 +664,33 @@ class Inline } } + /** + * @param string $scalar + * + * @return string + * + * @internal + */ + public static function evaluateBinaryScalar($scalar) + { + $parsedBinaryData = self::parseScalar(preg_replace('/\s/', '', $scalar)); + + if (0 !== (strlen($parsedBinaryData) % 4)) { + throw new ParseException(sprintf('The normalized base64 encoded data (data without whitespace characters) length must be a multiple of four (%d bytes given).', strlen($parsedBinaryData))); + } + + if (!preg_match('#^[A-Z0-9+/]+={0,2}$#i', $parsedBinaryData)) { + throw new ParseException(sprintf('The base64 encoded data (%s) contains invalid characters.', $parsedBinaryData)); + } + + return base64_decode($parsedBinaryData, true); + } + + private static function isBinaryString($value) + { + return !preg_match('//u', $value) || preg_match('/[^\x09-\x0d\x20-\xff]/', $value); + } + /** * Gets a regex that matches a YAML date. * @@ -563,6 +723,6 @@ EOF; */ private static function getHexRegex() { - return '~^0x[0-9a-f]++$~i'; + return '~^0x[0-9a-f_]++$~i'; } } diff --git a/vendor/symfony/yaml/Parser.php b/vendor/symfony/yaml/Parser.php index 28b58c3..cb886ad 100644 --- a/vendor/symfony/yaml/Parser.php +++ b/vendor/symfony/yaml/Parser.php @@ -20,38 +20,70 @@ use Symfony\Component\Yaml\Exception\ParseException; */ class Parser { + const TAG_PATTERN = '((?P![\w!.\/:-]+) +)?'; const BLOCK_SCALAR_HEADER_PATTERN = '(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?'; private $offset = 0; + private $totalNumberOfLines; private $lines = array(); private $currentLineNb = -1; private $currentLine = ''; private $refs = array(); + private $skippedLineNumbers = array(); + private $locallySkippedLineNumbers = array(); /** * Constructor. * - * @param int $offset The offset of YAML document (used for line numbers in error messages) + * @param int $offset The offset of YAML document (used for line numbers in error messages) + * @param int|null $totalNumberOfLines The overall number of lines being parsed + * @param int[] $skippedLineNumbers Number of comment lines that have been skipped by the parser */ - public function __construct($offset = 0) + public function __construct($offset = 0, $totalNumberOfLines = null, array $skippedLineNumbers = array()) { $this->offset = $offset; + $this->totalNumberOfLines = $totalNumberOfLines; + $this->skippedLineNumbers = $skippedLineNumbers; } /** * Parses a YAML string to a PHP value. * - * @param string $value A YAML string - * @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise - * @param bool $objectSupport true if object support is enabled, false otherwise - * @param bool $objectForMap true if maps should return a stdClass instead of array() + * @param string $value A YAML string + * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior * * @return mixed A PHP value * * @throws ParseException If the YAML is not valid */ - public function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false) + public function parse($value, $flags = 0) { + if (is_bool($flags)) { + @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED); + + if ($flags) { + $flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE; + } else { + $flags = 0; + } + } + + if (func_num_args() >= 3) { + @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED); + + if (func_get_arg(2)) { + $flags |= Yaml::PARSE_OBJECT; + } + } + + if (func_num_args() >= 4) { + @trigger_error('Passing a boolean flag to toggle object for map support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED); + + if (func_get_arg(3)) { + $flags |= Yaml::PARSE_OBJECT_FOR_MAP; + } + } + if (!preg_match('//u', $value)) { throw new ParseException('The YAML value does not appear to be valid UTF-8.'); } @@ -60,6 +92,10 @@ class Parser $value = $this->cleanup($value); $this->lines = explode("\n", $value); + if (null === $this->totalNumberOfLines) { + $this->totalNumberOfLines = count($this->lines); + } + if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) { $mbEncoding = mb_internal_encoding(); mb_internal_encoding('UTF-8'); @@ -81,7 +117,7 @@ class Parser $isRef = $mergeNode = false; if (preg_match('#^\-((?P\s+)(?P.+?))?\s*$#u', $this->currentLine, $values)) { if ($context && 'mapping' == $context) { - throw new ParseException('You cannot define a sequence item when in a mapping'); + throw new ParseException('You cannot define a sequence item when in a mapping', $this->getRealCurrentLineNb() + 1, $this->currentLine); } $context = 'sequence'; @@ -92,27 +128,20 @@ class Parser // array if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { - $c = $this->getRealCurrentLineNb() + 1; - $parser = new self($c); - $parser->refs = &$this->refs; - $data[] = $parser->parse($this->getNextEmbedBlock(null, true), $exceptionOnInvalidType, $objectSupport, $objectForMap); + $data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags); } else { if (isset($values['leadspaces']) && preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P.+?))?\s*$#u', $values['value'], $matches) ) { // this is a compact notation element, add to next block and parse - $c = $this->getRealCurrentLineNb(); - $parser = new self($c); - $parser->refs = &$this->refs; - $block = $values['value']; if ($this->isNextLineIndented()) { $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + strlen($values['leadspaces']) + 1); } - $data[] = $parser->parse($block, $exceptionOnInvalidType, $objectSupport, $objectForMap); + $data[] = $this->parseBlock($this->getRealCurrentLineNb(), $block, $flags); } else { - $data[] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap, $context); + $data[] = $this->parseValue($values['value'], $flags, $context); } } if ($isRef) { @@ -120,13 +149,14 @@ class Parser } } elseif (preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P.+?))?\s*$#u', $this->currentLine, $values) && (false === strpos($values['key'], ' #') || in_array($values['key'][0], array('"', "'")))) { if ($context && 'sequence' == $context) { - throw new ParseException('You cannot define a mapping item when in a sequence'); + throw new ParseException('You cannot define a mapping item when in a sequence', $this->currentLineNb + 1, $this->currentLine); } $context = 'mapping'; // force correct settings - Inline::parse(null, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs); + Inline::parse(null, $flags, $this->refs); try { + Inline::$parsedLineNumber = $this->getRealCurrentLineNb(); $key = Inline::parseScalar($values['key']); } catch (ParseException $e) { $e->setParsedLine($this->getRealCurrentLineNb() + 1); @@ -166,10 +196,7 @@ class Parser } else { $value = $this->getNextEmbedBlock(); } - $c = $this->getRealCurrentLineNb() + 1; - $parser = new self($c); - $parser->refs = &$this->refs; - $parsed = $parser->parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap); + $parsed = $this->parseBlock($this->getRealCurrentLineNb() + 1, $value, $flags); if (!is_array($parsed)) { throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine); @@ -215,24 +242,29 @@ class Parser // But overwriting is allowed when a merge node is used in current block. if ($allowOverwrite || !isset($data[$key])) { $data[$key] = null; + } else { + @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED); } } else { - $c = $this->getRealCurrentLineNb() + 1; - $parser = new self($c); - $parser->refs = &$this->refs; - $value = $parser->parse($this->getNextEmbedBlock(), $exceptionOnInvalidType, $objectSupport, $objectForMap); + // remember the parsed line number here in case we need it to provide some contexts in error messages below + $realCurrentLineNbKey = $this->getRealCurrentLineNb(); + $value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $flags); // Spec: Keys MUST be unique; first one wins. // But overwriting is allowed when a merge node is used in current block. if ($allowOverwrite || !isset($data[$key])) { $data[$key] = $value; + } else { + @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, $realCurrentLineNbKey + 1), E_USER_DEPRECATED); } } } else { - $value = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap, $context); + $value = $this->parseValue($values['value'], $flags, $context); // Spec: Keys MUST be unique; first one wins. // But overwriting is allowed when a merge node is used in current block. if ($allowOverwrite || !isset($data[$key])) { $data[$key] = $value; + } else { + @trigger_error(sprintf('Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since version 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key, $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED); } } if ($isRef) { @@ -241,13 +273,14 @@ class Parser } else { // multiple documents are not supported if ('---' === $this->currentLine) { - throw new ParseException('Multiple documents are not supported.'); + throw new ParseException('Multiple documents are not supported.', $this->currentLineNb + 1, $this->currentLine); } // 1-liner optionally followed by newline(s) if (is_string($value) && $this->lines[0] === trim($value)) { try { - $value = Inline::parse($this->lines[0], $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs); + Inline::$parsedLineNumber = $this->getRealCurrentLineNb(); + $value = Inline::parse($this->lines[0], $flags, $this->refs); } catch (ParseException $e) { $e->setParsedLine($this->getRealCurrentLineNb() + 1); $e->setSnippet($this->currentLine); @@ -255,17 +288,6 @@ class Parser throw $e; } - if (is_array($value)) { - $first = reset($value); - if (is_string($first) && 0 === strpos($first, '*')) { - $data = array(); - foreach ($value as $alias) { - $data[] = $this->refs[substr($alias, 1)]; - } - $value = $data; - } - } - if (isset($mbEncoding)) { mb_internal_encoding($mbEncoding); } @@ -301,7 +323,7 @@ class Parser mb_internal_encoding($mbEncoding); } - if ($objectForMap && !is_object($data) && 'mapping' === $context) { + if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && !is_object($data) && 'mapping' === $context) { $object = new \stdClass(); foreach ($data as $key => $value) { @@ -314,6 +336,24 @@ class Parser return empty($data) ? null : $data; } + private function parseBlock($offset, $yaml, $flags) + { + $skippedLineNumbers = $this->skippedLineNumbers; + + foreach ($this->locallySkippedLineNumbers as $lineNumber) { + if ($lineNumber < $offset) { + continue; + } + + $skippedLineNumbers[] = $lineNumber; + } + + $parser = new self($offset, $this->totalNumberOfLines, $skippedLineNumbers); + $parser->refs = &$this->refs; + + return $parser->parse($yaml, $flags); + } + /** * Returns the current line number (takes the offset into account). * @@ -321,7 +361,17 @@ class Parser */ private function getRealCurrentLineNb() { - return $this->currentLineNb + $this->offset; + $realCurrentLineNumber = $this->currentLineNb + $this->offset; + + foreach ($this->skippedLineNumbers as $skippedLineNumber) { + if ($skippedLineNumber > $realCurrentLineNumber) { + break; + } + + ++$realCurrentLineNumber; + } + + return $realCurrentLineNumber; } /** @@ -424,6 +474,14 @@ class Parser // we ignore "comment" lines only when we are not inside a scalar block if (empty($blockScalarIndentations) && $this->isCurrentLineComment()) { + // remember ignored comment lines (they are used later in nested + // parser calls to determine real line numbers) + // + // CAUTION: beware to not populate the global property here as it + // will otherwise influence the getRealCurrentLineNb() call here + // for consecutive comment lines and subsequent embedded blocks + $this->locallySkippedLineNumbers[] = $this->getRealCurrentLineNb(); + continue; } @@ -459,26 +517,32 @@ class Parser /** * Moves the parser to the previous line. + * + * @return bool */ private function moveToPreviousLine() { + if ($this->currentLineNb < 1) { + return false; + } + $this->currentLine = $this->lines[--$this->currentLineNb]; + + return true; } /** * Parses a YAML value. * - * @param string $value A YAML value - * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise - * @param bool $objectSupport True if object support is enabled, false otherwise - * @param bool $objectForMap true if maps should return a stdClass instead of array() - * @param string $context The parser context (either sequence or mapping) + * @param string $value A YAML value + * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior + * @param string $context The parser context (either sequence or mapping) * * @return mixed A PHP value * * @throws ParseException When reference does not exist */ - private function parseValue($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $context) + private function parseValue($value, $flags, $context) { if (0 === strpos($value, '*')) { if (false !== $pos = strpos($value, '#')) { @@ -488,22 +552,52 @@ class Parser } if (!array_key_exists($value, $this->refs)) { - throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLine); + throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine); } return $this->refs[$value]; } - if (preg_match('/^'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) { + if (preg_match('/^'.self::TAG_PATTERN.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) { $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; - return $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers)); + $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers)); + + if (isset($matches['tag']) && '!!binary' === $matches['tag']) { + return Inline::evaluateBinaryScalar($data); + } + + return $data; } try { - $parsedValue = Inline::parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs); + $quotation = '' !== $value && ('"' === $value[0] || "'" === $value[0]) ? $value[0] : null; - if ('mapping' === $context && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) { + // do not take following lines into account when the current line is a quoted single line value + if (null !== $quotation && preg_match('/^'.$quotation.'.*'.$quotation.'(\s*#.*)?$/', $value)) { + return Inline::parse($value, $flags, $this->refs); + } + + while ($this->moveToNextLine()) { + // unquoted strings end before the first unindented line + if (null === $quotation && $this->getCurrentLineIndentation() === 0) { + $this->moveToPreviousLine(); + + break; + } + + $value .= ' '.trim($this->currentLine); + + // quoted string values end with a line that is terminated with the quotation character + if ('' !== $this->currentLine && substr($this->currentLine, -1) === $quotation) { + break; + } + } + + Inline::$parsedLineNumber = $this->getRealCurrentLineNb(); + $parsedValue = Inline::parse($value, $flags, $this->refs); + + if ('mapping' === $context && is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) { throw new ParseException('A colon cannot be used in an unquoted mapping value.'); } @@ -580,6 +674,8 @@ class Parser if ($notEOF) { $blockLines[] = ''; $this->moveToPreviousLine(); + } elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) { + $blockLines[] = ''; } // folded style @@ -686,6 +782,11 @@ class Parser return '' !== $ltrimmedLine && $ltrimmedLine[0] === '#'; } + private function isCurrentLineLastLineInDocument() + { + return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1); + } + /** * Cleanups a YAML string to be parsed. * @@ -763,7 +864,7 @@ class Parser */ private function isStringUnIndentedCollectionItem() { - return 0 === strpos($this->currentLine, '- '); + return '-' === rtrim($this->currentLine) || 0 === strpos($this->currentLine, '- '); } /** diff --git a/vendor/symfony/yaml/Tests/Command/LintCommandTest.php b/vendor/symfony/yaml/Tests/Command/LintCommandTest.php new file mode 100644 index 0000000..708eec5 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Command/LintCommandTest.php @@ -0,0 +1,106 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml\Tests\Command; + +use Symfony\Component\Yaml\Command\LintCommand; +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Tester\CommandTester; + +/** + * Tests the YamlLintCommand. + * + * @author Robin Chalas + */ +class LintCommandTest extends \PHPUnit_Framework_TestCase +{ + private $files; + + public function testLintCorrectFile() + { + $tester = $this->createCommandTester(); + $filename = $this->createFile('foo: bar'); + + $ret = $tester->execute(array('filename' => $filename), array('verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'decorated' => false)); + + $this->assertEquals(0, $ret, 'Returns 0 in case of success'); + $this->assertRegExp('/^\/\/ OK in /', trim($tester->getDisplay())); + } + + public function testLintIncorrectFile() + { + $incorrectContent = ' +foo: +bar'; + $tester = $this->createCommandTester(); + $filename = $this->createFile($incorrectContent); + + $ret = $tester->execute(array('filename' => $filename), array('decorated' => false)); + + $this->assertEquals(1, $ret, 'Returns 1 in case of error'); + $this->assertContains('Unable to parse at line 3 (near "bar").', trim($tester->getDisplay())); + } + + /** + * @expectedException \RuntimeException + */ + public function testLintFileNotReadable() + { + $tester = $this->createCommandTester(); + $filename = $this->createFile(''); + unlink($filename); + + $ret = $tester->execute(array('filename' => $filename), array('decorated' => false)); + } + + /** + * @return string Path to the new file + */ + private function createFile($content) + { + $filename = tempnam(sys_get_temp_dir().'/framework-yml-lint-test', 'sf-'); + file_put_contents($filename, $content); + + $this->files[] = $filename; + + return $filename; + } + + /** + * @return CommandTester + */ + protected function createCommandTester() + { + $application = new Application(); + $application->add(new LintCommand()); + $command = $application->find('lint:yaml'); + + return new CommandTester($command); + } + + protected function setUp() + { + $this->files = array(); + @mkdir(sys_get_temp_dir().'/framework-yml-lint-test'); + } + + protected function tearDown() + { + foreach ($this->files as $file) { + if (file_exists($file)) { + unlink($file); + } + } + + rmdir(sys_get_temp_dir().'/framework-yml-lint-test'); + } +} diff --git a/vendor/symfony/yaml/Tests/DumperTest.php b/vendor/symfony/yaml/Tests/DumperTest.php index 84069d8..06e9d3f 100644 --- a/vendor/symfony/yaml/Tests/DumperTest.php +++ b/vendor/symfony/yaml/Tests/DumperTest.php @@ -13,6 +13,7 @@ namespace Symfony\Component\Yaml\Tests; use Symfony\Component\Yaml\Parser; use Symfony\Component\Yaml\Dumper; +use Symfony\Component\Yaml\Yaml; class DumperTest extends \PHPUnit_Framework_TestCase { @@ -50,6 +51,34 @@ class DumperTest extends \PHPUnit_Framework_TestCase $this->array = null; } + public function testIndentationInConstructor() + { + $dumper = new Dumper(7); + $expected = <<<'EOF' +'': bar +foo: '#bar' +'foo''bar': { } +bar: + - 1 + - foo +foobar: + foo: bar + bar: + - 1 + - foo + foobar: + foo: bar + bar: + - 1 + - foo + +EOF; + $this->assertEquals($expected, $dumper->dump($this->array, 4, 0)); + } + + /** + * @group legacy + */ public function testSetIndentation() { $this->dumper->setIndentation(7); @@ -177,6 +206,16 @@ EOF; } public function testObjectSupportEnabled() + { + $dump = $this->dumper->dump(array('foo' => new A(), 'bar' => 1), 0, 0, Yaml::DUMP_OBJECT); + + $this->assertEquals('{ foo: !php/object:O:30:"Symfony\Component\Yaml\Tests\A":1:{s:1:"a";s:3:"foo";}, bar: 1 }', $dump, '->dump() is able to dump objects'); + } + + /** + * @group legacy + */ + public function testObjectSupportEnabledPassingTrue() { $dump = $this->dumper->dump(array('foo' => new A(), 'bar' => 1), 0, 0, false, true); @@ -195,7 +234,16 @@ EOF; */ public function testObjectSupportDisabledWithExceptions() { - $this->dumper->dump(array('foo' => new A(), 'bar' => 1), 0, 0, true, false); + $this->dumper->dump(array('foo' => new A(), 'bar' => 1), 0, 0, Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE); + } + + /** + * @group legacy + * @expectedException \Symfony\Component\Yaml\Exception\DumpException + */ + public function testObjectSupportDisabledWithExceptionsPassingTrue() + { + $this->dumper->dump(array('foo' => new A(), 'bar' => 1), 0, 0, true); } /** @@ -229,13 +277,81 @@ EOF; ); } + public function testBinaryDataIsDumpedBase64Encoded() + { + $binaryData = file_get_contents(__DIR__.'/Fixtures/arrow.gif'); + $expected = '{ data: !!binary '.base64_encode($binaryData).' }'; + + $this->assertSame($expected, $this->dumper->dump(array('data' => $binaryData))); + } + + public function testNonUtf8DataIsDumpedBase64Encoded() + { + // "für" (ISO-8859-1 encoded) + $this->assertSame('!!binary ZsM/cg==', $this->dumper->dump("f\xc3\x3fr")); + } + + /** + * @dataProvider objectAsMapProvider + */ + public function testDumpObjectAsMap($object, $expected) + { + $yaml = $this->dumper->dump($object, 0, 0, Yaml::DUMP_OBJECT_AS_MAP); + + $this->assertEquals($expected, Yaml::parse($yaml, Yaml::PARSE_OBJECT_FOR_MAP)); + } + + public function objectAsMapProvider() + { + $tests = array(); + + $bar = new \stdClass(); + $bar->class = 'classBar'; + $bar->args = array('bar'); + $zar = new \stdClass(); + $foo = new \stdClass(); + $foo->bar = $bar; + $foo->zar = $zar; + $object = new \stdClass(); + $object->foo = $foo; + $tests['stdClass'] = array($object, $object); + + $arrayObject = new \ArrayObject(); + $arrayObject['foo'] = 'bar'; + $arrayObject['baz'] = 'foobar'; + $parsedArrayObject = new \stdClass(); + $parsedArrayObject->foo = 'bar'; + $parsedArrayObject->baz = 'foobar'; + $tests['ArrayObject'] = array($arrayObject, $parsedArrayObject); + + $a = new A(); + $tests['arbitrary-object'] = array($a, null); + + return $tests; + } + + public function testDumpMultiLineStringAsScalarBlock() + { + $data = array( + 'data' => array( + 'single_line' => 'foo bar baz', + 'multi_line' => "foo\nline with trailing spaces:\n \nbar\r\ninteger like line:\n123456789\nempty line:\n\nbaz", + 'nested_inlined_multi_line_string' => array( + 'inlined_multi_line' => "foo\nbar\r\nempty line:\n\nbaz", + ), + ), + ); + + $this->assertSame(file_get_contents(__DIR__.'/Fixtures/multiple_lines_as_literal_block.yml'), $this->dumper->dump($data, 2, 0, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK)); + } + /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The indentation must be greater than zero */ public function testZeroIndentationThrowsException() { - $this->dumper->setIndentation(0); + new Dumper(0); } /** @@ -244,7 +360,7 @@ EOF; */ public function testNegativeIndentationThrowsException() { - $this->dumper->setIndentation(-4); + new Dumper(-4); } } diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsSpecificationExamples.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsSpecificationExamples.yml index ec1c4c3..ac0c69d 100644 --- a/vendor/symfony/yaml/Tests/Fixtures/YtsSpecificationExamples.yml +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsSpecificationExamples.yml @@ -509,24 +509,31 @@ test: Integers spec: 2.19 yaml: | canonical: 12345 - decimal: +12,345 octal: 014 hexadecimal: 0xC php: | array( 'canonical' => 12345, - 'decimal' => 12345.0, 'octal' => 014, 'hexadecimal' => 0xC ) --- +test: Decimal Integer +deprecated: true +spec: 2.19 +yaml: | + decimal: +12,345 +php: | + array( + 'decimal' => 12345.0, + ) +--- # FIX: spec shows parens around -inf and NaN test: Floating point spec: 2.20 yaml: | canonical: 1.23015e+3 exponential: 12.3015e+02 - fixed: 1,230.15 negative infinity: -.inf not a number: .NaN float as whole number: !!float 1 @@ -534,12 +541,21 @@ php: | array( 'canonical' => 1230.15, 'exponential' => 1230.15, - 'fixed' => 1230.15, 'negative infinity' => log(0), 'not a number' => -log(0), 'float as whole number' => (float) 1 ) --- +test: Fixed Floating point +deprecated: true +spec: 2.20 +yaml: | + fixed: 1,230.15 +php: | + array( + 'fixed' => 1230.15, + ) +--- test: Miscellaneous spec: 2.21 yaml: | @@ -1532,29 +1548,43 @@ php: | test: Integer yaml: | canonical: 12345 - decimal: +12,345 octal: 014 hexadecimal: 0xC php: | array( 'canonical' => 12345, - 'decimal' => 12345.0, 'octal' => 12, 'hexadecimal' => 12 ) --- +test: Decimal +deprecated: true +yaml: | + decimal: +12,345 +php: | + array( + 'decimal' => 12345.0, + ) +--- +test: Fixed Float +deprecated: true +yaml: | + fixed: 1,230.15 +php: | + array( + 'fixed' => 1230.15, + ) +--- test: Float yaml: | canonical: 1.23015e+3 exponential: 12.3015e+02 - fixed: 1,230.15 negative infinity: -.inf not a number: .NaN php: | array( 'canonical' => 1230.15, 'exponential' => 1230.15, - 'fixed' => 1230.15, 'negative infinity' => log(0), 'not a number' => -log(0) ) diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsTypeTransfers.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsTypeTransfers.yml index 46c8d4a..8fefa49 100644 --- a/vendor/symfony/yaml/Tests/Fixtures/YtsTypeTransfers.yml +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsTypeTransfers.yml @@ -176,13 +176,37 @@ brief: > yaml: | zero: 0 simple: 12 - one-thousand: 1,000 - negative one-thousand: -1,000 php: | array( 'zero' => 0, 'simple' => 12, + ) +--- +test: Positive Big Integer +deprecated: true +dump_skip: true +brief: > + An integer is a series of numbers, optionally + starting with a positive or negative sign. Integers + may also contain commas for readability. +yaml: | + one-thousand: 1,000 +php: | + array( 'one-thousand' => 1000.0, + ) +--- +test: Negative Big Integer +deprecated: true +dump_skip: true +brief: > + An integer is a series of numbers, optionally + starting with a positive or negative sign. Integers + may also contain commas for readability. +yaml: | + negative one-thousand: -1,000 +php: | + array( 'negative one-thousand' => -1000.0 ) --- @@ -208,15 +232,27 @@ brief: > positive and negative infinity and "not a number." yaml: | a simple float: 2.00 - larger float: 1,000.09 scientific notation: 1.00009e+3 php: | array( 'a simple float' => 2.0, - 'larger float' => 1000.09, 'scientific notation' => 1000.09 ) --- +test: Larger Float +dump_skip: true +deprecated: true +brief: > + Floats are represented by numbers with decimals, + allowing for scientific notation, as well as + positive and negative infinity and "not a number." +yaml: | + larger float: 1,000.09 +php: | + array( + 'larger float' => 1000.09, + ) +--- test: Time todo: true brief: > diff --git a/vendor/symfony/yaml/Tests/Fixtures/arrow.gif b/vendor/symfony/yaml/Tests/Fixtures/arrow.gif new file mode 100644 index 0000000..443aca4 Binary files /dev/null and b/vendor/symfony/yaml/Tests/Fixtures/arrow.gif differ diff --git a/vendor/symfony/yaml/Tests/Fixtures/multiple_lines_as_literal_block.yml b/vendor/symfony/yaml/Tests/Fixtures/multiple_lines_as_literal_block.yml new file mode 100644 index 0000000..b4903d3 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/multiple_lines_as_literal_block.yml @@ -0,0 +1,13 @@ +data: + single_line: 'foo bar baz' + multi_line: | + foo + line with trailing spaces: + + bar + integer like line: + 123456789 + empty line: + + baz + nested_inlined_multi_line_string: { inlined_multi_line: "foo\nbar\r\nempty line:\n\nbaz" } diff --git a/vendor/symfony/yaml/Tests/Fixtures/sfMergeKey.yml b/vendor/symfony/yaml/Tests/Fixtures/sfMergeKey.yml index 4b67d34..8d2b4d3 100644 --- a/vendor/symfony/yaml/Tests/Fixtures/sfMergeKey.yml +++ b/vendor/symfony/yaml/Tests/Fixtures/sfMergeKey.yml @@ -18,11 +18,7 @@ yaml: | x: Oren c: foo: bar - foo: ignore bar: foo - duplicate: - foo: bar - foo: ignore foo2: &foo2 a: Ballmer ding: &dong [ fi, fei, fo, fam] @@ -48,7 +44,6 @@ php: | array( 'foo' => array('a' => 'Steve', 'b' => 'Clark', 'c' => 'Brian'), 'bar' => array('a' => 'before', 'd' => 'other', 'b' => 'new', 'c' => array('foo' => 'bar', 'bar' => 'foo'), 'x' => 'Oren'), - 'duplicate' => array('foo' => 'bar'), 'foo2' => array('a' => 'Ballmer'), 'ding' => array('fi', 'fei', 'fo', 'fam'), 'check' => array('a' => 'Steve', 'b' => 'Clark', 'c' => 'Brian', 'fi', 'fei', 'fo', 'fam', 'isit' => 'tested'), diff --git a/vendor/symfony/yaml/Tests/InlineTest.php b/vendor/symfony/yaml/Tests/InlineTest.php index 3da5dd5..355deb4 100644 --- a/vendor/symfony/yaml/Tests/InlineTest.php +++ b/vendor/symfony/yaml/Tests/InlineTest.php @@ -12,6 +12,7 @@ namespace Symfony\Component\Yaml\Tests; use Symfony\Component\Yaml\Inline; +use Symfony\Component\Yaml\Yaml; class InlineTest extends \PHPUnit_Framework_TestCase { @@ -27,6 +28,55 @@ class InlineTest extends \PHPUnit_Framework_TestCase * @dataProvider getTestsForParseWithMapObjects */ public function testParseWithMapObjects($yaml, $value) + { + $actual = Inline::parse($yaml, Yaml::PARSE_OBJECT_FOR_MAP); + + $this->assertSame(serialize($value), serialize($actual)); + } + + /** + * @dataProvider getTestsForParsePhpConstants + */ + public function testParsePhpConstants($yaml, $value) + { + $actual = Inline::parse($yaml, Yaml::PARSE_CONSTANT); + + $this->assertSame($value, $actual); + } + + public function getTestsForParsePhpConstants() + { + return array( + array('!php/const:Symfony\Component\Yaml\Yaml::PARSE_CONSTANT', Yaml::PARSE_CONSTANT), + array('!php/const:PHP_INT_MAX', PHP_INT_MAX), + array('[!php/const:PHP_INT_MAX]', array(PHP_INT_MAX)), + array('{ foo: !php/const:PHP_INT_MAX }', array('foo' => PHP_INT_MAX)), + ); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessage The constant "WRONG_CONSTANT" is not defined + */ + public function testParsePhpConstantThrowsExceptionWhenUndefined() + { + Inline::parse('!php/const:WRONG_CONSTANT', Yaml::PARSE_CONSTANT); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessageRegExp #The string "!php/const:PHP_INT_MAX" could not be parsed as a constant.*# + */ + public function testParsePhpConstantThrowsExceptionOnInvalidType() + { + Inline::parse('!php/const:PHP_INT_MAX', Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE); + } + + /** + * @group legacy + * @dataProvider getTestsForParseWithMapObjects + */ + public function testParseWithMapObjectsPassingTrue($yaml, $value) { $actual = Inline::parse($yaml, false, false, true); @@ -114,6 +164,16 @@ class InlineTest extends \PHPUnit_Framework_TestCase Inline::parse($value); } + /** + * @group legacy + * @expectedDeprecation Using a colon that is not followed by an indication character (i.e. " ", ",", "[", "]", "{", "}" is deprecated since version 3.2 and will throw a ParseException in 4.0. + * throws \Symfony\Component\Yaml\Exception\ParseException in 4.0 + */ + public function testParseMappingKeyWithColonNotFollowedBySpace() + { + Inline::parse('{1:""}'); + } + /** * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ @@ -142,6 +202,15 @@ class InlineTest extends \PHPUnit_Framework_TestCase * @dataProvider getDataForParseReferences */ public function testParseReferences($yaml, $expected) + { + $this->assertSame($expected, Inline::parse($yaml, 0, array('var' => 'var-value'))); + } + + /** + * @group legacy + * @dataProvider getDataForParseReferences + */ + public function testParseReferencesAsFifthArgument($yaml, $expected) { $this->assertSame($expected, Inline::parse($yaml, false, false, false, array('var' => 'var-value'))); } @@ -161,6 +230,19 @@ class InlineTest extends \PHPUnit_Framework_TestCase } public function testParseMapReferenceInSequence() + { + $foo = array( + 'a' => 'Steve', + 'b' => 'Clark', + 'c' => 'Brian', + ); + $this->assertSame(array($foo), Inline::parse('[*foo]', 0, array('foo' => $foo))); + } + + /** + * @group legacy + */ + public function testParseMapReferenceInSequenceAsFifthArgument() { $foo = array( 'a' => 'Steve', @@ -190,7 +272,7 @@ class InlineTest extends \PHPUnit_Framework_TestCase /** * @dataProvider getReservedIndicators - * @expectedException Symfony\Component\Yaml\Exception\ParseException + * @expectedException \Symfony\Component\Yaml\Exception\ParseException * @expectedExceptionMessage cannot start a plain scalar; you need to quote the scalar. */ public function testParseUnquotedScalarStartingWithReservedIndicator($indicator) @@ -205,7 +287,7 @@ class InlineTest extends \PHPUnit_Framework_TestCase /** * @dataProvider getScalarIndicators - * @expectedException Symfony\Component\Yaml\Exception\ParseException + * @expectedException \Symfony\Component\Yaml\Exception\ParseException * @expectedExceptionMessage cannot start a plain scalar; you need to quote the scalar. */ public function testParseUnquotedScalarStartingWithScalarIndicator($indicator) @@ -218,6 +300,34 @@ class InlineTest extends \PHPUnit_Framework_TestCase return array(array('|'), array('>')); } + /** + * @group legacy + * @expectedDeprecation Not quoting the scalar "%bar " starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0. + * throws \Symfony\Component\Yaml\Exception\ParseException in 4.0 + */ + public function testParseUnquotedScalarStartingWithPercentCharacter() + { + Inline::parse('{ foo: %bar }'); + } + + /** + * @dataProvider getDataForIsHash + */ + public function testIsHash($array, $expected) + { + $this->assertSame($expected, Inline::isHash($array)); + } + + public function getDataForIsHash() + { + return array( + array(array(), false), + array(array(1, 2, 3), false), + array(array(2 => 1, 1 => 2, 0 => 3), true), + array(array('foo' => 1, 'bar' => 2), true), + ); + } + public function getTestsForParse() { return array( @@ -227,11 +337,17 @@ class InlineTest extends \PHPUnit_Framework_TestCase array('true', true), array('12', 12), array('-12', -12), + array('1_2', 12), + array('_12', '_12'), + array('12_', 12), array('"quoted string"', 'quoted string'), array("'quoted string'", 'quoted string'), array('12.30e+02', 12.30e+02), + array('123.45_67', 123.4567), array('0x4D2', 0x4D2), + array('0x_4_D_2_', 0x4D2), array('02333', 02333), + array('0_2_3_3_3', 02333), array('.Inf', -log(0)), array('-.Inf', log(0)), array("'686e444'", '686e444'), @@ -267,7 +383,7 @@ class InlineTest extends \PHPUnit_Framework_TestCase array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')), // mappings - array('{foo:bar,bar:foo,false:false,null:null,integer:12}', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)), + array('{foo: bar,bar: foo,false: false,null: null,integer: 12}', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)), array('{ foo : bar, bar : foo, false : false, null : null, integer : 12 }', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)), array('{foo: \'bar\', bar: \'foo: bar\'}', array('foo' => 'bar', 'bar' => 'foo: bar')), array('{\'foo\': \'bar\', "bar": \'foo: bar\'}', array('foo' => 'bar', 'bar' => 'foo: bar')), @@ -279,6 +395,8 @@ class InlineTest extends \PHPUnit_Framework_TestCase array('[foo, {bar: foo}]', array('foo', array('bar' => 'foo'))), array('{ foo: {bar: foo} }', array('foo' => array('bar' => 'foo'))), array('{ foo: [bar, foo] }', array('foo' => array('bar', 'foo'))), + array('{ foo:{bar: foo} }', array('foo' => array('bar' => 'foo'))), + array('{ foo:[bar, foo] }', array('foo' => array('bar', 'foo'))), array('[ foo, [ bar, foo ] ]', array('foo', array('bar', 'foo'))), @@ -334,7 +452,7 @@ class InlineTest extends \PHPUnit_Framework_TestCase array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')), // mappings - array('{foo:bar,bar:foo,false:false,null:null,integer:12}', (object) array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)), + array('{foo: bar,bar: foo,false: false,null: null,integer: 12}', (object) array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)), array('{ foo : bar, bar : foo, false : false, null : null, integer : 12 }', (object) array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)), array('{foo: \'bar\', bar: \'foo: bar\'}', (object) array('foo' => 'bar', 'bar' => 'foo: bar')), array('{\'foo\': \'bar\', "bar": \'foo: bar\'}', (object) array('foo' => 'bar', 'bar' => 'foo: bar')), @@ -379,10 +497,15 @@ class InlineTest extends \PHPUnit_Framework_TestCase array('false', false), array('true', true), array('12', 12), + array("'1_2'", '1_2'), + array('_12', '_12'), + array("'12_'", '12_'), array("'quoted string'", 'quoted string'), array('!!float 1230', 12.30e+02), array('1234', 0x4D2), array('1243', 02333), + array("'0x_4_D_2_'", '0x_4_D_2_'), + array("'0_2_3_3_3'", '0_2_3_3_3'), array('.Inf', -log(0)), array('-.Inf', log(0)), array("'686e444'", '686e444'), @@ -424,6 +547,133 @@ class InlineTest extends \PHPUnit_Framework_TestCase array('[foo, { bar: foo, foo: [foo, { bar: foo }] }, [foo, { bar: foo }]]', array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo')))), array('[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']', array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container')), + + array('{ foo: { bar: { 1: 2, baz: 3 } } }', array('foo' => array('bar' => array(1 => 2, 'baz' => 3)))), ); } + + /** + * @dataProvider getTimestampTests + */ + public function testParseTimestampAsUnixTimestampByDefault($yaml, $year, $month, $day, $hour, $minute, $second) + { + $this->assertSame(gmmktime($hour, $minute, $second, $month, $day, $year), Inline::parse($yaml)); + } + + /** + * @dataProvider getTimestampTests + */ + public function testParseTimestampAsDateTimeObject($yaml, $year, $month, $day, $hour, $minute, $second, $timezone) + { + $expected = new \DateTime($yaml); + $expected->setTimeZone(new \DateTimeZone('UTC')); + $expected->setDate($year, $month, $day); + + if (PHP_VERSION_ID >= 70100) { + $expected->setTime($hour, $minute, $second, 1000000 * ($second - (int) $second)); + } else { + $expected->setTime($hour, $minute, $second); + } + + $date = Inline::parse($yaml, Yaml::PARSE_DATETIME); + $this->assertEquals($expected, $date); + $this->assertSame($timezone, $date->format('O')); + } + + public function getTimestampTests() + { + return array( + 'canonical' => array('2001-12-15T02:59:43.1Z', 2001, 12, 15, 2, 59, 43.1, '+0000'), + 'ISO-8601' => array('2001-12-15t21:59:43.10-05:00', 2001, 12, 16, 2, 59, 43.1, '-0500'), + 'spaced' => array('2001-12-15 21:59:43.10 -5', 2001, 12, 16, 2, 59, 43.1, '-0500'), + 'date' => array('2001-12-15', 2001, 12, 15, 0, 0, 0, '+0000'), + ); + } + + /** + * @dataProvider getTimestampTests + */ + public function testParseNestedTimestampListAsDateTimeObject($yaml, $year, $month, $day, $hour, $minute, $second) + { + $expected = new \DateTime($yaml); + $expected->setTimeZone(new \DateTimeZone('UTC')); + $expected->setDate($year, $month, $day); + if (PHP_VERSION_ID >= 70100) { + $expected->setTime($hour, $minute, $second, 1000000 * ($second - (int) $second)); + } else { + $expected->setTime($hour, $minute, $second); + } + + $expectedNested = array('nested' => array($expected)); + $yamlNested = "{nested: [$yaml]}"; + + $this->assertEquals($expectedNested, Inline::parse($yamlNested, Yaml::PARSE_DATETIME)); + } + + /** + * @dataProvider getDateTimeDumpTests + */ + public function testDumpDateTime($dateTime, $expected) + { + $this->assertSame($expected, Inline::dump($dateTime)); + } + + public function getDateTimeDumpTests() + { + $tests = array(); + + $dateTime = new \DateTime('2001-12-15 21:59:43', new \DateTimeZone('UTC')); + $tests['date-time-utc'] = array($dateTime, '2001-12-15T21:59:43+00:00'); + + $dateTime = new \DateTimeImmutable('2001-07-15 21:59:43', new \DateTimeZone('Europe/Berlin')); + $tests['immutable-date-time-europe-berlin'] = array($dateTime, '2001-07-15T21:59:43+02:00'); + + return $tests; + } + + /** + * @dataProvider getBinaryData + */ + public function testParseBinaryData($data) + { + $this->assertSame('Hello world', Inline::parse($data)); + } + + public function getBinaryData() + { + return array( + 'enclosed with double quotes' => array('!!binary "SGVsbG8gd29ybGQ="'), + 'enclosed with single quotes' => array("!!binary 'SGVsbG8gd29ybGQ='"), + 'containing spaces' => array('!!binary "SGVs bG8gd 29ybGQ="'), + ); + } + + /** + * @dataProvider getInvalidBinaryData + */ + public function testParseInvalidBinaryData($data, $expectedMessage) + { + $this->setExpectedExceptionRegExp('\Symfony\Component\Yaml\Exception\ParseException', $expectedMessage); + + Inline::parse($data); + } + + public function getInvalidBinaryData() + { + return array( + 'length not a multiple of four' => array('!!binary "SGVsbG8d29ybGQ="', '/The normalized base64 encoded data \(data without whitespace characters\) length must be a multiple of four \(\d+ bytes given\)/'), + 'invalid characters' => array('!!binary "SGVsbG8#d29ybGQ="', '/The base64 encoded data \(.*\) contains invalid characters/'), + 'too many equals characters' => array('!!binary "SGVsbG8gd29yb==="', '/The base64 encoded data \(.*\) contains invalid characters/'), + 'misplaced equals character' => array('!!binary "SGVsbG8gd29ybG=Q"', '/The base64 encoded data \(.*\) contains invalid characters/'), + ); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessage Malformed inline YAML string: {this, is not, supported}. + */ + public function testNotSupportedMissingValue() + { + Inline::parse('{this, is not, supported}'); + } } diff --git a/vendor/symfony/yaml/Tests/ParserTest.php b/vendor/symfony/yaml/Tests/ParserTest.php index fc15c32..f2498d1 100644 --- a/vendor/symfony/yaml/Tests/ParserTest.php +++ b/vendor/symfony/yaml/Tests/ParserTest.php @@ -31,9 +31,30 @@ class ParserTest extends \PHPUnit_Framework_TestCase /** * @dataProvider getDataFormSpecifications */ - public function testSpecifications($file, $expected, $yaml, $comment) + public function testSpecifications($file, $expected, $yaml, $comment, $deprecated) { + $deprecations = array(); + + if ($deprecated) { + set_error_handler(function ($type, $msg) use (&$deprecations) { + if (E_USER_DEPRECATED !== $type) { + restore_error_handler(); + + return call_user_func_array('PHPUnit_Util_ErrorHandler::handleError', func_get_args()); + } + + $deprecations[] = $msg; + }); + } + $this->assertEquals($expected, var_export($this->parser->parse($yaml), true), $comment); + + if ($deprecated) { + restore_error_handler(); + + $this->assertCount(1, $deprecations); + $this->assertContains('Using the comma as a group separator for floats is deprecated since version 3.2 and will be removed in 4.0.', $deprecations[0]); + } } public function getDataFormSpecifications() @@ -58,7 +79,7 @@ class ParserTest extends \PHPUnit_Framework_TestCase } else { eval('$expected = '.trim($test['php']).';'); - $tests[] = array($file, var_export($expected, true), $test['yaml'], $test['test']); + $tests[] = array($file, var_export($expected, true), $test['yaml'], $test['test'], isset($test['deprecated']) ? $test['deprecated'] : false); } } } @@ -421,19 +442,37 @@ EOF; public function testObjectSupportEnabled() { - $input = <<assertEquals(array('foo' => new B(), 'bar' => 1), $this->parser->parse($input, false, true), '->parse() is able to parse objects'); + $this->assertEquals(array('foo' => new B(), 'bar' => 1), $this->parser->parse($input, Yaml::PARSE_OBJECT), '->parse() is able to parse objects'); + } - $input = <<assertEquals(array('foo' => new B(), 'bar' => 1), $this->parser->parse($input, false, true), '->parse() is able to parse objects'); } + /** + * @group legacy + */ + public function testObjectSupportEnabledWithDeprecatedTag() + { + $input = <<<'EOF' +foo: !!php/object:O:30:"Symfony\Component\Yaml\Tests\B":1:{s:1:"b";s:3:"foo";} +bar: 1 +EOF; + $this->assertEquals(array('foo' => new B(), 'bar' => 1), $this->parser->parse($input, Yaml::PARSE_OBJECT), '->parse() is able to parse objects'); + } + /** * @dataProvider invalidDumpedObjectProvider */ @@ -446,6 +485,15 @@ EOF; * @dataProvider getObjectForMapTests */ public function testObjectForMap($yaml, $expected) + { + $this->assertEquals($expected, $this->parser->parse($yaml, Yaml::PARSE_OBJECT_FOR_MAP)); + } + + /** + * @group legacy + * @dataProvider getObjectForMapTests + */ + public function testObjectForMapEnabledWithMappingUsingBooleanToggles($yaml, $expected) { $this->assertEquals($expected, $this->parser->parse($yaml, false, false, true)); } @@ -454,7 +502,7 @@ EOF; { $tests = array(); - $yaml = <<baz = 'foobar'; $tests['object-for-map-is-applied-after-parsing'] = array($yaml, $expected); - $yaml = <<array[1]->key = 'two'; $tests['nest-map-and-sequence'] = array($yaml, $expected); - $yaml = <<map->{2} = 'two'; $tests['numeric-keys'] = array($yaml, $expected); - $yaml = <<parser->parse($yaml, true, false); + $this->parser->parse($yaml, Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE); + } + + /** + * @group legacy + * @dataProvider invalidDumpedObjectProvider + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testObjectsSupportDisabledWithExceptionsUsingBooleanToggles($yaml) + { + $this->parser->parse($yaml, true); } public function invalidDumpedObjectProvider() { - $yamlTag = << array( + array( + 'b' => array( + array( + 'bar' => 'baz', + ), + ), + ), + 'foo', + ), + 'd' => 'e', + ); + + $this->assertSame($expected, $this->parser->parse($yaml)); + } + + public function testSequenceFollowedByCommentEmbeddedInMapping() + { + $yaml = <<<'EOT' +a: + b: + - c +# comment + d: e +EOT; + $expected = array( + 'a' => array( + 'b' => array('c'), + 'd' => 'e', + ), + ); + + $this->assertSame($expected, $this->parser->parse($yaml)); + } + /** * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ @@ -647,7 +752,7 @@ EOF */ public function testScalarInSequence() { - Yaml::parse(<<assertSame($expected, Yaml::parse($input)); } + /** + * @group legacy + */ public function testMappingDuplicateKeyFlow() { - $input = <<assertSame($expected, Yaml::parse($input)); } + /** + * @group legacy + * @dataProvider getParseExceptionOnDuplicateData + * @expectedDeprecation Duplicate key "%s" detected on line %d whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated %s. + * throws \Symfony\Component\Yaml\Exception\ParseException in 4.0 + */ + public function testParseExceptionOnDuplicate($input, $duplicateKey, $lineNumber) + { + Yaml::parse($input); + } + + public function getParseExceptionOnDuplicateData() + { + $tests = array(); + + $yaml = << @@ -1005,7 +1183,7 @@ EOT; $expected = array( 'foo' => array( 'bar' => array( - 'scalar-block' => 'line1 line2>', + 'scalar-block' => "line1 line2>\n", ), 'baz' => array( 'foobar' => null, @@ -1035,7 +1213,7 @@ EOT; public function testBlankLinesAreParsedAsNewLinesInFoldedBlocks() { - $yaml = <<

      A heading

      @@ -1047,7 +1225,7 @@ EOT; $this->assertSame( array( - 'test' => << <<<'EOT'

      A heading

      • a list
      • may be a good example
      EOT @@ -1059,7 +1237,7 @@ EOT public function testAdditionallyIndentedLinesAreParsedAsNewLinesInFoldedBlocks() { - $yaml = <<

      A heading

      @@ -1071,7 +1249,7 @@ EOT; $this->assertSame( array( - 'test' => << <<<'EOT'

      A heading

      • a list
      • @@ -1083,6 +1261,194 @@ EOT $this->parser->parse($yaml) ); } + + /** + * @dataProvider getBinaryData + */ + public function testParseBinaryData($data) + { + $this->assertSame(array('data' => 'Hello world'), $this->parser->parse($data)); + } + + public function getBinaryData() + { + return array( + 'enclosed with double quotes' => array('data: !!binary "SGVsbG8gd29ybGQ="'), + 'enclosed with single quotes' => array("data: !!binary 'SGVsbG8gd29ybGQ='"), + 'containing spaces' => array('data: !!binary "SGVs bG8gd 29ybGQ="'), + 'in block scalar' => array( + <<<'EOT' +data: !!binary | + SGVsbG8gd29ybGQ= +EOT + ), + 'containing spaces in block scalar' => array( + <<<'EOT' +data: !!binary | + SGVs bG8gd 29ybGQ= +EOT + ), + ); + } + + /** + * @dataProvider getInvalidBinaryData + */ + public function testParseInvalidBinaryData($data, $expectedMessage) + { + $this->setExpectedExceptionRegExp('\Symfony\Component\Yaml\Exception\ParseException', $expectedMessage); + + $this->parser->parse($data); + } + + public function getInvalidBinaryData() + { + return array( + 'length not a multiple of four' => array('data: !!binary "SGVsbG8d29ybGQ="', '/The normalized base64 encoded data \(data without whitespace characters\) length must be a multiple of four \(\d+ bytes given\)/'), + 'invalid characters' => array('!!binary "SGVsbG8#d29ybGQ="', '/The base64 encoded data \(.*\) contains invalid characters/'), + 'too many equals characters' => array('data: !!binary "SGVsbG8gd29yb==="', '/The base64 encoded data \(.*\) contains invalid characters/'), + 'misplaced equals character' => array('data: !!binary "SGVsbG8gd29ybG=Q"', '/The base64 encoded data \(.*\) contains invalid characters/'), + 'length not a multiple of four in block scalar' => array( + <<<'EOT' +data: !!binary | + SGVsbG8d29ybGQ= +EOT + , + '/The normalized base64 encoded data \(data without whitespace characters\) length must be a multiple of four \(\d+ bytes given\)/', + ), + 'invalid characters in block scalar' => array( + <<<'EOT' +data: !!binary | + SGVsbG8#d29ybGQ= +EOT + , + '/The base64 encoded data \(.*\) contains invalid characters/', + ), + 'too many equals characters in block scalar' => array( + <<<'EOT' +data: !!binary | + SGVsbG8gd29yb=== +EOT + , + '/The base64 encoded data \(.*\) contains invalid characters/', + ), + 'misplaced equals character in block scalar' => array( + <<<'EOT' +data: !!binary | + SGVsbG8gd29ybG=Q +EOT + , + '/The base64 encoded data \(.*\) contains invalid characters/', + ), + ); + } + + public function testParseDateAsMappingValue() + { + $yaml = <<<'EOT' +date: 2002-12-14 +EOT; + $expectedDate = new \DateTime(); + $expectedDate->setTimeZone(new \DateTimeZone('UTC')); + $expectedDate->setDate(2002, 12, 14); + $expectedDate->setTime(0, 0, 0); + + $this->assertEquals(array('date' => $expectedDate), $this->parser->parse($yaml, Yaml::PARSE_DATETIME)); + } + + /** + * @param $lineNumber + * @param $yaml + * @dataProvider parserThrowsExceptionWithCorrectLineNumberProvider + */ + public function testParserThrowsExceptionWithCorrectLineNumber($lineNumber, $yaml) + { + $this->setExpectedException( + '\Symfony\Component\Yaml\Exception\ParseException', + sprintf('Unexpected characters near "," at line %d (near "bar: "123",").', $lineNumber) + ); + + $this->parser->parse($yaml); + } + + public function parserThrowsExceptionWithCorrectLineNumberProvider() + { + return array( + array( + 4, + <<<'YAML' +foo: + - + # bar + bar: "123", +YAML + ), + array( + 5, + <<<'YAML' +foo: + - + # bar + # bar + bar: "123", +YAML + ), + array( + 8, + <<<'YAML' +foo: + - + # foobar + baz: 123 +bar: + - + # bar + bar: "123", +YAML + ), + array( + 10, + <<<'YAML' +foo: + - + # foobar + # foobar + baz: 123 +bar: + - + # bar + # bar + bar: "123", +YAML + ), + ); + } + + public function testParseMultiLineQuotedString() + { + $yaml = <<assertSame(array('foo' => 'bar baz foobar foo', 'bar' => 'baz'), $this->parser->parse($yaml)); + } + + public function testParseMultiLineUnquotedString() + { + $yaml = <<assertSame(array('foo' => 'bar baz foobar foo', 'bar' => 'baz'), $this->parser->parse($yaml)); + } } class B diff --git a/vendor/symfony/yaml/Unescaper.php b/vendor/symfony/yaml/Unescaper.php index 6e4f1d7..6e863e1 100644 --- a/vendor/symfony/yaml/Unescaper.php +++ b/vendor/symfony/yaml/Unescaper.php @@ -31,9 +31,9 @@ class Unescaper /** * Unescapes a single quoted string. * - * @param string $value A single quoted string. + * @param string $value A single quoted string * - * @return string The unescaped string. + * @return string The unescaped string */ public function unescapeSingleQuotedString($value) { @@ -43,9 +43,9 @@ class Unescaper /** * Unescapes a double quoted string. * - * @param string $value A double quoted string. + * @param string $value A double quoted string * - * @return string The unescaped string. + * @return string The unescaped string */ public function unescapeDoubleQuotedString($value) { diff --git a/vendor/symfony/yaml/Yaml.php b/vendor/symfony/yaml/Yaml.php index caede55..46e6ef5 100644 --- a/vendor/symfony/yaml/Yaml.php +++ b/vendor/symfony/yaml/Yaml.php @@ -20,6 +20,16 @@ use Symfony\Component\Yaml\Exception\ParseException; */ class Yaml { + const DUMP_OBJECT = 1; + const PARSE_EXCEPTION_ON_INVALID_TYPE = 2; + const PARSE_OBJECT = 4; + const PARSE_OBJECT_FOR_MAP = 8; + const DUMP_EXCEPTION_ON_INVALID_TYPE = 16; + const PARSE_DATETIME = 32; + const DUMP_OBJECT_AS_MAP = 64; + const DUMP_MULTI_LINE_LITERAL_BLOCK = 128; + const PARSE_CONSTANT = 256; + /** * Parses YAML into a PHP value. * @@ -29,45 +39,81 @@ class Yaml * print_r($array); * * - * @param string $input A string containing YAML - * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise - * @param bool $objectSupport True if object support is enabled, false otherwise - * @param bool $objectForMap True if maps should return a stdClass instead of array() + * @param string $input A string containing YAML + * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior * * @return mixed The YAML converted to a PHP value * * @throws ParseException If the YAML is not valid */ - public static function parse($input, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false) + public static function parse($input, $flags = 0) { + if (is_bool($flags)) { + @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED); + + if ($flags) { + $flags = self::PARSE_EXCEPTION_ON_INVALID_TYPE; + } else { + $flags = 0; + } + } + + if (func_num_args() >= 3) { + @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the PARSE_OBJECT flag instead.', E_USER_DEPRECATED); + + if (func_get_arg(2)) { + $flags |= self::PARSE_OBJECT; + } + } + + if (func_num_args() >= 4) { + @trigger_error('Passing a boolean flag to toggle object for map support is deprecated since version 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED); + + if (func_get_arg(3)) { + $flags |= self::PARSE_OBJECT_FOR_MAP; + } + } + $yaml = new Parser(); - return $yaml->parse($input, $exceptionOnInvalidType, $objectSupport, $objectForMap); + return $yaml->parse($input, $flags); } /** - * Dumps a PHP array to a YAML string. + * Dumps a PHP value to a YAML string. * * The dump method, when supplied with an array, will do its best * to convert the array into friendly YAML. * - * @param array $array PHP array - * @param int $inline The level where you switch to inline YAML - * @param int $indent The amount of spaces to use for indentation of nested nodes. - * @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise - * @param bool $objectSupport true if object support is enabled, false otherwise + * @param mixed $input The PHP value + * @param int $inline The level where you switch to inline YAML + * @param int $indent The amount of spaces to use for indentation of nested nodes + * @param int $flags A bit field of DUMP_* constants to customize the dumped YAML string * - * @return string A YAML string representing the original PHP array + * @return string A YAML string representing the original PHP value */ - public static function dump($array, $inline = 2, $indent = 4, $exceptionOnInvalidType = false, $objectSupport = false) + public static function dump($input, $inline = 2, $indent = 4, $flags = 0) { - if ($indent < 1) { - throw new \InvalidArgumentException('The indentation must be greater than zero.'); + if (is_bool($flags)) { + @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since version 3.1 and will be removed in 4.0. Use the DUMP_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED); + + if ($flags) { + $flags = self::DUMP_EXCEPTION_ON_INVALID_TYPE; + } else { + $flags = 0; + } } - $yaml = new Dumper(); - $yaml->setIndentation($indent); + if (func_num_args() >= 5) { + @trigger_error('Passing a boolean flag to toggle object support is deprecated since version 3.1 and will be removed in 4.0. Use the DUMP_OBJECT flag instead.', E_USER_DEPRECATED); - return $yaml->dump($array, $inline, 0, $exceptionOnInvalidType, $objectSupport); + if (func_get_arg(4)) { + $flags |= self::DUMP_OBJECT; + } + } + + $yaml = new Dumper($indent); + + return $yaml->dump($input, $inline, 0, $flags); } } diff --git a/vendor/symfony/yaml/composer.json b/vendor/symfony/yaml/composer.json index db1714c..9c92beb 100644 --- a/vendor/symfony/yaml/composer.json +++ b/vendor/symfony/yaml/composer.json @@ -18,6 +18,12 @@ "require": { "php": ">=5.5.9" }, + "require-dev": { + "symfony/console": "~2.8|~3.0" + }, + "suggest": { + "symfony/console": "For validating YAML files using the lint command" + }, "autoload": { "psr-4": { "Symfony\\Component\\Yaml\\": "" }, "exclude-from-classmap": [ @@ -27,7 +33,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "3.0-dev" + "dev-master": "3.2-dev" } } }