From acc75edc28c7a86a29c36b9455dfac8fc18d8d49 Mon Sep 17 00:00:00 2001 From: exu Date: Mon, 26 Jun 2023 13:40:26 +0200 Subject: [PATCH] (Grav GitSync) Automatic Commit from exu --- plugins/form/CHANGELOG.md | 6 + plugins/form/blueprints.yaml | 2 +- plugins/form/form.php | 19 +- plugins/login-oauth2-extras/CHANGELOG.md | 43 + plugins/login-oauth2-extras/LICENSE | 21 + plugins/login-oauth2-extras/README.md | 273 +++ plugins/login-oauth2-extras/blueprints.yaml | 1006 +++++++++++ .../classes/Providers/AzureProvider.php | 186 ++ .../classes/Providers/DiscordProvider.php | 50 + .../classes/Providers/ExtraProvider.php | 25 + .../classes/Providers/GitlabProvider.php | 55 + .../classes/Providers/JiraProvider.php | 43 + .../classes/Providers/KeycloakProvider.php | 53 + .../classes/Providers/OktaProvider.php | 43 + .../classes/Providers/PatreonProvider.php | 45 + .../classes/Providers/SlackProvider.php | 45 + .../classes/Providers/TwitchProvider.php | 45 + plugins/login-oauth2-extras/composer.json | 28 + plugins/login-oauth2-extras/composer.lock | 593 +++++++ .../css/login-oauth2-extras.css | 64 + plugins/login-oauth2-extras/languages/en.yaml | 10 + .../login-oauth2-extras.php | 109 ++ .../login-oauth2-extras.yaml | 136 ++ plugins/login-oauth2-extras/media/azure.svg | 1 + plugins/login-oauth2-extras/media/discord.svg | 1 + plugins/login-oauth2-extras/media/gitlab.svg | 1 + plugins/login-oauth2-extras/media/jira.svg | 8 + plugins/login-oauth2-extras/media/okta.svg | 29 + plugins/login-oauth2-extras/media/patreon.svg | 8 + plugins/login-oauth2-extras/media/slack.svg | 1 + plugins/login-oauth2-extras/media/twitch.svg | 1 + .../login-oauth2/providers/azure.html.twig | 4 + .../login-oauth2/providers/discord.html.twig | 4 + .../login-oauth2/providers/gitlab.html.twig | 4 + .../login-oauth2/providers/jira.html.twig | 4 + .../login-oauth2/providers/keycloak.html.twig | 4 + .../login-oauth2/providers/okta.html.twig | 4 + .../login-oauth2/providers/patreon.html.twig | 4 + .../login-oauth2/providers/slack.html.twig | 4 + .../login-oauth2/providers/twitch.html.twig | 4 + .../adam-paterson/oauth2-slack/.gitignore | 3 + .../oauth2-slack/.scrutinizer.yml | 35 + .../adam-paterson/oauth2-slack/.travis.yml | 22 + .../oauth2-slack/CONTRIBUTING.md | 42 + .../vendor/adam-paterson/oauth2-slack/LICENSE | 21 + .../adam-paterson/oauth2-slack/README.md | 95 ++ .../adam-paterson/oauth2-slack/composer.json | 42 + .../adam-paterson/oauth2-slack/phpunit.xml | 37 + .../oauth2-slack/src/Provider/Slack.php | 147 ++ .../src/Provider/SlackAuthorizedUser.php | 66 + .../src/Provider/SlackResourceOwner.php | 134 ++ .../test/src/Provider/SlackTest.php | 269 +++ .../login-oauth2-extras/vendor/autoload.php | 7 + .../vendor/composer/ClassLoader.php | 572 +++++++ .../vendor/composer/InstalledVersions.php | 350 ++++ .../vendor/composer/LICENSE | 21 + .../vendor/composer/autoload_classmap.php | 10 + .../vendor/composer/autoload_namespaces.php | 9 + .../vendor/composer/autoload_psr4.php | 20 + .../vendor/composer/autoload_real.php | 57 + .../vendor/composer/autoload_static.php | 110 ++ .../vendor/composer/installed.json | 608 +++++++ .../vendor/composer/installed.php | 151 ++ .../vendor/composer/platform_check.php | 26 + .../vendor/firebase/php-jwt/LICENSE | 30 + .../vendor/firebase/php-jwt/README.md | 289 ++++ .../vendor/firebase/php-jwt/composer.json | 36 + .../php-jwt/src/BeforeValidException.php | 7 + .../firebase/php-jwt/src/ExpiredException.php | 7 + .../vendor/firebase/php-jwt/src/JWK.php | 172 ++ .../vendor/firebase/php-jwt/src/JWT.php | 611 +++++++ .../vendor/firebase/php-jwt/src/Key.php | 59 + .../php-jwt/src/SignatureInvalidException.php | 7 + .../vendor/foxworth42/oauth2-okta/LICENSE | 21 + .../vendor/foxworth42/oauth2-okta/README.md | 32 + .../foxworth42/oauth2-okta/composer.json | 46 + .../foxworth42/oauth2-okta/example/index.php | 36 + .../oauth2-okta/example/provider.php | 26 + .../foxworth42/oauth2-okta/example/reset.php | 8 + .../foxworth42/oauth2-okta/example/server.sh | 4 + .../foxworth42/oauth2-okta/example/user.php | 40 + .../foxworth42/oauth2-okta/phpcs.xml.dist | 18 + .../foxworth42/oauth2-okta/phpunit.xml.dist | 27 + .../oauth2-okta/src/Provider/Okta.php | 105 ++ .../oauth2-okta/src/Provider/OktaUser.php | 118 ++ .../gravure/oauth2-patreon/.editorconfig | 11 + .../vendor/gravure/oauth2-patreon/.gitignore | 2 + .../vendor/gravure/oauth2-patreon/LICENSE.md | 21 + .../vendor/gravure/oauth2-patreon/README.md | 45 + .../gravure/oauth2-patreon/composer.json | 35 + .../Exceptions/InvalidResourceException.php | 10 + .../oauth2-patreon/src/Provider/Patreon.php | 144 ++ .../oauth2-patreon/src/Resources/Factory.php | 79 + .../oauth2-patreon/src/Resources/Patron.php | 71 + .../oauth2-patreon/src/Resources/Pledge.php | 8 + .../oauth2-patreon/src/Resources/Resource.php | 36 + .../vendor/mrjoops/oauth2-jira/.gitignore | 50 + .../mrjoops/oauth2-jira/.scrutinizer.yml | 35 + .../vendor/mrjoops/oauth2-jira/.travis.yml | 32 + .../mrjoops/oauth2-jira/CONTRIBUTING.md | 40 + .../vendor/mrjoops/oauth2-jira/LICENSE | 21 + .../vendor/mrjoops/oauth2-jira/README.md | 125 ++ .../vendor/mrjoops/oauth2-jira/composer.json | 38 + .../oauth2-jira/nbproject/project.properties | 23 + .../mrjoops/oauth2-jira/nbproject/project.xml | 9 + .../JiraIdentityProviderException.php | 54 + .../mrjoops/oauth2-jira/src/Provider/Jira.php | 147 ++ .../src/Provider/JiraResourceOwner.php | 78 + .../src/Provider/JiraResourceOwnerTest.php | 74 + .../test/src/Provider/JiraTest.php | 228 +++ .../vendor/omines/oauth2-gitlab/.gitignore | 9 + .../vendor/omines/oauth2-gitlab/.php_cs | 32 + .../omines/oauth2-gitlab/.scrutinizer.yml | 35 + .../vendor/omines/oauth2-gitlab/.travis.yml | 30 + .../vendor/omines/oauth2-gitlab/CHANGELOG.md | 78 + .../omines/oauth2-gitlab/CONTRIBUTING.md | 7 + .../vendor/omines/oauth2-gitlab/LICENSE | 21 + .../vendor/omines/oauth2-gitlab/README.md | 121 ++ .../oauth2-gitlab/bin/install-infection | 8 + .../vendor/omines/oauth2-gitlab/composer.json | 51 + .../omines/oauth2-gitlab/infection.json.dist | 12 + .../omines/oauth2-gitlab/phpunit.xml.dist | 22 + .../vendor/omines/oauth2-gitlab/renovate.json | 2 + .../GitlabIdentityProviderException.php | 60 + .../oauth2-gitlab/src/Provider/Gitlab.php | 117 ++ .../src/Provider/GitlabResourceOwner.php | 171 ++ .../test/src/Provider/GitlabTest.php | 225 +++ .../stevenmaguire/oauth2-keycloak/.gitignore | 4 + .../oauth2-keycloak/.scrutinizer.yml | 35 + .../stevenmaguire/oauth2-keycloak/.travis.yml | 26 + .../oauth2-keycloak/CHANGELOG.md | 74 + .../oauth2-keycloak/CONTRIBUTING.md | 42 + .../stevenmaguire/oauth2-keycloak/LICENSE | 21 + .../stevenmaguire/oauth2-keycloak/README.md | 175 ++ .../oauth2-keycloak/composer.json | 44 + .../oauth2-keycloak/examples/index.php | 53 + .../oauth2-keycloak/phpunit.xml.dist | 38 + .../EncryptionConfigurationException.php | 22 + .../oauth2-keycloak/src/Provider/Keycloak.php | 325 ++++ .../src/Provider/KeycloakResourceOwner.php | 65 + .../test/src/Provider/KeycloakTest.php | 306 ++++ .../vendor/thenetworg/oauth2-azure/.gitignore | 5 + .../thenetworg/oauth2-azure/CHANGELOG.md | 5 + .../vendor/thenetworg/oauth2-azure/LICENSE.md | 21 + .../vendor/thenetworg/oauth2-azure/README.md | 232 +++ .../thenetworg/oauth2-azure/composer.json | 34 + .../oauth2-azure/src/Grant/JwtBearer.php | 18 + .../oauth2-azure/src/Provider/Azure.php | 323 ++++ .../src/Provider/AzureResourceOwner.php | 97 ++ .../oauth2-azure/src/Token/AccessToken.php | 72 + .../vertisan/oauth2-twitch-helix/.gitignore | 2 + .../vertisan/oauth2-twitch-helix/.travis.yml | 17 + .../vertisan/oauth2-twitch-helix/LICENCE | 21 + .../vertisan/oauth2-twitch-helix/README.md | 35 + .../oauth2-twitch-helix/composer.json | 41 + .../vertisan/oauth2-twitch-helix/phpunit.xml | 17 + .../TwitchHelixIdentityProviderException.php | 8 + .../oauth2-twitch-helix/src/TwitchHelix.php | 110 ++ .../src/TwitchHelixResourceOwner.php | 137 ++ .../oauth2-twitch-helix/tests/TwitchTest.php | 117 ++ .../wohali/oauth2-discord-new/.gitignore | 10 + .../oauth2-discord-new/.scrutinizer.yml | 36 + .../wohali/oauth2-discord-new/.travis.yml | 31 + .../wohali/oauth2-discord-new/CONTRIBUTING.md | 40 + .../vendor/wohali/oauth2-discord-new/LICENSE | 22 + .../wohali/oauth2-discord-new/README.md | 204 +++ .../wohali/oauth2-discord-new/composer.json | 48 + .../wohali/oauth2-discord-new/coverage.clover | 72 + .../wohali/oauth2-discord-new/phpunit.xml | 35 + .../src/Provider/Discord.php | 125 ++ .../src/Provider/DiscordResourceOwner.php | 109 ++ .../DiscordIdentityProviderException.php | 49 + .../test/src/Provider/DiscordTest.php | 146 ++ plugins/login-oauth2/.gitignore | 1 + plugins/login-oauth2/CHANGELOG.md | 116 ++ plugins/login-oauth2/LICENSE | 21 + plugins/login-oauth2/README.md | 317 ++++ plugins/login-oauth2/blueprints.yaml | 707 ++++++++ plugins/login-oauth2/classes/OAuth2.php | 85 + .../login-oauth2/classes/ProviderFactory.php | 38 + .../classes/Providers/BaseProvider.php | 139 ++ .../classes/Providers/FacebookProvider.php | 73 + .../classes/Providers/GithubProvider.php | 106 ++ .../classes/Providers/GoogleProvider.php | 90 + .../classes/Providers/InstagramProvider.php | 69 + .../classes/Providers/LinkedinProvider.php | 71 + .../classes/Providers/ProviderInterface.php | 73 + plugins/login-oauth2/composer.json | 23 + plugins/login-oauth2/composer.lock | 1071 ++++++++++++ plugins/login-oauth2/css/login-oauth2.css | 106 ++ plugins/login-oauth2/languages/en.yaml | 43 + plugins/login-oauth2/login-oauth2.php | 490 ++++++ plugins/login-oauth2/login-oauth2.yaml | 98 ++ plugins/login-oauth2/media/facebook.svg | 1 + plugins/login-oauth2/media/github.svg | 1 + plugins/login-oauth2/media/google.svg | 1 + plugins/login-oauth2/media/instagram.svg | 1 + plugins/login-oauth2/media/linkedin.svg | 1 + plugins/login-oauth2/scss/login-oauth2.scss | 158 ++ .../login-oauth2/login-oauth2.html.twig | 17 + .../login-oauth2/providers/facebook.html.twig | 4 + .../login-oauth2/providers/github.html.twig | 4 + .../login-oauth2/providers/google.html.twig | 4 + .../providers/instagram.html.twig | 4 + .../login-oauth2/providers/linkedin.html.twig | 4 + plugins/login-oauth2/vendor/autoload.php | 25 + .../vendor/composer/ClassLoader.php | 581 +++++++ .../vendor/composer/InstalledVersions.php | 352 ++++ plugins/login-oauth2/vendor/composer/LICENSE | 21 + .../vendor/composer/autoload_classmap.php | 10 + .../vendor/composer/autoload_files.php | 14 + .../vendor/composer/autoload_namespaces.php | 9 + .../vendor/composer/autoload_psr4.php | 16 + .../vendor/composer/autoload_real.php | 50 + .../vendor/composer/autoload_static.php | 86 + .../vendor/composer/installed.json | 1088 ++++++++++++ .../vendor/composer/installed.php | 185 ++ .../vendor/composer/platform_check.php | 26 + .../vendor/guzzlehttp/guzzle/CHANGELOG.md | 1519 +++++++++++++++++ .../vendor/guzzlehttp/guzzle/LICENSE | 27 + .../vendor/guzzlehttp/guzzle/README.md | 94 + .../vendor/guzzlehttp/guzzle/UPGRADING.md | 1253 ++++++++++++++ .../vendor/guzzlehttp/guzzle/composer.json | 105 ++ .../guzzlehttp/guzzle/src/BodySummarizer.php | 28 + .../guzzle/src/BodySummarizerInterface.php | 13 + .../vendor/guzzlehttp/guzzle/src/Client.php | 477 ++++++ .../guzzlehttp/guzzle/src/ClientInterface.php | 84 + .../guzzlehttp/guzzle/src/ClientTrait.php | 241 +++ .../guzzle/src/Cookie/CookieJar.php | 317 ++++ .../guzzle/src/Cookie/CookieJarInterface.php | 79 + .../guzzle/src/Cookie/FileCookieJar.php | 101 ++ .../guzzle/src/Cookie/SessionCookieJar.php | 77 + .../guzzle/src/Cookie/SetCookie.php | 446 +++++ .../src/Exception/BadResponseException.php | 39 + .../guzzle/src/Exception/ClientException.php | 10 + .../guzzle/src/Exception/ConnectException.php | 56 + .../guzzle/src/Exception/GuzzleException.php | 9 + .../Exception/InvalidArgumentException.php | 7 + .../guzzle/src/Exception/RequestException.php | 166 ++ .../guzzle/src/Exception/ServerException.php | 10 + .../Exception/TooManyRedirectsException.php | 7 + .../src/Exception/TransferException.php | 7 + .../guzzle/src/Handler/CurlFactory.php | 595 +++++++ .../src/Handler/CurlFactoryInterface.php | 25 + .../guzzle/src/Handler/CurlHandler.php | 49 + .../guzzle/src/Handler/CurlMultiHandler.php | 262 +++ .../guzzle/src/Handler/EasyHandle.php | 112 ++ .../guzzle/src/Handler/HeaderProcessor.php | 42 + .../guzzle/src/Handler/MockHandler.php | 211 +++ .../guzzlehttp/guzzle/src/Handler/Proxy.php | 51 + .../guzzle/src/Handler/StreamHandler.php | 593 +++++++ .../guzzlehttp/guzzle/src/HandlerStack.php | 275 +++ .../guzzle/src/MessageFormatter.php | 198 +++ .../guzzle/src/MessageFormatterInterface.php | 18 + .../guzzlehttp/guzzle/src/Middleware.php | 260 +++ .../vendor/guzzlehttp/guzzle/src/Pool.php | 125 ++ .../guzzle/src/PrepareBodyMiddleware.php | 104 ++ .../guzzle/src/RedirectMiddleware.php | 228 +++ .../guzzlehttp/guzzle/src/RequestOptions.php | 264 +++ .../guzzlehttp/guzzle/src/RetryMiddleware.php | 116 ++ .../guzzlehttp/guzzle/src/TransferStats.php | 133 ++ .../vendor/guzzlehttp/guzzle/src/Utils.php | 385 +++++ .../guzzlehttp/guzzle/src/functions.php | 167 ++ .../guzzle/src/functions_include.php | 6 + .../vendor/guzzlehttp/promises/CHANGELOG.md | 110 ++ .../vendor/guzzlehttp/promises/LICENSE | 24 + .../vendor/guzzlehttp/promises/README.md | 546 ++++++ .../vendor/guzzlehttp/promises/composer.json | 58 + .../promises/src/AggregateException.php | 17 + .../promises/src/CancellationException.php | 10 + .../guzzlehttp/promises/src/Coroutine.php | 169 ++ .../vendor/guzzlehttp/promises/src/Create.php | 84 + .../vendor/guzzlehttp/promises/src/Each.php | 90 + .../guzzlehttp/promises/src/EachPromise.php | 247 +++ .../promises/src/FulfilledPromise.php | 84 + .../vendor/guzzlehttp/promises/src/Is.php | 46 + .../guzzlehttp/promises/src/Promise.php | 278 +++ .../promises/src/PromiseInterface.php | 97 ++ .../promises/src/PromisorInterface.php | 16 + .../promises/src/RejectedPromise.php | 91 + .../promises/src/RejectionException.php | 48 + .../guzzlehttp/promises/src/TaskQueue.php | 67 + .../promises/src/TaskQueueInterface.php | 24 + .../vendor/guzzlehttp/promises/src/Utils.php | 276 +++ .../guzzlehttp/promises/src/functions.php | 363 ++++ .../promises/src/functions_include.php | 6 + .../vendor/guzzlehttp/psr7/CHANGELOG.md | 396 +++++ .../vendor/guzzlehttp/psr7/LICENSE | 26 + .../vendor/guzzlehttp/psr7/README.md | 872 ++++++++++ .../vendor/guzzlehttp/psr7/composer.json | 96 ++ .../guzzlehttp/psr7/src/AppendStream.php | 248 +++ .../guzzlehttp/psr7/src/BufferStream.php | 149 ++ .../guzzlehttp/psr7/src/CachingStream.php | 153 ++ .../guzzlehttp/psr7/src/DroppingStream.php | 49 + .../src/Exception/MalformedUriException.php | 14 + .../vendor/guzzlehttp/psr7/src/FnStream.php | 180 ++ .../vendor/guzzlehttp/psr7/src/Header.php | 134 ++ .../guzzlehttp/psr7/src/HttpFactory.php | 100 ++ .../guzzlehttp/psr7/src/InflateStream.php | 37 + .../guzzlehttp/psr7/src/LazyOpenStream.php | 41 + .../guzzlehttp/psr7/src/LimitStream.php | 157 ++ .../vendor/guzzlehttp/psr7/src/Message.php | 246 +++ .../guzzlehttp/psr7/src/MessageTrait.php | 264 +++ .../vendor/guzzlehttp/psr7/src/MimeType.php | 1237 ++++++++++++++ .../guzzlehttp/psr7/src/MultipartStream.php | 159 ++ .../guzzlehttp/psr7/src/NoSeekStream.php | 28 + .../vendor/guzzlehttp/psr7/src/PumpStream.php | 179 ++ .../vendor/guzzlehttp/psr7/src/Query.php | 113 ++ .../vendor/guzzlehttp/psr7/src/Request.php | 157 ++ .../vendor/guzzlehttp/psr7/src/Response.php | 160 ++ .../vendor/guzzlehttp/psr7/src/Rfc7230.php | 23 + .../guzzlehttp/psr7/src/ServerRequest.php | 344 ++++ .../vendor/guzzlehttp/psr7/src/Stream.php | 282 +++ .../psr7/src/StreamDecoratorTrait.php | 155 ++ .../guzzlehttp/psr7/src/StreamWrapper.php | 175 ++ .../guzzlehttp/psr7/src/UploadedFile.php | 211 +++ .../vendor/guzzlehttp/psr7/src/Uri.php | 740 ++++++++ .../guzzlehttp/psr7/src/UriComparator.php | 52 + .../guzzlehttp/psr7/src/UriNormalizer.php | 220 +++ .../guzzlehttp/psr7/src/UriResolver.php | 211 +++ .../vendor/guzzlehttp/psr7/src/Utils.php | 459 +++++ .../jakeasmith/http_build_url/.gitignore | 5 + .../jakeasmith/http_build_url/.travis.yml | 13 + .../vendor/jakeasmith/http_build_url/LICENSE | 21 + .../jakeasmith/http_build_url/composer.json | 18 + .../http_build_url/phpunit.xml.dist | 21 + .../jakeasmith/http_build_url/readme.md | 20 + .../http_build_url/src/http_build_url.php | 174 ++ .../http_build_url/tests/HttpBuildUrlTest.php | 216 +++ .../http_build_url/tests/bootstrap.php | 13 + .../vendor/league/oauth2-client/LICENSE | 21 + .../vendor/league/oauth2-client/README.md | 58 + .../vendor/league/oauth2-client/composer.json | 58 + .../oauth2-client/src/Grant/AbstractGrant.php | 80 + .../src/Grant/AuthorizationCode.php | 41 + .../src/Grant/ClientCredentials.php | 39 + .../Grant/Exception/InvalidGrantException.php | 26 + .../oauth2-client/src/Grant/GrantFactory.php | 104 ++ .../oauth2-client/src/Grant/Password.php | 42 + .../oauth2-client/src/Grant/RefreshToken.php | 41 + .../HttpBasicAuthOptionProvider.php | 42 + .../OptionProviderInterface.php | 30 + .../OptionProvider/PostAuthOptionProvider.php | 51 + .../src/Provider/AbstractProvider.php | 843 +++++++++ .../Exception/IdentityProviderException.php | 48 + .../src/Provider/GenericProvider.php | 233 +++ .../src/Provider/GenericResourceOwner.php | 61 + .../src/Provider/ResourceOwnerInterface.php | 36 + .../oauth2-client/src/Token/AccessToken.php | 243 +++ .../src/Token/AccessTokenInterface.php | 74 + .../ResourceOwnerAccessTokenInterface.php | 25 + .../src/Tool/ArrayAccessorTrait.php | 52 + .../src/Tool/BearerAuthorizationTrait.php | 36 + .../src/Tool/GuardedPropertyTrait.php | 70 + .../src/Tool/MacAuthorizationTrait.php | 83 + .../src/Tool/ProviderRedirectTrait.php | 122 ++ .../src/Tool/QueryBuilderTrait.php | 33 + .../oauth2-client/src/Tool/RequestFactory.php | 87 + .../src/Tool/RequiredParameterTrait.php | 56 + .../oauth2-facebook/.github/workflows/ci.yaml | 56 + .../.github/workflows/static-analysis.yaml | 23 + .../vendor/league/oauth2-facebook/LICENSE | 21 + .../league/oauth2-facebook/composer.json | 40 + .../src/Grant/FbExchangeToken.php | 23 + .../src/Provider/AppSecretProof.php | 19 + .../Exception/FacebookProviderException.php | 9 + .../oauth2-facebook/src/Provider/Facebook.php | 210 +++ .../src/Provider/FacebookUser.php | 216 +++ .../vendor/league/oauth2-github/.gitignore | 5 + .../league/oauth2-github/.scrutinizer.yml | 35 + .../vendor/league/oauth2-github/.travis.yml | 27 + .../vendor/league/oauth2-github/CHANGELOG.md | 92 + .../league/oauth2-github/CONTRIBUTING.md | 42 + .../vendor/league/oauth2-github/LICENSE | 21 + .../vendor/league/oauth2-github/README.md | 129 ++ .../vendor/league/oauth2-github/composer.json | 43 + .../vendor/league/oauth2-github/phpunit.xml | 37 + .../GithubIdentityProviderException.php | 53 + .../oauth2-github/src/Provider/Github.php | 110 ++ .../src/Provider/GithubResourceOwner.php | 108 ++ .../src/Provider/GithubResourceOwnerTest.php | 36 + .../test/src/Provider/GithubTest.php | 215 +++ .../oauth2-google/.github/workflows/ci.yaml | 65 + .../.github/workflows/static-analysis.yaml | 25 + .../vendor/league/oauth2-google/CHANGELOG.md | 79 + .../league/oauth2-google/CONTRIBUTING.md | 42 + .../vendor/league/oauth2-google/LICENSE | 21 + .../vendor/league/oauth2-google/README.md | 241 +++ .../vendor/league/oauth2-google/composer.json | 43 + .../league/oauth2-google/examples/index.php | 35 + .../oauth2-google/examples/provider.php | 24 + .../league/oauth2-google/examples/reset.php | 7 + .../league/oauth2-google/examples/server.sh | 3 + .../league/oauth2-google/examples/user.php | 39 + .../league/oauth2-google/phpunit.xml.dist | 26 + .../src/Exception/HostedDomainException.php | 19 + .../oauth2-google/src/Provider/Google.php | 154 ++ .../oauth2-google/src/Provider/GoogleUser.php | 109 ++ .../vendor/league/oauth2-instagram/.gitignore | 7 + .../league/oauth2-instagram/.scrutinizer.yml | 35 + .../league/oauth2-instagram/.travis.yml | 34 + .../league/oauth2-instagram/CHANGELOG.md | 181 ++ .../league/oauth2-instagram/CONTRIBUTING.md | 42 + .../vendor/league/oauth2-instagram/LICENSE | 21 + .../vendor/league/oauth2-instagram/README.md | 134 ++ .../league/oauth2-instagram/composer.json | 44 + .../league/oauth2-instagram/phpunit.xml | 28 + .../src/Grant/IgExchangeToken.php | 32 + .../src/Grant/IgRefreshToken.php | 32 + .../InstagramIdentityProviderException.php | 56 + .../src/Provider/Instagram.php | 301 ++++ .../src/Provider/InstagramResourceOwner.php | 51 + .../tests/src/Provider/InstagramTest.php | 270 +++ .../vendor/league/oauth2-linkedin/.gitignore | 5 + .../league/oauth2-linkedin/.scrutinizer.yml | 35 + .../vendor/league/oauth2-linkedin/.travis.yml | 50 + .../league/oauth2-linkedin/CHANGELOG.md | 324 ++++ .../league/oauth2-linkedin/CONTRIBUTING.md | 42 + .../vendor/league/oauth2-linkedin/LICENSE | 21 + .../vendor/league/oauth2-linkedin/README.md | 194 +++ .../league/oauth2-linkedin/composer.json | 44 + .../vendor/league/oauth2-linkedin/phpunit.xml | 37 + .../LinkedInAccessDeniedException.php | 8 + .../oauth2-linkedin/src/Provider/LinkedIn.php | 276 +++ .../src/Provider/LinkedInResourceOwner.php | 207 +++ .../src/Token/LinkedInAccessToken.php | 41 + .../test/api_responses/email.json | 13 + .../test/api_responses/me.json | 186 ++ .../test/src/Provider/LinkedInTest.php | 431 +++++ .../vendor/paragonie/random_compat/LICENSE | 22 + .../paragonie/random_compat/build-phar.sh | 5 + .../paragonie/random_compat/composer.json | 34 + .../dist/random_compat.phar.pubkey | 5 + .../dist/random_compat.phar.pubkey.asc | 11 + .../paragonie/random_compat/lib/random.php | 32 + .../random_compat/other/build_phar.php | 57 + .../random_compat/psalm-autoload.php | 9 + .../vendor/paragonie/random_compat/psalm.xml | 19 + .../vendor/psr/http-client/CHANGELOG.md | 23 + .../vendor/psr/http-client/LICENSE | 19 + .../vendor/psr/http-client/README.md | 12 + .../vendor/psr/http-client/composer.json | 27 + .../src/ClientExceptionInterface.php | 10 + .../psr/http-client/src/ClientInterface.php | 20 + .../src/NetworkExceptionInterface.php | 24 + .../src/RequestExceptionInterface.php | 24 + .../vendor/psr/http-factory/.gitignore | 2 + .../vendor/psr/http-factory/.pullapprove.yml | 7 + .../vendor/psr/http-factory/LICENSE | 21 + .../vendor/psr/http-factory/README.md | 10 + .../vendor/psr/http-factory/composer.json | 35 + .../src/RequestFactoryInterface.php | 18 + .../src/ResponseFactoryInterface.php | 18 + .../src/ServerRequestFactoryInterface.php | 24 + .../src/StreamFactoryInterface.php | 45 + .../src/UploadedFileFactoryInterface.php | 34 + .../http-factory/src/UriFactoryInterface.php | 17 + .../vendor/psr/http-message/CHANGELOG.md | 36 + .../vendor/psr/http-message/LICENSE | 19 + .../vendor/psr/http-message/README.md | 13 + .../vendor/psr/http-message/composer.json | 26 + .../psr/http-message/src/MessageInterface.php | 187 ++ .../psr/http-message/src/RequestInterface.php | 129 ++ .../http-message/src/ResponseInterface.php | 68 + .../src/ServerRequestInterface.php | 261 +++ .../psr/http-message/src/StreamInterface.php | 158 ++ .../src/UploadedFileInterface.php | 123 ++ .../psr/http-message/src/UriInterface.php | 323 ++++ .../vendor/ralouphie/getallheaders/LICENSE | 21 + .../vendor/ralouphie/getallheaders/README.md | 27 + .../ralouphie/getallheaders/composer.json | 26 + .../getallheaders/src/getallheaders.php | 46 + .../symfony/deprecation-contracts/.gitignore | 3 + .../deprecation-contracts/CHANGELOG.md | 5 + .../symfony/deprecation-contracts/LICENSE | 19 + .../symfony/deprecation-contracts/README.md | 26 + .../deprecation-contracts/composer.json | 35 + .../deprecation-contracts/function.php | 27 + plugins/login-oauth2/watch.sh | 27 + 479 files changed, 51125 insertions(+), 18 deletions(-) create mode 100644 plugins/login-oauth2-extras/CHANGELOG.md create mode 100644 plugins/login-oauth2-extras/LICENSE create mode 100644 plugins/login-oauth2-extras/README.md create mode 100644 plugins/login-oauth2-extras/blueprints.yaml create mode 100644 plugins/login-oauth2-extras/classes/Providers/AzureProvider.php create mode 100644 plugins/login-oauth2-extras/classes/Providers/DiscordProvider.php create mode 100644 plugins/login-oauth2-extras/classes/Providers/ExtraProvider.php create mode 100644 plugins/login-oauth2-extras/classes/Providers/GitlabProvider.php create mode 100644 plugins/login-oauth2-extras/classes/Providers/JiraProvider.php create mode 100644 plugins/login-oauth2-extras/classes/Providers/KeycloakProvider.php create mode 100644 plugins/login-oauth2-extras/classes/Providers/OktaProvider.php create mode 100644 plugins/login-oauth2-extras/classes/Providers/PatreonProvider.php create mode 100644 plugins/login-oauth2-extras/classes/Providers/SlackProvider.php create mode 100644 plugins/login-oauth2-extras/classes/Providers/TwitchProvider.php create mode 100644 plugins/login-oauth2-extras/composer.json create mode 100644 plugins/login-oauth2-extras/composer.lock create mode 100644 plugins/login-oauth2-extras/css/login-oauth2-extras.css create mode 100644 plugins/login-oauth2-extras/languages/en.yaml create mode 100644 plugins/login-oauth2-extras/login-oauth2-extras.php create mode 100644 plugins/login-oauth2-extras/login-oauth2-extras.yaml create mode 100644 plugins/login-oauth2-extras/media/azure.svg create mode 100644 plugins/login-oauth2-extras/media/discord.svg create mode 100644 plugins/login-oauth2-extras/media/gitlab.svg create mode 100644 plugins/login-oauth2-extras/media/jira.svg create mode 100644 plugins/login-oauth2-extras/media/okta.svg create mode 100644 plugins/login-oauth2-extras/media/patreon.svg create mode 100644 plugins/login-oauth2-extras/media/slack.svg create mode 100644 plugins/login-oauth2-extras/media/twitch.svg create mode 100644 plugins/login-oauth2-extras/templates/login-oauth2/providers/azure.html.twig create mode 100644 plugins/login-oauth2-extras/templates/login-oauth2/providers/discord.html.twig create mode 100644 plugins/login-oauth2-extras/templates/login-oauth2/providers/gitlab.html.twig create mode 100644 plugins/login-oauth2-extras/templates/login-oauth2/providers/jira.html.twig create mode 100644 plugins/login-oauth2-extras/templates/login-oauth2/providers/keycloak.html.twig create mode 100644 plugins/login-oauth2-extras/templates/login-oauth2/providers/okta.html.twig create mode 100644 plugins/login-oauth2-extras/templates/login-oauth2/providers/patreon.html.twig create mode 100644 plugins/login-oauth2-extras/templates/login-oauth2/providers/slack.html.twig create mode 100644 plugins/login-oauth2-extras/templates/login-oauth2/providers/twitch.html.twig create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.gitignore create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.scrutinizer.yml create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.travis.yml create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/CONTRIBUTING.md create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/LICENSE create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/README.md create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/composer.json create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/phpunit.xml create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/Slack.php create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/SlackAuthorizedUser.php create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/SlackResourceOwner.php create mode 100644 plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/test/src/Provider/SlackTest.php create mode 100644 plugins/login-oauth2-extras/vendor/autoload.php create mode 100644 plugins/login-oauth2-extras/vendor/composer/ClassLoader.php create mode 100644 plugins/login-oauth2-extras/vendor/composer/InstalledVersions.php create mode 100644 plugins/login-oauth2-extras/vendor/composer/LICENSE create mode 100644 plugins/login-oauth2-extras/vendor/composer/autoload_classmap.php create mode 100644 plugins/login-oauth2-extras/vendor/composer/autoload_namespaces.php create mode 100644 plugins/login-oauth2-extras/vendor/composer/autoload_psr4.php create mode 100644 plugins/login-oauth2-extras/vendor/composer/autoload_real.php create mode 100644 plugins/login-oauth2-extras/vendor/composer/autoload_static.php create mode 100644 plugins/login-oauth2-extras/vendor/composer/installed.json create mode 100644 plugins/login-oauth2-extras/vendor/composer/installed.php create mode 100644 plugins/login-oauth2-extras/vendor/composer/platform_check.php create mode 100644 plugins/login-oauth2-extras/vendor/firebase/php-jwt/LICENSE create mode 100644 plugins/login-oauth2-extras/vendor/firebase/php-jwt/README.md create mode 100644 plugins/login-oauth2-extras/vendor/firebase/php-jwt/composer.json create mode 100644 plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/BeforeValidException.php create mode 100644 plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/ExpiredException.php create mode 100644 plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/JWK.php create mode 100644 plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/JWT.php create mode 100644 plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/Key.php create mode 100644 plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/SignatureInvalidException.php create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/LICENSE create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/README.md create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/composer.json create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/example/index.php create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/example/provider.php create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/example/reset.php create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/example/server.sh create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/example/user.php create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/phpcs.xml.dist create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/phpunit.xml.dist create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/src/Provider/Okta.php create mode 100644 plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/src/Provider/OktaUser.php create mode 100644 plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/.editorconfig create mode 100644 plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/.gitignore create mode 100644 plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/LICENSE.md create mode 100644 plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/README.md create mode 100644 plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/composer.json create mode 100644 plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Exceptions/InvalidResourceException.php create mode 100644 plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Provider/Patreon.php create mode 100644 plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Factory.php create mode 100644 plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Patron.php create mode 100644 plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Pledge.php create mode 100644 plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Resource.php create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.gitignore create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.scrutinizer.yml create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.travis.yml create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/CONTRIBUTING.md create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/LICENSE create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/README.md create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/composer.json create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/nbproject/project.properties create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/nbproject/project.xml create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/Exception/JiraIdentityProviderException.php create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/Jira.php create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/JiraResourceOwner.php create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/test/src/Provider/JiraResourceOwnerTest.php create mode 100644 plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/test/src/Provider/JiraTest.php create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.gitignore create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.php_cs create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.scrutinizer.yml create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.travis.yml create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/CHANGELOG.md create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/CONTRIBUTING.md create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/LICENSE create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/README.md create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/bin/install-infection create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/composer.json create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/infection.json.dist create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/phpunit.xml.dist create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/renovate.json create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/Exception/GitlabIdentityProviderException.php create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/Gitlab.php create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/GitlabResourceOwner.php create mode 100644 plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/test/src/Provider/GitlabTest.php create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.gitignore create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.scrutinizer.yml create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.travis.yml create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/CHANGELOG.md create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/CONTRIBUTING.md create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/LICENSE create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/README.md create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/composer.json create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/examples/index.php create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/phpunit.xml.dist create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/src/Provider/Exception/EncryptionConfigurationException.php create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/src/Provider/Keycloak.php create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/src/Provider/KeycloakResourceOwner.php create mode 100644 plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/test/src/Provider/KeycloakTest.php create mode 100644 plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/.gitignore create mode 100644 plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/CHANGELOG.md create mode 100644 plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/LICENSE.md create mode 100644 plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/README.md create mode 100644 plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/composer.json create mode 100644 plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Grant/JwtBearer.php create mode 100644 plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Provider/Azure.php create mode 100644 plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Provider/AzureResourceOwner.php create mode 100644 plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Token/AccessToken.php create mode 100644 plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/.gitignore create mode 100644 plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/.travis.yml create mode 100644 plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/LICENCE create mode 100644 plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/README.md create mode 100644 plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/composer.json create mode 100644 plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/phpunit.xml create mode 100644 plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/src/Exception/TwitchHelixIdentityProviderException.php create mode 100644 plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/src/TwitchHelix.php create mode 100644 plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/src/TwitchHelixResourceOwner.php create mode 100644 plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/tests/TwitchTest.php create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.gitignore create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.scrutinizer.yml create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.travis.yml create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/CONTRIBUTING.md create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/LICENSE create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/README.md create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/composer.json create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/coverage.clover create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/phpunit.xml create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/Discord.php create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/DiscordResourceOwner.php create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/Exception/DiscordIdentityProviderException.php create mode 100644 plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/test/src/Provider/DiscordTest.php create mode 100644 plugins/login-oauth2/.gitignore create mode 100644 plugins/login-oauth2/CHANGELOG.md create mode 100644 plugins/login-oauth2/LICENSE create mode 100644 plugins/login-oauth2/README.md create mode 100644 plugins/login-oauth2/blueprints.yaml create mode 100644 plugins/login-oauth2/classes/OAuth2.php create mode 100644 plugins/login-oauth2/classes/ProviderFactory.php create mode 100644 plugins/login-oauth2/classes/Providers/BaseProvider.php create mode 100644 plugins/login-oauth2/classes/Providers/FacebookProvider.php create mode 100644 plugins/login-oauth2/classes/Providers/GithubProvider.php create mode 100644 plugins/login-oauth2/classes/Providers/GoogleProvider.php create mode 100644 plugins/login-oauth2/classes/Providers/InstagramProvider.php create mode 100644 plugins/login-oauth2/classes/Providers/LinkedinProvider.php create mode 100644 plugins/login-oauth2/classes/Providers/ProviderInterface.php create mode 100644 plugins/login-oauth2/composer.json create mode 100644 plugins/login-oauth2/composer.lock create mode 100644 plugins/login-oauth2/css/login-oauth2.css create mode 100644 plugins/login-oauth2/languages/en.yaml create mode 100644 plugins/login-oauth2/login-oauth2.php create mode 100644 plugins/login-oauth2/login-oauth2.yaml create mode 100644 plugins/login-oauth2/media/facebook.svg create mode 100644 plugins/login-oauth2/media/github.svg create mode 100644 plugins/login-oauth2/media/google.svg create mode 100644 plugins/login-oauth2/media/instagram.svg create mode 100644 plugins/login-oauth2/media/linkedin.svg create mode 100644 plugins/login-oauth2/scss/login-oauth2.scss create mode 100644 plugins/login-oauth2/templates/login-oauth2/login-oauth2.html.twig create mode 100644 plugins/login-oauth2/templates/login-oauth2/providers/facebook.html.twig create mode 100644 plugins/login-oauth2/templates/login-oauth2/providers/github.html.twig create mode 100644 plugins/login-oauth2/templates/login-oauth2/providers/google.html.twig create mode 100644 plugins/login-oauth2/templates/login-oauth2/providers/instagram.html.twig create mode 100644 plugins/login-oauth2/templates/login-oauth2/providers/linkedin.html.twig create mode 100644 plugins/login-oauth2/vendor/autoload.php create mode 100644 plugins/login-oauth2/vendor/composer/ClassLoader.php create mode 100644 plugins/login-oauth2/vendor/composer/InstalledVersions.php create mode 100644 plugins/login-oauth2/vendor/composer/LICENSE create mode 100644 plugins/login-oauth2/vendor/composer/autoload_classmap.php create mode 100644 plugins/login-oauth2/vendor/composer/autoload_files.php create mode 100644 plugins/login-oauth2/vendor/composer/autoload_namespaces.php create mode 100644 plugins/login-oauth2/vendor/composer/autoload_psr4.php create mode 100644 plugins/login-oauth2/vendor/composer/autoload_real.php create mode 100644 plugins/login-oauth2/vendor/composer/autoload_static.php create mode 100644 plugins/login-oauth2/vendor/composer/installed.json create mode 100644 plugins/login-oauth2/vendor/composer/installed.php create mode 100644 plugins/login-oauth2/vendor/composer/platform_check.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/CHANGELOG.md create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/LICENSE create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/README.md create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/UPGRADING.md create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/composer.json create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/BodySummarizer.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Client.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/ClientInterface.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/ClientTrait.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/ClientException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/ConnectException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/InvalidArgumentException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/TooManyRedirectsException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/TransferException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/HandlerStack.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/MessageFormatter.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Middleware.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Pool.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/RequestOptions.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/RetryMiddleware.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/TransferStats.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Utils.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/functions.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/functions_include.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/CHANGELOG.md create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/LICENSE create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/README.md create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/composer.json create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/AggregateException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/CancellationException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/Coroutine.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/Create.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/Each.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/EachPromise.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/FulfilledPromise.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/Is.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/Promise.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/PromiseInterface.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/PromisorInterface.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/RejectedPromise.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/RejectionException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/TaskQueue.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/TaskQueueInterface.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/Utils.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/functions.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/promises/src/functions_include.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/CHANGELOG.md create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/LICENSE create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/README.md create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/composer.json create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/AppendStream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/BufferStream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/CachingStream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/DroppingStream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/FnStream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Header.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/HttpFactory.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/InflateStream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/LazyOpenStream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/LimitStream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Message.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MessageTrait.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MimeType.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MultipartStream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/NoSeekStream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/PumpStream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Query.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Request.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Response.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Rfc7230.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/ServerRequest.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Stream.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/StreamWrapper.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UploadedFile.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Uri.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriComparator.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriNormalizer.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriResolver.php create mode 100644 plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Utils.php create mode 100644 plugins/login-oauth2/vendor/jakeasmith/http_build_url/.gitignore create mode 100644 plugins/login-oauth2/vendor/jakeasmith/http_build_url/.travis.yml create mode 100644 plugins/login-oauth2/vendor/jakeasmith/http_build_url/LICENSE create mode 100644 plugins/login-oauth2/vendor/jakeasmith/http_build_url/composer.json create mode 100644 plugins/login-oauth2/vendor/jakeasmith/http_build_url/phpunit.xml.dist create mode 100644 plugins/login-oauth2/vendor/jakeasmith/http_build_url/readme.md create mode 100644 plugins/login-oauth2/vendor/jakeasmith/http_build_url/src/http_build_url.php create mode 100644 plugins/login-oauth2/vendor/jakeasmith/http_build_url/tests/HttpBuildUrlTest.php create mode 100644 plugins/login-oauth2/vendor/jakeasmith/http_build_url/tests/bootstrap.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/LICENSE create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/README.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/composer.json create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/AbstractGrant.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/AuthorizationCode.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/ClientCredentials.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/Exception/InvalidGrantException.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/GrantFactory.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/Password.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/RefreshToken.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/HttpBasicAuthOptionProvider.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/OptionProviderInterface.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/PostAuthOptionProvider.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/AbstractProvider.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/Exception/IdentityProviderException.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/GenericProvider.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/GenericResourceOwner.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/ResourceOwnerInterface.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Token/AccessToken.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Token/AccessTokenInterface.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Token/ResourceOwnerAccessTokenInterface.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/ArrayAccessorTrait.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/BearerAuthorizationTrait.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/GuardedPropertyTrait.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/MacAuthorizationTrait.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/QueryBuilderTrait.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/RequestFactory.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/RequiredParameterTrait.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-facebook/.github/workflows/ci.yaml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-facebook/.github/workflows/static-analysis.yaml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-facebook/LICENSE create mode 100644 plugins/login-oauth2/vendor/league/oauth2-facebook/composer.json create mode 100644 plugins/login-oauth2/vendor/league/oauth2-facebook/src/Grant/FbExchangeToken.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-facebook/src/Provider/AppSecretProof.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-facebook/src/Provider/Exception/FacebookProviderException.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-facebook/src/Provider/Facebook.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-facebook/src/Provider/FacebookUser.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/.gitignore create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/.scrutinizer.yml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/.travis.yml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/CHANGELOG.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/CONTRIBUTING.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/LICENSE create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/README.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/composer.json create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/phpunit.xml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/Exception/GithubIdentityProviderException.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/Github.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/GithubResourceOwner.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/test/src/Provider/GithubResourceOwnerTest.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-github/test/src/Provider/GithubTest.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/.github/workflows/ci.yaml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/.github/workflows/static-analysis.yaml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/CHANGELOG.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/CONTRIBUTING.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/LICENSE create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/README.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/composer.json create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/examples/index.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/examples/provider.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/examples/reset.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/examples/server.sh create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/examples/user.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/phpunit.xml.dist create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/src/Exception/HostedDomainException.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/src/Provider/Google.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-google/src/Provider/GoogleUser.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/.gitignore create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/.scrutinizer.yml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/.travis.yml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/CHANGELOG.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/CONTRIBUTING.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/LICENSE create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/README.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/composer.json create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/phpunit.xml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/src/Grant/IgExchangeToken.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/src/Grant/IgRefreshToken.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/src/Provider/Exception/InstagramIdentityProviderException.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/src/Provider/Instagram.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/src/Provider/InstagramResourceOwner.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-instagram/tests/src/Provider/InstagramTest.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/.gitignore create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/.scrutinizer.yml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/.travis.yml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/CHANGELOG.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/CONTRIBUTING.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/LICENSE create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/README.md create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/composer.json create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/phpunit.xml create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Provider/Exception/LinkedInAccessDeniedException.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Provider/LinkedIn.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Provider/LinkedInResourceOwner.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Token/LinkedInAccessToken.php create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/test/api_responses/email.json create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/test/api_responses/me.json create mode 100644 plugins/login-oauth2/vendor/league/oauth2-linkedin/test/src/Provider/LinkedInTest.php create mode 100644 plugins/login-oauth2/vendor/paragonie/random_compat/LICENSE create mode 100644 plugins/login-oauth2/vendor/paragonie/random_compat/build-phar.sh create mode 100644 plugins/login-oauth2/vendor/paragonie/random_compat/composer.json create mode 100644 plugins/login-oauth2/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey create mode 100644 plugins/login-oauth2/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey.asc create mode 100644 plugins/login-oauth2/vendor/paragonie/random_compat/lib/random.php create mode 100644 plugins/login-oauth2/vendor/paragonie/random_compat/other/build_phar.php create mode 100644 plugins/login-oauth2/vendor/paragonie/random_compat/psalm-autoload.php create mode 100644 plugins/login-oauth2/vendor/paragonie/random_compat/psalm.xml create mode 100644 plugins/login-oauth2/vendor/psr/http-client/CHANGELOG.md create mode 100644 plugins/login-oauth2/vendor/psr/http-client/LICENSE create mode 100644 plugins/login-oauth2/vendor/psr/http-client/README.md create mode 100644 plugins/login-oauth2/vendor/psr/http-client/composer.json create mode 100644 plugins/login-oauth2/vendor/psr/http-client/src/ClientExceptionInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-client/src/ClientInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-client/src/NetworkExceptionInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-client/src/RequestExceptionInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-factory/.gitignore create mode 100644 plugins/login-oauth2/vendor/psr/http-factory/.pullapprove.yml create mode 100644 plugins/login-oauth2/vendor/psr/http-factory/LICENSE create mode 100644 plugins/login-oauth2/vendor/psr/http-factory/README.md create mode 100644 plugins/login-oauth2/vendor/psr/http-factory/composer.json create mode 100644 plugins/login-oauth2/vendor/psr/http-factory/src/RequestFactoryInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-factory/src/ResponseFactoryInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-factory/src/ServerRequestFactoryInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-factory/src/StreamFactoryInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-factory/src/UploadedFileFactoryInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-factory/src/UriFactoryInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-message/CHANGELOG.md create mode 100644 plugins/login-oauth2/vendor/psr/http-message/LICENSE create mode 100644 plugins/login-oauth2/vendor/psr/http-message/README.md create mode 100644 plugins/login-oauth2/vendor/psr/http-message/composer.json create mode 100644 plugins/login-oauth2/vendor/psr/http-message/src/MessageInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-message/src/RequestInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-message/src/ResponseInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-message/src/ServerRequestInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-message/src/StreamInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-message/src/UploadedFileInterface.php create mode 100644 plugins/login-oauth2/vendor/psr/http-message/src/UriInterface.php create mode 100644 plugins/login-oauth2/vendor/ralouphie/getallheaders/LICENSE create mode 100644 plugins/login-oauth2/vendor/ralouphie/getallheaders/README.md create mode 100644 plugins/login-oauth2/vendor/ralouphie/getallheaders/composer.json create mode 100644 plugins/login-oauth2/vendor/ralouphie/getallheaders/src/getallheaders.php create mode 100644 plugins/login-oauth2/vendor/symfony/deprecation-contracts/.gitignore create mode 100644 plugins/login-oauth2/vendor/symfony/deprecation-contracts/CHANGELOG.md create mode 100644 plugins/login-oauth2/vendor/symfony/deprecation-contracts/LICENSE create mode 100644 plugins/login-oauth2/vendor/symfony/deprecation-contracts/README.md create mode 100644 plugins/login-oauth2/vendor/symfony/deprecation-contracts/composer.json create mode 100644 plugins/login-oauth2/vendor/symfony/deprecation-contracts/function.php create mode 100644 plugins/login-oauth2/watch.sh diff --git a/plugins/form/CHANGELOG.md b/plugins/form/CHANGELOG.md index 1577d68..87e9dbf 100644 --- a/plugins/form/CHANGELOG.md +++ b/plugins/form/CHANGELOG.md @@ -1,3 +1,9 @@ +# v7.2.0 +## 06/21/2023 + +1. [](#bugfix) + * Fixed a long-standing bug with cached forms not working properly in multi-language scenarios + # v7.1.3 ## 05/09/2023 diff --git a/plugins/form/blueprints.yaml b/plugins/form/blueprints.yaml index 4552765..094eaa4 100644 --- a/plugins/form/blueprints.yaml +++ b/plugins/form/blueprints.yaml @@ -1,7 +1,7 @@ name: Form slug: form type: plugin -version: 7.1.3 +version: 7.2.0 description: Enables forms handling and processing icon: check-square author: diff --git a/plugins/form/form.php b/plugins/form/form.php index bd96770..9ed14b1 100644 --- a/plugins/form/form.php +++ b/plugins/form/form.php @@ -65,8 +65,6 @@ class FormPlugin extends Plugin protected $active_forms = []; /** @var array */ protected $json_response = []; - /** @var bool */ - protected $recache_forms = false; /** * @return bool @@ -223,11 +221,6 @@ class FormPlugin extends Plugin $submitted = false; $this->json_response = []; - // Save cached forms. - if ($this->recache_forms) { - $this->saveCachedForms(); - } - /** @var PageInterface $page */ $page = $this->grav['page']; @@ -838,9 +831,8 @@ class FormPlugin extends Plugin if (!isset($this->forms[$route][$name])) { $form['_page_routable'] = !$page->isModule(); - $this->forms[$route][$name] = $form; - $this->recache_forms = true; + $this->saveCachedForms(); } } @@ -863,7 +855,7 @@ class FormPlugin extends Plugin $form['_page_routable'] = true; $this->forms[$route][$name] = $form; - $this->recache_forms = true; + $this->saveCachedForms(); } } @@ -1267,13 +1259,6 @@ class FormPlugin extends Plugin */ protected function saveCachedForms(): void { - // Save the current state of the forms to cache - if (!$this->recache_forms) { - return; - } - - $this->recache_forms = false; - /** @var Cache $cache */ $cache = $this->grav['cache']; diff --git a/plugins/login-oauth2-extras/CHANGELOG.md b/plugins/login-oauth2-extras/CHANGELOG.md new file mode 100644 index 0000000..e303eb9 --- /dev/null +++ b/plugins/login-oauth2-extras/CHANGELOG.md @@ -0,0 +1,43 @@ +# v2.2.0 +## 03/30/2022 + +1. [](#new) + * Added Okta provider [#7](https://github.com/trilbymedia/grav-plugin-login-oauth2-extras/pull/7) +2. [](#bugfix) + * Fixed issues with TwitchHelix provider [#6](https://github.com/trilbymedia/grav-plugin-login-oauth2-extras/issues/6) + +# v2.1.2 +## 03/16/2022 + +1. [](#new) + * Added Keycloak provider [#5](https://github.com/trilbymedia/grav-plugin-login-oauth2-extras/pull/5) +2. [](#improved) + * Updated Twitch provider to TwitchHelix [#6](https://github.com/trilbymedia/grav-plugin-login-oauth2-extras/issues/6) + * Updated all vendor libraries to latest + +# v2.1.1 +## 12/02/2020 + +1. [](#improved) + * Azure - Add tenant option for OpenID scopes [#3](https://github.com/trilbymedia/grav-plugin-login-oauth2-extras/pull/3) + * Azure - Get profile picture form Azure [#3](https://github.com/trilbymedia/grav-plugin-login-oauth2-extras/pull/3) + * Azure - Get group memberships from Azure [#3](https://github.com/trilbymedia/grav-plugin-login-oauth2-extras/pull/3) + +# v2.1.0 +## 05/11/2020 + +1. [](#new) + * Added Patreon Provider + * Added Azure Provider [#1](https://github.com/trilbymedia/grav-plugin-login-oauth2-extras/pull/1) + +# v2.0.1 +## 04/27/2019 + +1. [](#new) + * Added Twitch Provider + +# v2.0.0 +## 04/26/2019 + +1. [](#new) + * ChangeLog started... diff --git a/plugins/login-oauth2-extras/LICENSE b/plugins/login-oauth2-extras/LICENSE new file mode 100644 index 0000000..c86e4b1 --- /dev/null +++ b/plugins/login-oauth2-extras/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Trilby Media + +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/plugins/login-oauth2-extras/README.md b/plugins/login-oauth2-extras/README.md new file mode 100644 index 0000000..74fc3cd --- /dev/null +++ b/plugins/login-oauth2-extras/README.md @@ -0,0 +1,273 @@ +# Login Login OAuth2 Extras Plugin + +The **Login Login OAuth2 Extras** Plugin is for [Grav CMS](http://github.com/getgrav/grav). This plugin provides extra authenticatoin providers not included in the [Login OAuth2 Plugin](http://github.com/trilbymedia/grav-plugin-login-oauth2). + + +**NOTE:** Please use the same **Callback URIs** and configuration from **Login OAuth2 Plugin**. + +Currently the plugin supports the following providers: + +* **GitLab:** - https://docs.gitlab.com/ee/integration/oauth_provider.html +* **Discord:** - https://extrasapp.com/developers/docs/topics/oauth2 +* **Slack:** - https://api.slack.com/docs/sign-in-with-slack +* **Jira:** - https://developer.atlassian.com/server/jira/platform/oauth/ +* **Twitch** - https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/ +* **Azure** - https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app +* **Patreon** - https://docs.patreon.com/#oauth +* **Keycloak** - https://github.com/stevenmaguire/oauth2-keycloak +* **Okta** - https://github.com/foxworth42/oauth2-okta + +If you wish to add a new provider, please open a pull request against this repo. + +## Installation + +Installing the Login Login OAuth2 Extras plugin can be done in one of two ways. The GPM (Grav Package Manager) installation method enables you to quickly and easily install the plugin with a simple terminal command, while the manual method enables you to do so via a zip file. + +The simplest way to install this plugin is via the [Grav Package Manager (GPM)](http://learn.getgrav.org/advanced/grav-gpm) through your system's terminal (also called the command line). From the root of your Grav install type: + + bin/gpm install login-oauth2-extras + +This will install the Login Login OAuth2 Extras plugin into your `/user/plugins` directory within Grav. Its files can be found under `/your/site/grav/user/plugins/login-oauth2-extras`. + +## Configuration + +Before configuring this plugin, you should copy the `user/plugins/login-oauth2-extras/login-oauth2-extras.yaml` to `user/config/plugins/login-oauth2-extras.yaml` and only edit that copy. + +Here is the default configuration and an explanation of available options: + +```yaml +enabled: true +built_in_css: true +providers: + gitlab: + enabled: false + client_id: '' + client_secret: '' + domain: + options: + scope: ['read_user', 'openid'] + discord: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['identify', 'email'] + slack: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['users:read', 'users:read.email'] + jira: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['read:jira-user'] + twitch: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['user_read'] + azure: + enabled: false + tenant: 'common' + client_id: '' + client_secret: '' + options: + scope: ['openid', 'email', 'profile', 'offline_access', 'User.Read'] + get_groups: false + avatar_max_size: 240 + patreon: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['users'] + keycloak: + enabled: false + authserver_url: '' + realm: '' + client_id: '' + client_secret: '' + options: + scope: ['users'] + userdata_login: '' + userdata_fullname: '' + userdata_email: '' + okta: + enabled: false + client_id: + client_secret: + issuer: + options: + scope: ['openid', 'email', 'profile'] + + +admin: + enabled: true + built_in_css: true + providers: + gitlab: + enabled: false + client_id: '' + client_secret: '' + domain: + options: + scope: ['read_user', 'openid'] + discord: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['identify', 'email'] + slack: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['users:read', 'users:read.email'] + jira: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['read:jira-user'] + twitch: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['user_read'] + azure: + enabled: false + tenant: 'common' + client_id: '' + client_secret: '' + options: + scope: ['openid', 'email', 'profile', 'offline_access', 'User.Read'] + get_groups: false + avatar_max_size: 240 + patreon: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['users'] + keycloak: + enabled: false + authserver_url: '' + realm: '' + client_id: '' + client_secret: '' + options: + scope: ['users'] + userdata_login: '' + userdata_fullname: '' + userdata_email: '' + okta: + enabled: false + client_id: + client_secret: + issuer: + options: + scope: ['openid', 'email', 'profile'] +``` + +Note that if you use the admin plugin, a file with your configuration, and named login-oauth2-extras.yaml will be saved in the `user/config/plugins/` folder once the configuration is saved in the admin. + +### OAuth2 Providers + +#### GitLab + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| `true` \| [default: `false`] | +|client_id|The **Client ID** Provided by GitLab when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by GitLab when you register an application for OAuth2 authentication | `` | +|domain|A custom GitLab domain| `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['read_user', 'openid']` | + +#### Discord + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| `true` \| [default: `false`] | +|client_id|The **Client ID** Provided by Discord when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by Discord when you register an application for OAuth2 authentication | `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['identify', 'email']` | + +#### Slack + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| `true` \| [default: `false`] | +|client_id|The **Client ID** Provided by Slack when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by Slack when you register an application for OAuth2 authentication | `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['users:read', 'users:read.email']` | + +#### Jira + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| `true` \| [default: `false`] | +|client_id|The **Client ID** Provided by Jira when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by Jira when you register an application for OAuth2 authentication | `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['read:jira-user']` | + +#### Twitch + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| `true` \| [default: `false`] | +|client_id|The **Client ID** Provided by Twitch when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by Twitch when you register an application for OAuth2 authentication | `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['user_read']` | + +#### Azure + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| `true` \| [default: `false`] | +|tenant|The **Tenant ID** of your Azure AD tenant that you want to use. Use 'common' for all users, 'organizations' for Azure AD work or school accounts, 'consumers' for personal Microsoft accounts or a tenant id for accounts from a single Azure AD tenant.|`common`, `organizations`, `consumers`, e.g. `58673e44-617a-4d61-88b5-fb480759a841`| +|client_id|The **Client ID** Provided by Azure when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by Azure when you register an application for OAuth2 authentication | `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['openid', 'email', 'profile', 'offline_access', 'User.Read']` | +|get_groups|Add all the groups from Azure to the users, which includes transitive memberships. This needs at least the `GroupMember.Read.All` scope as well, which needs admin consent. **Warning**: if you save the users the groups will only be added, but not removed.| `true` \| [default: `false`] | +|avatar_max_size|The maximum size in pixels of the avatar to store. Azure does not provide all sizes, only 48x48, 64x64, 96x96, 120x120, 240x240, 360x360, 432x432, 504x504, and 648x648. | e.g. `240` | + +#### Patreon + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| `true` \| [default: `false`] | +|client_id|The **Client ID** Provided by Patreon when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by Patreon when you register an application for OAuth2 authentication | `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['users']` | + +#### Keycloak + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| `true` \| [default: `false`] | +|authserver_url| The **AuthServer URL** of your Keycloak server that you want to use. |`` | +|realm| The **Realm** of your Keycloak server that you want to use. |`` | +|client_id|The **Client ID** Provided by Keycloak when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by Keycloak when you register an application for OAuth2 authentication | `` | +|encryption_algorithm| The **Encryption Algorithm** to be used, if your Keycloak instance is configured to use encryption. |`` \| e.g. `RS256` | +|encryption_key| The contents of your public key or certificate that should be used for decryption, if your Keycloak instance is configured to use encryption. |`` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['users']` | +|userdata_login| The **Login** key of the Keycloak user data.|`` | +|userdata_fullname| The user's **full name** key of the Keycloak user data.|`` \| e.g. `name` | +|userdata_email| The user's **email address** key of the Keycloak user data.|`` \| e.g. `email` | + +#### Okta + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +| enabled | Enable or disable this specific provider. This stops its showing as an valid login option | `true` \| [default: `false`] | +| client_id | The **Client ID** Provided by Okta when you register an application for OAuth2 authentication | `` | +| client_secret | The **Client Secret** Provided by Okta when you register an application for OAuth2 authentication | `` | +| issuer | The **Issuer** Provided by Okta when you register an application for OAuth2 authentication | `` | +| scope | An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | default: `['openid', 'email', 'profile']` | diff --git a/plugins/login-oauth2-extras/blueprints.yaml b/plugins/login-oauth2-extras/blueprints.yaml new file mode 100644 index 0000000..2d9f284 --- /dev/null +++ b/plugins/login-oauth2-extras/blueprints.yaml @@ -0,0 +1,1006 @@ +name: Login OAuth2 Extras +type: plugin +slug: login-oauth2-extras +version: 2.2.0 +description: Extra Login OAuth2 Providers (requires Login OAuth2 Plugin) +icon: plug +author: + name: Trilby Media + email: hello@trilby.media +homepage: https://github.com/trilbymedia/grav-plugin-login-oauth2-extras +demo: http://demo.yoursite.com +keywords: grav, plugin, etc +bugs: https://github.com/trilbymedia/grav-plugin-login-oauth2-extras/issues +docs: https://github.com/trilbymedia/grav-plugin-login-oauth2-extras/blob/develop/README.md +license: MIT +dependencies: + - { name: login-oauth2, version: '~2.0' } + +form: + validation: strict + fields: + enabled: + type: toggle + label: Plugin Status + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + instructions: + type: display + markdown: true + description: This plugin requires [Login OAuth2](/admin/plugins/login-oauth2) to function. There are several settings that must be set in that plugin to ensure these extra providers will function (`Configuration` and `Admin`) + + built_in_css: + type: toggle + label: PLUGIN_LOGIN_OAUTH2.BUILTIN_CSS + help: PLUGIN_LOGIN_OAUTH2.BUILTIN_CSS_HELP + highlight: 1 + default: 1 + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + + gitlab: + type: fieldset + title: GitLab + collapsible: true + + fields: + + gitlab_columns: + type: columns + + fields: + + gitlab_column_left: + type: column + + fields: + + gitlab.site: + type: display + style: vertical + content: '

Site

' + + providers.gitlab.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.gitlab.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.gitlab.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.gitlab.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.gitlab.domain: + type: text + label: PLUGIN_LOGIN_OAUTH2.RESTRICT_DOMAIN + placeholder: https://my.gitlab.example + + + gitlab_column_right: + type: column + + fields: + + gitlab.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.gitlab.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.gitlab.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.gitlab.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.gitlab.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + admin.providers.gitlab.domain: + type: text + label: PLUGIN_LOGIN_OAUTH2.RESTRICT_DOMAIN + placeholder: https://my.gitlab.example + + providers.gitlab.description: + type: display + style: vertical + content: '[ GitLab OAuth2 from the official documentation](https://docs.gitlab.com/ee/integration/oauth_provider.html?target=_blank)' + markdown: true + + discord: + type: fieldset + title: Discord + collapsible: true + + fields: + + discord_columns: + type: columns + + fields: + + discord_column_left: + type: column + + fields: + + discord.site: + type: display + style: vertical + content: '

Site

' + + providers.discord.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.discord.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.discord.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.discord.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + discord_column_right: + type: column + + fields: + + discord.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.discord.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.discord.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.discord.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.discord.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.discord.description: + type: display + style: vertical + content: '[ Discord OAuth2 from the official documentation](https://extrasapp.com/developers/docs/topics/oauth2?target=_blank)' + markdown: true + + slack: + type: fieldset + title: Slack + collapsible: true + + fields: + + slack_columns: + type: columns + + fields: + + slack_column_left: + type: column + + fields: + + slack.site: + type: display + style: vertical + content: '

Site

' + + providers.slack.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.slack.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.slack.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.slack.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + slack_column_right: + type: column + + fields: + + slack.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.slack.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.slack.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.slack.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.slack.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.slack.description: + type: display + style: vertical + content: '[ Slack OAuth2 from the official documentation](https://api.slack.com/docs/sign-in-with-slack?target=_blank)' + markdown: true + + jira: + type: fieldset + title: Jira + collapsible: true + + fields: + + jira_columns: + type: columns + + fields: + + jira_column_left: + type: column + + fields: + + jira.site: + type: display + style: vertical + content: '

Site

' + + providers.jira.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.jira.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.jira.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.jira.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + jira_column_right: + type: column + + fields: + + jira.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.jira.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.jira.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.jira.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.jira.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.jira.description: + type: display + style: vertical + content: '[ Jira OAuth2 from the official documentation](https://developer.atlassian.com/server/jira/platform/oauth/?target=_blank)' + markdown: true + + twitch: + type: fieldset + title: Twitch + collapsible: true + + fields: + + twitch_columns: + type: columns + + fields: + + twitch_column_left: + type: column + + fields: + + twitch.site: + type: display + style: vertical + content: '

Site

' + + providers.twitch.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.twitch.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.twitch.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.twitch.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + twitch_column_right: + type: column + + fields: + + twitch.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.twitch.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.twitch.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.twitch.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.twitch.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.twitch.description: + type: display + style: vertical + content: '[ Twitch OAuth2 from the official documentation](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/?target=_blank)' + markdown: true + + azure: + type: fieldset + title: Azure + collapsible: true + + fields: + + azure_columns: + type: columns + + fields: + + azure_column_left: + type: column + + fields: + + azure.site: + type: display + style: vertical + content: '

Site

' + + providers.azure.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.azure.tenant: + type: text + label: Tenant ID + help: Use 'common' for all users, 'organizations' for Azure AD work or school accounts, 'consumers' for personal Microsoft accounts or a tenant id for accounts from a single Azure AD tenant. + + providers.azure.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.azure.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.azure.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.azure.options.get_groups: + type: toggle + label: Get groups + help: Add all the groups from Azure to the users, which includes transitive memberships. This needs at least the 'GroupMember.Read.All' scope as well, which needs admin consent. + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.azure.options.avatar_max_size: + type: number + size: x-small + append: px + label: Maximum avatar size + help: Azure does not provide all sizes, only certain pre-defined ones. The minimum size is 48px, the maximum 648px. + validate: + type: number + min: 48 + max: 648 + + azure_column_right: + type: column + + fields: + + azure.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.azure.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.azure.tenant: + type: text + label: Tenant ID + help: Use 'common' for all users, 'organizations' for Azure AD work or school accounts, 'consumers' for personal Microsoft accounts or a tenant id for accounts from a single Azure AD tenant. + + admin.providers.azure.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.azure.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.azure.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + admin.providers.azure.options.get_groups: + type: toggle + label: Get groups + help: Add all the groups from Azure to the users, which includes transitive memberships. This needs at least the 'GroupMember.Read.All' scope as well, which needs admin consent. + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.azure.options.avatar_max_size: + type: number + size: x-small + append: px + label: Maximum avatar size + help: Azure does not provide all sizes, only certain pre-defined ones. The minimum size is 48px, the maximum 648px. + validate: + type: number + min: 48 + max: 648 + + providers.azure.description: + type: display + style: vertical + content: '[ Quickstart: Register an application with the Microsoft identity platform](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app). Make sure you create a client secret for the authorization code flow.' + markdown: true + + patreon: + type: fieldset + title: Patreon + collapsible: true + + fields: + + patreon_columns: + type: columns + + fields: + + patreon_column_left: + type: column + + fields: + + patreon.site: + type: display + style: vertical + content: '

Site

' + + providers.patreon.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.patreon.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.patreon.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.patreon.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + patreon_column_right: + type: column + + fields: + + patreon.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.patreon.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.patreon.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.patreon.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.patreon.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.patreon.description: + type: display + style: vertical + content: '[ Patreon OAuth2 from the official documentation](https://docs.patreon.com/#oauth?target=_blank)' + markdown: true + keycloak: + type: fieldset + title: Keycloak + collapsible: true + + fields: + + keycloak_columns: + type: columns + + fields: + + keycloak_column_left: + type: column + + fields: + + keycloak.site: + type: display + style: vertical + content: '

Site

' + + providers.keycloak.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.keycloak.realm: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.REALM + + providers.keycloak.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.keycloak.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.keycloak.authserver_url: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.AUTHSERVER_URL + + providers.keycloak.encryption_algorithm: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.ENCRYPTION_ALGORITHM + + providers.keycloak.encryption_key: + type: textarea + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.ENCRYPTION_KEY + + providers.keycloak.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.keycloak.userdata_login: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.USERDATA_LOGIN + + providers.keycloak.userdata_fullname: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.USERDATA_FULLNAME + + providers.keycloak.userdata_email: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.USERDATA_EMAIL + + keycloak_column_right: + type: column + + fields: + + keycloak.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.keycloak.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.keycloak.realm: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.REALM + + admin.providers.keycloak.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.keycloak.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.keycloak.authserver_url: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.AUTHSERVER_URL + + admin.providers.keycloak.encryption_algorithm: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.ENCRYPTION_ALGORITHM + + admin.providers.keycloak.encryption_key: + type: textarea + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.ENCRYPTION_KEY + + admin.providers.keycloak.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + admin.providers.keycloak.userdata_login: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.USERDATA_LOGIN + + admin.providers.keycloak.userdata_fullname: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.USERDATA_FULLNAME + + admin.providers.keycloak.userdata_email: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.USERDATA_EMAIL + + providers.keycloak.description: + type: display + style: vertical + content: '[ Keycloak Provider for OAuth2](https://github.com/stevenmaguire/oauth2-keycloak?target=_blank)' + markdown: true + + okta: + type: fieldset + title: Okta + collapsible: true + + fields: + + okta_columns: + type: columns + + fields: + + okta_column_left: + type: column + + fields: + + okta.site: + type: display + style: vertical + content: '

Site

' + + providers.okta.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.okta.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.okta.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.okta.issuer: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.OKTA.ISSUER + + providers.okta.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + okta_column_right: + type: column + + fields: + + okta.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.okta.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.okta.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.okta.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.okta.issuer: + type: text + label: PLUGIN_LOGIN_OAUTH2_EXTRAS.OKTA.ISSUER + + admin.providers.okta.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.okta.description: + type: display + style: vertical + content: '[ Okta for OAuth2](https://github.com/foxworth42/oauth2-okta?target=_blank)' + markdown: true diff --git a/plugins/login-oauth2-extras/classes/Providers/AzureProvider.php b/plugins/login-oauth2-extras/classes/Providers/AzureProvider.php new file mode 100644 index 0000000..0776103 --- /dev/null +++ b/plugins/login-oauth2-extras/classes/Providers/AzureProvider.php @@ -0,0 +1,186 @@ + $this->config->get('providers.azure.client_id'), + 'clientSecret' => $this->config->get('providers.azure.client_secret'), + 'tenant' => $this->config->get('providers.azure.tenant'), + // Get access tokens for the Microsoft Graph API instead of the old Azure AD Graph. + 'urlAPI' => 'https://graph.microsoft.com', + 'resource' => 'https://graph.microsoft.com', + 'redirectUri' => $this->getCallbackUri(), + ]; + + parent::initProvider($options); + } + + public function getAuthorizationUrl() + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.azure.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + public function getUserData($user) + { + $name = $user->claim('name'); + $data_user = [ + 'id' => $user->getId(), + 'login' => $user->getUpn(), + 'fullname' => $name, + 'email' => $user->claim('email') ?: $user->getUpn(), + 'azure' => [ + // The avatar can be set by using avatar_url or avatar. + // Technically we're not setting a url because pictures from Azure are not public, so this contains a + // data url with a base64 encoded image. + 'avatar' => $this->getAvatar($name), + 'issuer' => $user->claim('iss'), + 'tenant' => $user->getTenantId(), + ] + ]; + + $getGroups = $this->config->get('providers.azure.options.get_groups'); + if ($getGroups) + { + $data_user['groups'] = $this->getUserGroups($name); + } + + return $data_user; + } + + public function getAvatar($name) + { + $avatarMaxSize = $this->config->get('providers.azure.options.avatar_max_size'); + // This should already be validated to be at least 48, because that's the lowest available resolution, but just + // to be sure. + if ($avatarMaxSize < 48) + { + $avatarMaxSize = 48; + } + + // First get the meta information for all the available pictures, there are versions from 48x48 to 648x648, + // depending on the size uploaded by the user. + // Use the beta endpoint to get the profile picture as the v1.0 endpoint only returns the picture if the user + // has a mailbox. See https://docs.microsoft.com/en-us/graph/known-issues#users + $photoMetaUrl = 'https://graph.microsoft.com/beta/me/photos/'; + try + { + $photoMetaList = $this->provider->get($photoMetaUrl, $this->token); + } + catch (IdentityProviderException $e) + { + // User seems to have no picture. + Grav::instance()['log']->info('AzureProvider: failed to get photo for user \'' . $name . + '\'. Exception message: ' . $e->getMessage()); + return null; + } + + // Limit picture size by width or height, depending on which is larger. + $comparisonProperty = $photoMetaList[0]['height'] > $photoMetaList[0]['width'] ? 'height' : 'width'; + + // Filter pictures by maximum size that was configured. + $photoMetaList = array_filter( + $photoMetaList, + function ($photoMeta) use ($comparisonProperty, $avatarMaxSize) + { + return $photoMeta[$comparisonProperty] <= $avatarMaxSize; + } + ); + + // Get the metadata for the largest remaining picture. + $photoMeta = array_reduce( + $photoMetaList, + function($carry, $item) use ($comparisonProperty){ + return $carry[$comparisonProperty] < $item[$comparisonProperty] ? $item : $carry; + }, + [$comparisonProperty => -PHP_INT_MAX] + ); + + // Get the actual picture. + $photoUrl = $photoMetaUrl . $photoMeta['id'] . '/$value'; + try + { + $photo = $this->provider->get($photoUrl, $this->token); + } + catch (IdentityProviderException $e) + { + // Getting the picture failed even though getting the meta succeeded. + Grav::instance()['log']->error('AzureProvider: failed to get photo for user \'' . $name . + '\'. Exception message: ' . $e->getMessage()); + return null; + } + + // Use a data url with a base64 encoded image since we need to provide a url for the avatar. + return 'data:' . $photoMeta['@odata.mediaContentType'] . ';base64,' . base64_encode($photo); + } + + public function getUserGroups($name) + { + // Get the ids to the groups a user is member of, including transitive memberships. + $graphUrl = 'https://graph.microsoft.com/v1.0/'; + $memberGroupsUri = $graphUrl . 'me/getMemberGroups'; + $body = [ 'securityEnabledOnly' => true ]; + try + { + $groupIds = $this->provider->post($memberGroupsUri, $body, $this->token); + } + catch (IdentityProviderException $e) + { + // User might not be able to join any groups (e.g. personal Microsoft account). + Grav::instance()['log']->info('AzureProvider: cannot get groups for user \'' . $name . + '\'. Exception message: ' . $e->getMessage()); + return array(); + } + + // Get the whole group objects for each id in parallel by abusing Guzzle promises. + // Implementing this kind of parallelism in the lower level oauth2-azure and oauth2-client libraries would be + // better, but that might take a while, so doing it this way is faster for now. + + // Start the requests to Microsoft Graph. + $promises = array(); + foreach ($groupIds as $groupId) + { + $groupUrl = $graphUrl . 'groups/' . $groupId; + $promises[$groupId] = Promise\task( + function () use ($groupUrl) + { + return $this->provider->get($groupUrl, $this->token); + } + ); + } + + // Wait until all the requests complete. + $results = Promise\settle($promises)->wait(); + + // Get the actual groups or error messages from each request. + $groups = array(); + foreach ($results as $groupId => $result) + { + if($result['state'] === Promise\PromiseInterface::FULFILLED) + { + $groups[$groupId] = $result['value']; + } + else + { + $message = $result['reason']->getMessage(); + Grav::instance()['log']->error( + 'AzureProvider: failed to get name for group \'' . $groupId . '\'. Exception message: ' . $message); + } + } + + // Extract the names from the group objects + return array_column($groups, 'displayName'); + } +} diff --git a/plugins/login-oauth2-extras/classes/Providers/DiscordProvider.php b/plugins/login-oauth2-extras/classes/Providers/DiscordProvider.php new file mode 100644 index 0000000..fbbb7b6 --- /dev/null +++ b/plugins/login-oauth2-extras/classes/Providers/DiscordProvider.php @@ -0,0 +1,50 @@ + $this->config->get('providers.discord.client_id'), + 'clientSecret' => $this->config->get('providers.discord.client_secret'), + 'redirectUri' => $this->getCallbackUri(), + ]; + + parent::initProvider($options); + } + + public function getAuthorizationUrl() + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.discord.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + public function getUserData($user) + { + $data = $user->toArray(); + + $avatar_url = "https://cdn.discordapp.com/avatars/{$data['id']}/{$data['avatar']}.jpg"; + + $data_user = [ + 'id' => $user->getId(), + 'login' => $user->getUsername(), + 'fullname' => $user->getUsername(), + 'email' => $user->getEmail(), + 'discord' => [ + 'discriminator' => $data['discriminator'], + 'verified' => $data['verified'], + 'locale' => $data['locale'], + 'mfa_enabled' => $data['mfa_enabled'], + 'avatar_url' => $avatar_url, + ] + ]; + + return $data_user; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2-extras/classes/Providers/ExtraProvider.php b/plugins/login-oauth2-extras/classes/Providers/ExtraProvider.php new file mode 100644 index 0000000..a4718bd --- /dev/null +++ b/plugins/login-oauth2-extras/classes/Providers/ExtraProvider.php @@ -0,0 +1,25 @@ +isAdmin(); + $this->config = new Data(Grav::instance()['config']->get('plugins.login-oauth2-extras' . ($admin ? '.admin' : ''))); + } + + public function getAuthorizationUrl() + { + + } + + public function getUserData($user) + { + + } +} \ No newline at end of file diff --git a/plugins/login-oauth2-extras/classes/Providers/GitlabProvider.php b/plugins/login-oauth2-extras/classes/Providers/GitlabProvider.php new file mode 100644 index 0000000..41ce3bb --- /dev/null +++ b/plugins/login-oauth2-extras/classes/Providers/GitlabProvider.php @@ -0,0 +1,55 @@ +config->get('providers.gitlab.domain', false); + + $options += [ + 'clientId' => $this->config->get('providers.gitlab.client_id'), + 'clientSecret' => $this->config->get('providers.gitlab.client_secret'), + ]; + + if ($domain) { + $options += ['domain' => $domain]; + } + + parent::initProvider($options); + } + + public function getAuthorizationUrl() + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.gitlab.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + public function getUserData($user) + { + $data = $user->toArray(); + + $data_user = [ + 'id' => $user->getId(), + 'login' => $user->getUsername(), + 'fullname' => $user->getName(), + 'email' => $user->getEmail(), + 'gitlab' => [ + 'domain' => $user->getDomain(), + 'location' => $data['location'], + 'web_url' => $user->getProfileUrl(), + 'avatar_url' => $user->getAvatarUrl(), + 'active' => $user->isActive(), + 'external' => $user->isExternal(), + 'admin' => $user->isAdmin() + ] + ]; + + return $data_user; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2-extras/classes/Providers/JiraProvider.php b/plugins/login-oauth2-extras/classes/Providers/JiraProvider.php new file mode 100644 index 0000000..140cec1 --- /dev/null +++ b/plugins/login-oauth2-extras/classes/Providers/JiraProvider.php @@ -0,0 +1,43 @@ + $this->config->get('providers.jira.client_id'), + 'clientSecret' => $this->config->get('providers.jira.client_secret'), + 'redirectUri' => $this->getCallbackUri(), + ]; + + parent::initProvider($options); + } + + public function getAuthorizationUrl() + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.jira.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + public function getUserData($user) + { + $data_user = [ + 'id' => $user->getId(), + 'login' => $user->getName(), + 'fullname' => $user->getName(), + 'email' => $user->getEmail(), + 'jira' => [ + 'company' => $user->getName(), + 'avatar_url' => $user->getAvatarUrl(), + ], + ]; + + return $data_user; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2-extras/classes/Providers/KeycloakProvider.php b/plugins/login-oauth2-extras/classes/Providers/KeycloakProvider.php new file mode 100644 index 0000000..9f68e51 --- /dev/null +++ b/plugins/login-oauth2-extras/classes/Providers/KeycloakProvider.php @@ -0,0 +1,53 @@ + $this->config->get('providers.keycloak.realm'), + 'clientId' => $this->config->get('providers.keycloak.client_id'), + 'clientSecret' => $this->config->get('providers.keycloak.client_secret'), + 'authServerUrl' => $this->config->get('providers.keycloak.authserver_url'), + 'encryptionAlgorithm' => $this->config->get('providers.keycloak.encryption_algorithm'), + 'encryptionKey' => $this->config->get('providers.keycloak.encryption_key'), + ]; + + parent::initProvider($options); + } + + /** + * @return string + */ + public function getAuthorizationUrl(): string + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.keycloak.options.scope'); + return $this->provider->getAuthorizationUrl($options); + } + + public function getUserData($user): array + { + $data = $user->toArray(); + $data_user = [ + 'id' => $user->getId(), + 'login' => $data[$this->config->get('providers.keycloak.userdata_login')], + 'fullname' => $data[$this->config->get('providers.keycloak.userdata_fullname')], + 'email' => $data[$this->config->get('providers.keycloak.userdata_email')], + 'keycloak' => $data, + ]; + + return $data_user; + } +} diff --git a/plugins/login-oauth2-extras/classes/Providers/OktaProvider.php b/plugins/login-oauth2-extras/classes/Providers/OktaProvider.php new file mode 100644 index 0000000..337ca7f --- /dev/null +++ b/plugins/login-oauth2-extras/classes/Providers/OktaProvider.php @@ -0,0 +1,43 @@ + $this->config->get('providers.okta.client_id'), + 'clientSecret' => $this->config->get('providers.okta.client_secret'), + 'issuer' => $this->config->get('providers.okta.issuer') + ]; + + parent::initProvider($options); + } + + public function getAuthorizationUrl() + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.okta.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + public function getUserData($user) + { + $data_user = [ + 'id' => $user->getId(), + 'login' => $user->getPreferredUsername(), + 'fullname' => $user->getName(), + 'email' => $user->getEmail(), + 'okta' => [ + 'zone_info' => $user->getZoneInfo(), + 'locale' => $user->getLocale() + ] + ]; + + return $data_user; + } +} diff --git a/plugins/login-oauth2-extras/classes/Providers/PatreonProvider.php b/plugins/login-oauth2-extras/classes/Providers/PatreonProvider.php new file mode 100644 index 0000000..6bd2f82 --- /dev/null +++ b/plugins/login-oauth2-extras/classes/Providers/PatreonProvider.php @@ -0,0 +1,45 @@ + $this->config->get('providers.patreon.client_id'), + 'clientSecret' => $this->config->get('providers.patreon.client_secret'), + 'redirectUri' => $this->getCallbackUri(), + ]; + + parent::initProvider($options); + } + + public function getAuthorizationUrl() + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.patreon.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + public function getUserData($user) + { + $data = $user->toArray(); + + $data_user = [ + 'id' => $user->getId(), + 'login' => $data['email'], + 'fullname' => $data['full_name'], + 'email' => $data['email'], + 'patreon' => [ + 'avatar_url' => $user->getAvatar(), + 'url' => $data['url'], + ] + ]; + + return $data_user; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2-extras/classes/Providers/SlackProvider.php b/plugins/login-oauth2-extras/classes/Providers/SlackProvider.php new file mode 100644 index 0000000..7ce0a29 --- /dev/null +++ b/plugins/login-oauth2-extras/classes/Providers/SlackProvider.php @@ -0,0 +1,45 @@ + $this->config->get('providers.slack.client_id'), + 'clientSecret' => $this->config->get('providers.slack.client_secret'), + 'redirectUri' => $this->getCallbackUri(), + ]; + + parent::initProvider($options); + } + + public function getAuthorizationUrl() + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.slack.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + public function getUserData($user) + { + $data = $user->toArray(); + + $data_user = [ + 'id' => $user->getId(), + 'login' => $user->getName(), + 'fullname' => $data['user']['profile']['real_name'], + 'email' => $user->getEmail(), + 'slack' => [ + 'location' => $data['user']['tz'], + 'avatar_url' => $data['user']['profile']['image_512'], + ] + ]; + + return $data_user; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2-extras/classes/Providers/TwitchProvider.php b/plugins/login-oauth2-extras/classes/Providers/TwitchProvider.php new file mode 100644 index 0000000..03dbe04 --- /dev/null +++ b/plugins/login-oauth2-extras/classes/Providers/TwitchProvider.php @@ -0,0 +1,45 @@ + $this->config->get('providers.twitch.client_id'), + 'clientSecret' => $this->config->get('providers.twitch.client_secret'), + 'redirectUri' => $this->getCallbackUri(), + ]; + + parent::initProvider($options); + } + + public function getAuthorizationUrl() + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.twitch.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + public function getUserData($user) + { + $data_user = [ + 'id' => $user->getId(), + 'login' => $user->getLogin(), + 'fullname' => $user->getDisplayName(), + 'email' => $user->getEmail(), + 'twitch' => [ + 'avatar_url' => $user->getProfileImageUrl(), + 'bio' => $user->getDescription(), + 'type' => $user->getType() + ] + ]; + + return $data_user; + } + +} \ No newline at end of file diff --git a/plugins/login-oauth2-extras/composer.json b/plugins/login-oauth2-extras/composer.json new file mode 100644 index 0000000..5d36863 --- /dev/null +++ b/plugins/login-oauth2-extras/composer.json @@ -0,0 +1,28 @@ +{ + "require": { + "wohali/oauth2-discord-new": "^1.0", + "adam-paterson/oauth2-slack": "^1.1", + "mrjoops/oauth2-jira": "^0.2.4", + "omines/oauth2-gitlab": "^3.1", + "thenetworg/oauth2-azure": "^1.4", + "gravure/oauth2-patreon": "dev-master", + "guzzlehttp/promises": "^1.3", + "vertisan/oauth2-twitch-helix": "^1.1", + "stevenmaguire/oauth2-keycloak": "^3.0", + "foxworth42/oauth2-okta": "^1.0" + }, + "replace": { + "league/oauth2-client": "*", + "paragonie/random_compat": "*", + "psr/http-message": "*", + "guzzlehttp/psr7": "*", + "guzzlehttp/promises": "*", + "guzzlehttp/guzzle": "*" + + }, + "autoload": { + "psr-4": { + "Grav\\Plugin\\Login\\OAuth2\\": "classes/" + } + } +} diff --git a/plugins/login-oauth2-extras/composer.lock b/plugins/login-oauth2-extras/composer.lock new file mode 100644 index 0000000..04ba6df --- /dev/null +++ b/plugins/login-oauth2-extras/composer.lock @@ -0,0 +1,593 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "675a0c1d9fd5a72913e53019ec35ea31", + "packages": [ + { + "name": "adam-paterson/oauth2-slack", + "version": "1.1.3", + "source": { + "type": "git", + "url": "https://github.com/adam-paterson/oauth2-slack.git", + "reference": "ccc329eb3036a89d110227a4137e15d4a5661678" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/adam-paterson/oauth2-slack/zipball/ccc329eb3036a89d110227a4137e15d4a5661678", + "reference": "ccc329eb3036a89d110227a4137e15d4a5661678", + "shasum": "" + }, + "require": { + "league/oauth2-client": "1.*|2.*", + "php": ">=5.6.0" + }, + "require-dev": { + "mockery/mockery": "~0.9", + "phpunit/phpunit": "5.6", + "squizlabs/php_codesniffer": "~2.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "AdamPaterson\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Adam Paterson", + "email": "hello@adampaterson.co.uk" + } + ], + "description": "Slack OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "Authentication", + "SSO", + "authorization", + "identity", + "idp", + "oauth", + "oauth2", + "single sign on", + "slack", + "slack api" + ], + "support": { + "issues": "https://github.com/adam-paterson/oauth2-slack/issues", + "source": "https://github.com/adam-paterson/oauth2-slack/tree/master" + }, + "time": "2017-06-20T14:43:31+00:00" + }, + { + "name": "firebase/php-jwt", + "version": "v5.5.1", + "source": { + "type": "git", + "url": "https://github.com/firebase/php-jwt.git", + "reference": "83b609028194aa042ea33b5af2d41a7427de80e6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/firebase/php-jwt/zipball/83b609028194aa042ea33b5af2d41a7427de80e6", + "reference": "83b609028194aa042ea33b5af2d41a7427de80e6", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": ">=4.8 <=9" + }, + "suggest": { + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present" + }, + "type": "library", + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/firebase/php-jwt", + "keywords": [ + "jwt", + "php" + ], + "support": { + "issues": "https://github.com/firebase/php-jwt/issues", + "source": "https://github.com/firebase/php-jwt/tree/v5.5.1" + }, + "time": "2021-11-08T20:18:51+00:00" + }, + { + "name": "foxworth42/oauth2-okta", + "version": "v1.0.2", + "source": { + "type": "git", + "url": "https://github.com/foxworth42/oauth2-okta.git", + "reference": "0e7c2eb68f57eff8aafc4a3f0a1a1ec1c147c946" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/foxworth42/oauth2-okta/zipball/0e7c2eb68f57eff8aafc4a3f0a1a1ec1c147c946", + "reference": "0e7c2eb68f57eff8aafc4a3f0a1a1ec1c147c946", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0", + "php": ">=7.1.0" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^7.0", + "squizlabs/php_codesniffer": "^3.4" + }, + "type": "library", + "autoload": { + "psr-4": { + "Foxworth42\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ed Walker", + "email": "github@foxwire.org" + } + ], + "description": "Okta OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "Authentication", + "authorization", + "client", + "oauth", + "oauth2", + "okta" + ], + "support": { + "issues": "https://github.com/foxworth42/oauth2-okta/issues", + "source": "https://github.com/foxworth42/oauth2-okta/tree/v1.0.2" + }, + "time": "2020-09-28T06:28:26+00:00" + }, + { + "name": "gravure/oauth2-patreon", + "version": "dev-master", + "source": { + "type": "git", + "url": "https://github.com/gravure/oauth2-patreon.git", + "reference": "32c5bb7c6cdfb0cbb4e396ca8e9cbde447f41f47" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/gravure/oauth2-patreon/zipball/32c5bb7c6cdfb0cbb4e396ca8e9cbde447f41f47", + "reference": "32c5bb7c6cdfb0cbb4e396ca8e9cbde447f41f47", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^1.0 || ^2.0", + "php": "5.6.* || >=7.0" + }, + "default-branch": true, + "type": "library", + "autoload": { + "psr-4": { + "Gravure\\Patreon\\Oauth\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Daniël Klabbers", + "email": "daniel@klabbers.email", + "homepage": "http://luceos.com" + } + ], + "description": "Provides Patreon OAuth 2.0 support for PHP League's OAuth 2.0 Client.", + "keywords": [ + "league", + "oauth2", + "patreon" + ], + "support": { + "issues": "https://github.com/gravure/oauth2-patreon/issues", + "source": "https://github.com/gravure/oauth2-patreon" + }, + "time": "2018-02-06T12:41:19+00:00" + }, + { + "name": "mrjoops/oauth2-jira", + "version": "v0.2.4", + "source": { + "type": "git", + "url": "https://github.com/mrjoops/oauth2-jira.git", + "reference": "9c270f7a70ea13c8d844676cddf17977991cb347" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/mrjoops/oauth2-jira/zipball/9c270f7a70ea13c8d844676cddf17977991cb347", + "reference": "9c270f7a70ea13c8d844676cddf17977991cb347", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "mockery/mockery": "^1.2", + "phpunit/phpunit": "^5.0", + "squizlabs/php_codesniffer": "^3.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Mrjoops\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alexandre Lahure", + "email": "alexandre@lahu.re" + } + ], + "description": "Jira OAuth 2.0 support for the PHP League's OAuth 2.0 Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "jira", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/mrjoops/oauth2-jira/issues", + "source": "https://github.com/mrjoops/oauth2-jira/tree/develop" + }, + "time": "2018-11-11T19:49:42+00:00" + }, + { + "name": "omines/oauth2-gitlab", + "version": "3.4.0", + "source": { + "type": "git", + "url": "https://github.com/omines/oauth2-gitlab.git", + "reference": "0c37361c54fae71a85350c445bda1834db5859af" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/omines/oauth2-gitlab/zipball/0c37361c54fae71a85350c445bda1834db5859af", + "reference": "0c37361c54fae71a85350c445bda1834db5859af", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.4.1", + "php": ">=7.2" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.0", + "guzzlehttp/psr7": "^1.6", + "http-interop/http-factory-guzzle": "^1.0", + "m4tthumphrey/php-gitlab-api": "^10.0|^11.0", + "mockery/mockery": "^1.0", + "php-http/guzzle7-adapter": "^0.1", + "phpunit/phpunit": "^8.0|^9.0" + }, + "suggest": { + "m4tthumphrey/php-gitlab-api": "For further API usage using the acquired OAuth2 token" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Omines\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Niels Keurentjes", + "email": "niels.keurentjes@omines.com", + "homepage": "https://www.omines.nl/" + } + ], + "description": "GitLab OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "gitlab", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/omines/oauth2-gitlab/issues", + "source": "https://github.com/omines/oauth2-gitlab/tree/3.4.0" + }, + "time": "2021-02-08T12:15:55+00:00" + }, + { + "name": "stevenmaguire/oauth2-keycloak", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/stevenmaguire/oauth2-keycloak.git", + "reference": "645b84107b82a08cfed9c101081eb8548ea5be11" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/stevenmaguire/oauth2-keycloak/zipball/645b84107b82a08cfed9c101081eb8548ea5be11", + "reference": "645b84107b82a08cfed9c101081eb8548ea5be11", + "shasum": "" + }, + "require": { + "firebase/php-jwt": "~4.0|~5.0", + "league/oauth2-client": "^2.0 <2.3.0" + }, + "require-dev": { + "mockery/mockery": "~0.9", + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Stevenmaguire\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "description": "Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "keycloak", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/stevenmaguire/oauth2-keycloak/issues", + "source": "https://github.com/stevenmaguire/oauth2-keycloak/tree/3.0.0" + }, + "time": "2022-01-23T18:01:00+00:00" + }, + { + "name": "thenetworg/oauth2-azure", + "version": "v1.4.0", + "source": { + "type": "git", + "url": "https://github.com/TheNetworg/oauth2-azure.git", + "reference": "c57dcb63a925c29e744bffa4a079a95680dd5faf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/TheNetworg/oauth2-azure/zipball/c57dcb63a925c29e744bffa4a079a95680dd5faf", + "reference": "c57dcb63a925c29e744bffa4a079a95680dd5faf", + "shasum": "" + }, + "require": { + "firebase/php-jwt": "~3.0||~4.0||~5.0", + "league/oauth2-client": "~2.0", + "php": ">=5.5.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "TheNetworg\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jan Hajek", + "email": "jan.hajek@thenetw.org", + "homepage": "https://thenetw.org" + } + ], + "description": "Azure Active Directory OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "SSO", + "aad", + "authorization", + "azure", + "azure active directory", + "client", + "microsoft", + "oauth", + "oauth2", + "windows azure" + ], + "support": { + "issues": "https://github.com/TheNetworg/oauth2-azure/issues", + "source": "https://github.com/TheNetworg/oauth2-azure/tree/master" + }, + "time": "2018-10-02T08:54:26+00:00" + }, + { + "name": "vertisan/oauth2-twitch-helix", + "version": "1.1.2", + "source": { + "type": "git", + "url": "https://github.com/vertisan/oauth2-twitch-helix.git", + "reference": "67cac44b4adf113aee026424b435975a026db0e9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/vertisan/oauth2-twitch-helix/zipball/67cac44b4adf113aee026424b435975a026db0e9", + "reference": "67cac44b4adf113aee026424b435975a026db0e9", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.2.1", + "php": ">=5.6.0" + }, + "require-dev": { + "ext-json": "*", + "jakub-onderka/php-parallel-lint": "^1.0", + "mockery/mockery": "^1.2", + "phpunit/phpunit": "^5.7", + "squizlabs/php_codesniffer": "^3.4" + }, + "type": "library", + "autoload": { + "psr-4": { + "Vertisan\\OAuth2\\Client\\Provider\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paweł Farys", + "email": "pmg.farys@gmail.com", + "homepage": "https://github.com/vertisan" + } + ], + "description": "Twitch (new version Helix) OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "client", + "helix", + "league", + "oauth", + "package", + "twitch" + ], + "support": { + "issues": "https://github.com/vertisan/oauth2-twitch-helix/issues", + "source": "https://github.com/vertisan/oauth2-twitch-helix/tree/1.1.2" + }, + "time": "2022-02-03T20:38:26+00:00" + }, + { + "name": "wohali/oauth2-discord-new", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/wohali/oauth2-discord-new.git", + "reference": "0dcb5059cded358f55ae566de9621652cf8542c6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/wohali/oauth2-discord-new/zipball/0dcb5059cded358f55ae566de9621652cf8542c6", + "reference": "0dcb5059cded358f55ae566de9621652cf8542c6", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0" + }, + "conflict": { + "team-reflex/oauth2-discord": ">=1.0" + }, + "require-dev": { + "mockery/mockery": "~1.3.0", + "php-parallel-lint/php-parallel-lint": "~0.9", + "phpunit/phpunit": "~8.0", + "squizlabs/php_codesniffer": "^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Wohali\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Joan Touzet", + "email": "code@atypical.net", + "homepage": "https://github.com/wohali" + } + ], + "description": "Discord OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "discord", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/wohali/oauth2-discord-new/issues", + "source": "https://github.com/wohali/oauth2-discord-new/tree/master" + }, + "time": "2020-06-12T07:27:09+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": { + "gravure/oauth2-patreon": 20 + }, + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [], + "plugin-api-version": "2.2.0" +} diff --git a/plugins/login-oauth2-extras/css/login-oauth2-extras.css b/plugins/login-oauth2-extras/css/login-oauth2-extras.css new file mode 100644 index 0000000..3f2c13b --- /dev/null +++ b/plugins/login-oauth2-extras/css/login-oauth2-extras.css @@ -0,0 +1,64 @@ +.form-oauth2 button.discord { + background: #7289DA; +} +.form-oauth2 button.discord:hover { + background: #687DC7; +} + +.form-oauth2 button.slack { + background: #56B68B; +} +.form-oauth2 button.slack:hover { + background: #3D9D72; +} + +.form-oauth2 button.jira { + background: #0747A6; +} +.form-oauth2 button.jira:hover { + background: #095cd7; +} + +.form-oauth2 button.gitlab { + background: #fc6c26; +} +.form-oauth2 button.gitlab:hover { + background: #E3530D; +} + +.form-oauth2 button.twitch { + background: #6440A4; +} +.form-oauth2 button.twitch:hover { + background: #55368B; +} + +.form-oauth2 button.azure { + background: #2F2F2F; + font-family: Segoe UI, Frutiger, Frutiger Linotype, Dejavu Sans, Helvetica Neue, Arial, sans-serif; + font-weight: 600; +} + +.form-oauth2 button.patreon { + background: #002C49; +} +.form-oauth2 button.patreon:hover { + background: #004674; +} + +.form-oauth2 button.keycloak { + background: #C9C9C9; + color: #333333; +} +.form-oauth2 button.keycloak:hover { + background: #33C6E9; +} + +.form-oauth2 button.okta { + background: #e6e6e6; + color: #333333; +} +.form-oauth2 button.okta:hover { + background: #9ba9bd; +} + diff --git a/plugins/login-oauth2-extras/languages/en.yaml b/plugins/login-oauth2-extras/languages/en.yaml new file mode 100644 index 0000000..41a9fb7 --- /dev/null +++ b/plugins/login-oauth2-extras/languages/en.yaml @@ -0,0 +1,10 @@ +PLUGIN_LOGIN_OAUTH2_EXTRAS: + AUTHSERVER_URL: "Keycloak server URL" + REALM: "Keycloak realm name" + ENCRYPTION_ALGORITHM: "Encryption algorithm" + ENCRYPTION_KEY: "Encryption key or certificate (content)" + USERDATA_LOGIN: "Login key" + USERDATA_FULLNAME: "FullName key" + USERDATA_EMAIL: "Email key" + OKTA: + ISSUER: "Issuer" diff --git a/plugins/login-oauth2-extras/login-oauth2-extras.php b/plugins/login-oauth2-extras/login-oauth2-extras.php new file mode 100644 index 0000000..9666495 --- /dev/null +++ b/plugins/login-oauth2-extras/login-oauth2-extras.php @@ -0,0 +1,109 @@ + [ + ['autoload', 100000], + ['onPluginsInitialized', 0] + ], + 'onTwigLoader' => ['onTwigLoader', 0], + 'onTwigSiteVariables' => ['onTwigSiteVariables', 0], + 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0], + ]; + } + + /** + * Initialize the plugin + */ + public function onPluginsInitialized() + { + if ($this->isAdmin() && $this->grav['config']->get('plugins.login-oauth2.admin.enabled')) { + $this->admin = true; + } + + // Don't proceed if we are in the admin plugin + if ( $this->isAdmin() && !$this->admin) { + return; + } + + $this->addEnabledProviders(); + } + + /** + * [onPluginsInitialized:100000] Composer autoload. + * + * @return ClassLoader + */ + public function autoload() + { + return require __DIR__ . '/vendor/autoload.php'; + } + + public function onTwigLoader() + { + $media_paths = $this->grav['locator']->findResources('plugins://login-oauth2-extras/media'); + foreach(array_reverse($media_paths) as $images_path) { + $this->grav['twig']->addPath($images_path, 'oauth2-media'); + } + } + + /** + * [onTwigTemplatePaths] Add twig paths to plugin templates. + */ + public function onTwigTemplatePaths() + { + $twig = $this->grav['twig']; + $twig->twig_paths[] = __DIR__ . '/templates'; + } + + public function onTwigSiteVariables() + { + // add CSS for frontend if required + if ((!$this->isAdmin() && $this->config->get('plugins.login-oauth2-extras.built_in_css')) || + ($this->admin && $this->config->get('plugins.login-oauth2-extras.admin.built_in_css'))) { + $this->grav['assets']->add('plugin://login-oauth2-extras/css/login-oauth2-extras.css'); + } + } + + protected function addEnabledProviders() + { + if (isset($this->grav['oauth2'])) { + $oauth2 = $this->grav['oauth2']; + + if ($this->admin) { + $providers = $this->config->get('plugins.login-oauth2-extras.admin.providers', []); + } else { + $providers = $this->config->get('plugins.login-oauth2-extras.providers', []); + } + + foreach ($providers as $provider => $options) { + if ($options['enabled']) { + $oauth2->addProvider($provider, $options); + } + } + } + } +} diff --git a/plugins/login-oauth2-extras/login-oauth2-extras.yaml b/plugins/login-oauth2-extras/login-oauth2-extras.yaml new file mode 100644 index 0000000..4d8e179 --- /dev/null +++ b/plugins/login-oauth2-extras/login-oauth2-extras.yaml @@ -0,0 +1,136 @@ +enabled: true +built_in_css: true +providers: + gitlab: + enabled: false + client_id: '' + client_secret: '' + domain: + options: + scope: ['read_user', 'openid'] + discord: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['identify', 'email'] + slack: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['users:read', 'users:read.email'] + jira: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['read:jira-user'] + twitch: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['user_read'] + azure: + enabled: false + tenant: 'common' + client_id: '' + client_secret: '' + options: + scope: ['openid', 'email', 'profile', 'offline_access', 'User.Read'] + get_groups: false + avatar_max_size: 240 + patreon: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['users'] + keycloak: + enabled: false + authserver_url: '' + realm: '' + client_id: '' + client_secret: '' + options: + scope: ['users'] + userdata_login: '' + userdata_fullname: '' + userdata_email: '' + okta: + enabled: false + client_id: + client_secret: + issuer: + options: + scope: ['openid', 'email', 'profile'] + +admin: + enabled: true + built_in_css: true + providers: + gitlab: + enabled: false + client_id: '' + client_secret: '' + domain: + options: + scope: ['read_user', 'openid'] + discord: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['identify', 'email'] + slack: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['users:read', 'users:read.email'] + jira: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['read:jira-user'] + twitch: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['user_read'] + azure: + enabled: false + tenant: 'common' + client_id: '' + client_secret: '' + options: + scope: ['openid', 'email', 'profile', 'offline_access', 'User.Read'] + get_groups: false + avatar_max_size: 240 + patreon: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['users'] + keycloak: + enabled: false + authserver_url: '' + realm: '' + client_id: '' + client_secret: '' + options: + scope: ['users'] + userdata_login: '' + userdata_fullname: '' + userdata_email: '' + okta: + enabled: false + client_id: + client_secret: + issuer: + options: + scope: ['openid', 'email', 'profile'] diff --git a/plugins/login-oauth2-extras/media/azure.svg b/plugins/login-oauth2-extras/media/azure.svg new file mode 100644 index 0000000..1f73976 --- /dev/null +++ b/plugins/login-oauth2-extras/media/azure.svg @@ -0,0 +1 @@ +MS-SymbolLockup \ No newline at end of file diff --git a/plugins/login-oauth2-extras/media/discord.svg b/plugins/login-oauth2-extras/media/discord.svg new file mode 100644 index 0000000..4613aa9 --- /dev/null +++ b/plugins/login-oauth2-extras/media/discord.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/plugins/login-oauth2-extras/media/gitlab.svg b/plugins/login-oauth2-extras/media/gitlab.svg new file mode 100644 index 0000000..2f26efc --- /dev/null +++ b/plugins/login-oauth2-extras/media/gitlab.svg @@ -0,0 +1 @@ +GitLab icon \ No newline at end of file diff --git a/plugins/login-oauth2-extras/media/jira.svg b/plugins/login-oauth2-extras/media/jira.svg new file mode 100644 index 0000000..84c106b --- /dev/null +++ b/plugins/login-oauth2-extras/media/jira.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/plugins/login-oauth2-extras/media/okta.svg b/plugins/login-oauth2-extras/media/okta.svg new file mode 100644 index 0000000..6392b93 --- /dev/null +++ b/plugins/login-oauth2-extras/media/okta.svg @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + diff --git a/plugins/login-oauth2-extras/media/patreon.svg b/plugins/login-oauth2-extras/media/patreon.svg new file mode 100644 index 0000000..176413e --- /dev/null +++ b/plugins/login-oauth2-extras/media/patreon.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/plugins/login-oauth2-extras/media/slack.svg b/plugins/login-oauth2-extras/media/slack.svg new file mode 100644 index 0000000..15a7b9d --- /dev/null +++ b/plugins/login-oauth2-extras/media/slack.svg @@ -0,0 +1 @@ +Slack icon \ No newline at end of file diff --git a/plugins/login-oauth2-extras/media/twitch.svg b/plugins/login-oauth2-extras/media/twitch.svg new file mode 100644 index 0000000..2f4f635 --- /dev/null +++ b/plugins/login-oauth2-extras/media/twitch.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/plugins/login-oauth2-extras/templates/login-oauth2/providers/azure.html.twig b/plugins/login-oauth2-extras/templates/login-oauth2/providers/azure.html.twig new file mode 100644 index 0000000..4054f94 --- /dev/null +++ b/plugins/login-oauth2-extras/templates/login-oauth2/providers/azure.html.twig @@ -0,0 +1,4 @@ + diff --git a/plugins/login-oauth2-extras/templates/login-oauth2/providers/discord.html.twig b/plugins/login-oauth2-extras/templates/login-oauth2/providers/discord.html.twig new file mode 100644 index 0000000..2e3c39c --- /dev/null +++ b/plugins/login-oauth2-extras/templates/login-oauth2/providers/discord.html.twig @@ -0,0 +1,4 @@ + diff --git a/plugins/login-oauth2-extras/templates/login-oauth2/providers/gitlab.html.twig b/plugins/login-oauth2-extras/templates/login-oauth2/providers/gitlab.html.twig new file mode 100644 index 0000000..7c6d9c0 --- /dev/null +++ b/plugins/login-oauth2-extras/templates/login-oauth2/providers/gitlab.html.twig @@ -0,0 +1,4 @@ + diff --git a/plugins/login-oauth2-extras/templates/login-oauth2/providers/jira.html.twig b/plugins/login-oauth2-extras/templates/login-oauth2/providers/jira.html.twig new file mode 100644 index 0000000..337daed --- /dev/null +++ b/plugins/login-oauth2-extras/templates/login-oauth2/providers/jira.html.twig @@ -0,0 +1,4 @@ + diff --git a/plugins/login-oauth2-extras/templates/login-oauth2/providers/keycloak.html.twig b/plugins/login-oauth2-extras/templates/login-oauth2/providers/keycloak.html.twig new file mode 100644 index 0000000..4d79b58 --- /dev/null +++ b/plugins/login-oauth2-extras/templates/login-oauth2/providers/keycloak.html.twig @@ -0,0 +1,4 @@ + diff --git a/plugins/login-oauth2-extras/templates/login-oauth2/providers/okta.html.twig b/plugins/login-oauth2-extras/templates/login-oauth2/providers/okta.html.twig new file mode 100644 index 0000000..6bd5224 --- /dev/null +++ b/plugins/login-oauth2-extras/templates/login-oauth2/providers/okta.html.twig @@ -0,0 +1,4 @@ + diff --git a/plugins/login-oauth2-extras/templates/login-oauth2/providers/patreon.html.twig b/plugins/login-oauth2-extras/templates/login-oauth2/providers/patreon.html.twig new file mode 100644 index 0000000..49e026c --- /dev/null +++ b/plugins/login-oauth2-extras/templates/login-oauth2/providers/patreon.html.twig @@ -0,0 +1,4 @@ + diff --git a/plugins/login-oauth2-extras/templates/login-oauth2/providers/slack.html.twig b/plugins/login-oauth2-extras/templates/login-oauth2/providers/slack.html.twig new file mode 100644 index 0000000..3fff024 --- /dev/null +++ b/plugins/login-oauth2-extras/templates/login-oauth2/providers/slack.html.twig @@ -0,0 +1,4 @@ + diff --git a/plugins/login-oauth2-extras/templates/login-oauth2/providers/twitch.html.twig b/plugins/login-oauth2-extras/templates/login-oauth2/providers/twitch.html.twig new file mode 100644 index 0000000..0dae5da --- /dev/null +++ b/plugins/login-oauth2-extras/templates/login-oauth2/providers/twitch.html.twig @@ -0,0 +1,4 @@ + diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.gitignore b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.gitignore new file mode 100644 index 0000000..c9b53dc --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.gitignore @@ -0,0 +1,3 @@ +composer.lock +/vendor/ +/build/ diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.scrutinizer.yml b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.scrutinizer.yml new file mode 100644 index 0000000..e68a981 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.scrutinizer.yml @@ -0,0 +1,35 @@ +filter: + excluded_paths: [test/*] +checks: + php: + code_rating: true + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true +tools: + external_code_coverage: + timeout: 600 + runs: 3 + php_analyzer: true + php_code_coverage: false + php_code_sniffer: + config: + standard: PSR2 + filter: + paths: ['src'] + php_loc: + enabled: true + excluded_dirs: [vendor, test] + php_cpd: + enabled: true + excluded_dirs: [vendor, test] \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.travis.yml b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.travis.yml new file mode 100644 index 0000000..dbb8188 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/.travis.yml @@ -0,0 +1,22 @@ +language: php + +dist: trusty + +php: + - 5.6 + - 7.0 + - 7.1 + - hhvm + +before_script: + - travis_retry composer self-update + - travis_retry composer install --no-interaction --prefer-source --dev + - travis_retry phpenv rehash + +script: + - ./vendor/bin/phpcs --standard=psr2 src/ + - ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover + +after_script: + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover coverage.clover diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/CONTRIBUTING.md b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/CONTRIBUTING.md new file mode 100644 index 0000000..3d22de8 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +I accept contributions via Pull Requests on [Github](https://github.com/adam-paterson/oauth2-slack). + + +## Pull Requests + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow SemVer. Randomly breaking public APIs is not an option. + +- **Create topic branches** - Don't ask us to pull from your master branch. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. + +- **Ensure tests pass!** - Please run the tests (see below) before submitting your pull request, and make sure they pass. We won't accept a patch until all tests pass. + +- **Ensure no coding standards violations** - Please run PHP Code Sniffer using the PSR-2 standard (see below) before submitting your pull request. A violation will cause the build to fail, so please make sure there are no violations. We can't accept a patch if the build fails. + + +## Running Tests + +``` bash +$ ./vendor/bin/phpunit +``` + + +## Running PHP Code Sniffer + +``` bash +$ ./vendor/bin/phpcs src --standard=psr2 -sp +``` + +**Happy coding**! \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/LICENSE b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/LICENSE new file mode 100644 index 0000000..fe6ad41 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Adam Paterson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/README.md b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/README.md new file mode 100644 index 0000000..85a3fa2 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/README.md @@ -0,0 +1,95 @@ +# Slack Provider for OAuth 2.0 Client +[![Latest Version](https://img.shields.io/github/release/adam-paterson/oauth2-slack.svg?style=flat-square)](https://github.com/adam-paterson/oauth2-slack/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/adam-paterson/oauth2-slack/master.svg?style=flat-square)](https://travis-ci.org/adam-paterson/oauth2-slack) +[![HHVM Status](https://img.shields.io/hhvm/adam-paterson/oauth2-slack.svg?style=flat-square)](http://hhvm.h4cc.de/package/adam-paterson/oauth2-slack) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/adam-paterson/oauth2-slack.svg?style=flat-square)](https://scrutinizer-ci.com/g/adam-paterson/oauth2-slack/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/adam-paterson/oauth2-slack.svg?style=flat-square)](https://scrutinizer-ci.com/g/adam-paterson/oauth2-slack) +[![Dependency Status](https://img.shields.io/versioneye/d/php/adam-paterson:oauth2-slack/1.1.2.svg?style=flat-square)](https://www.versioneye.com/php/adam-paterson:oauth2-slack/1.1.2) +[![Total Downloads](https://img.shields.io/packagist/dt/adam-paterson/oauth2-slack.svg?style=flat-square)](https://packagist.org/packages/adam-paterson/oauth2-slack) + +This package provides Slack OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +## Installation + +To install, use composer: + +``` +composer require adam-paterson/oauth2-slack +``` +## Usage + +Usage is the same as The League's OAuth client, using `\AdamPaterson\OAuth2\Client\Provider\Slack` as the provider. + +### Authorization Code Flow + + '{slack-client-id}', + 'clientSecret' => '{slack-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', + ]); + + if (!isset($_GET['code'])) { + + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: '.$authUrl); + exit; + + // Check given state against previously stored one to mitigate CSRF attack + } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + unset($_SESSION['oauth2state']); + exit('Invalid state'); + + } else { + + // Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the user's details + $team = $provider->getResourceOwner($token); + + // Use these details to create a new profile + printf('Hello %s!', $team->getName()); + + } catch (Exception $e) { + + // Failed to get user details + exit('Oh dear...'); + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); + } + +## Testing + +``` bash +$ ./vendor/bin/phpunit +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/adam-paterson/oauth2-slack/blob/master/CONTRIBUTING.md) for details. + + +## Credits + +- [Adam Paterson](https://github.com/adam-paterson) +- [All Contributors](https://github.com/adam-paterson/oauth2-slack/contributors) + + +## License + +The MIT License (MIT). Please see [License File](https://github.com/adam-paterson/oauth2-slack/blob/master/LICENSE) for more information. diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/composer.json b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/composer.json new file mode 100644 index 0000000..912573d --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/composer.json @@ -0,0 +1,42 @@ +{ + "name": "adam-paterson/oauth2-slack", + "description": "Slack OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "oauth", + "oauth2", + "authorization", + "authentication", + "idp", + "identity", + "sso", + "single sign on", + "slack", + "slack api" + ], + "license": "MIT", + "authors": [ + { + "name": "Adam Paterson", + "email": "hello@adampaterson.co.uk" + } + ], + "require": { + "php": ">=5.6.0", + "league/oauth2-client": "1.*|2.*" + }, + "require-dev": { + "mockery/mockery": "~0.9", + "squizlabs/php_codesniffer": "~2.0", + "phpunit/phpunit": "5.6" + }, + "autoload": { + "psr-4": { + "AdamPaterson\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "AdamPaterson\\OAuth2\\Client\\Test\\": "test/src/" + } + } +} diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/phpunit.xml b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/phpunit.xml new file mode 100644 index 0000000..c1fdd2d --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/phpunit.xml @@ -0,0 +1,37 @@ + + + + + + + + + ./test/ + + + + + ./ + + ./vendor + ./test + + + + \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/Slack.php b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/Slack.php new file mode 100644 index 0000000..2ed3ca5 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/Slack.php @@ -0,0 +1,147 @@ + + * + * @package AdamPaterson\OAuth2\Client\Provider + */ +class Slack extends AbstractProvider +{ + /** + * Returns the base URL for authorizing a client. + * + * @return string + */ + public function getBaseAuthorizationUrl() + { + return "https://slack.com/oauth/authorize"; + } + + /** + * Returns the base URL for requesting an access token. + * + * @param array $params + * + * @return string + */ + public function getBaseAccessTokenUrl(array $params) + { + return "https://slack.com/api/oauth.access"; + } + + /** + * Returns the URL for requesting the resource owner's details. + * + * @param AccessToken $token + * + * @return string + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + $authorizedUser = $this->getAuthorizedUser($token); + + $params = [ + 'token' => $token->getToken(), + 'user' => $authorizedUser->getId() + ]; + + $url = 'https://slack.com/api/users.info?'.http_build_query($params); + + return $url; + } + + /** + * @param $token + * + * @return string + */ + public function getAuthorizedUserTestUrl($token) + { + return "https://slack.com/api/auth.test?token=".$token; + } + + /** + * Checks a provider response for errors. + * + * @throws IdentityProviderException + * + * @param ResponseInterface $response + * @param array|string $data Parsed response data + * + * @return void + */ + protected function checkResponse(ResponseInterface $response, $data) + { + } + + /** + * Create new resources owner using the generated access token. + * + * @param array $response + * @param AccessToken $token + * + * @return SlackResourceOwner + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + return new SlackResourceOwner($response); + } + + /** + * @return array + */ + protected function getDefaultScopes() + { + return []; + } + + /** + * @param AccessToken $token + * + * @return mixed + */ + public function fetchAuthorizedUserDetails(AccessToken $token) + { + $url = $this->getAuthorizedUserTestUrl($token); + + $request = $this->getAuthenticatedRequest(self::METHOD_GET, $url, $token); + + // Keep compatibility with League\OAuth2\Client v1 + if (!method_exists($this, 'getParsedResponse')) { + return $this->getResponse($request); + } + + return $this->getParsedResponse($request); + } + + /** + * @param AccessToken $token + * + * @return SlackAuthorizedUser + */ + public function getAuthorizedUser(AccessToken $token) + { + $response = $this->fetchAuthorizedUserDetails($token); + + return $this->createAuthorizedUser($response); + } + + /** + * @param $response + * + * @return SlackAuthorizedUser + */ + protected function createAuthorizedUser($response) + { + return new SlackAuthorizedUser($response); + } +} diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/SlackAuthorizedUser.php b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/SlackAuthorizedUser.php new file mode 100644 index 0000000..7a56e3f --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/SlackAuthorizedUser.php @@ -0,0 +1,66 @@ +response = $response; + } + + /** + * Returns the identifier of the authorized resource owner. + * + * @return mixed + */ + public function getId() + { + return $this->response['user_id']; + } + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray() + { + return $this->response; + } + + public function getUrl() + { + return $this->response['url'] ?: null; + } + + public function getTeam() + { + return $this->response['team'] ?: null; + } + + public function getUser() + { + return $this->response['user'] ?: null; + } + + public function getTeamId() + { + return $this->response['team_id'] ?: null; + } + + public function getUserId() + { + return $this->response['user_id'] ?: null; + } +} diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/SlackResourceOwner.php b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/SlackResourceOwner.php new file mode 100644 index 0000000..8328de0 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/src/Provider/SlackResourceOwner.php @@ -0,0 +1,134 @@ + + * + * @package AdamPaterson\OAuth2\Client\Provider + */ +class SlackResourceOwner implements ResourceOwnerInterface +{ + + protected $response; + + public function __construct(array $response) + { + $this->response = $response; + } + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray() + { + return $this->response; + } + + public function getId() + { + return $this->response['user']['id'] ?: null; + } + + + public function getName() + { + return $this->response['user']['name'] ?: null; + } + + public function isDeleted() + { + return $this->response['user']['deleted'] ?: null; + } + + public function getColor() + { + return $this->response['user']['color'] ?: null; + } + + public function getProfile() + { + return $this->response['user']['profile'] ?: null; + } + + public function getFirstName() + { + return $this->response['user']['profile']['first_name'] ?: null; + } + + public function getLastName() + { + return $this->response['user']['profile']['last_name'] ?: null; + } + + public function getRealName() + { + return $this->response['user']['profile']['real_name'] ?: null; + } + + public function getEmail() + { + return $this->response['user']['profile']['email'] ?: null; + } + + public function getSkype() + { + return $this->response['user']['profile']['skype'] ?: null; + } + + public function getPhone() + { + return $this->response['user']['profile']['phone'] ?: null; + } + + public function getImage24() + { + return $this->response['user']['profile']['image_24'] ?: null; + } + + public function getImage32() + { + return $this->response['user']['profile']['image_32'] ?: null; + } + + public function getImage48() + { + return $this->response['user']['profile']['image_48'] ?: null; + } + + public function getImage72() + { + return $this->response['user']['profile']['image_72'] ?: null; + } + + public function getImage192() + { + return $this->response['user']['profile']['image_192'] ?: null; + } + + public function isAdmin() + { + return $this->response['user']['is_admin'] ?: null; + } + + public function isOwner() + { + return $this->response['user']['is_owner'] ?: null; + } + + public function hasTwoFactorAuthentication() + { + return $this->response['user']['has_2fa'] ?: null; + } + + public function hasFiles() + { + return $this->response['user']['has_files'] ?: null; + } +} diff --git a/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/test/src/Provider/SlackTest.php b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/test/src/Provider/SlackTest.php new file mode 100644 index 0000000..98c71ec --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/adam-paterson/oauth2-slack/test/src/Provider/SlackTest.php @@ -0,0 +1,269 @@ +getMethod($name); + $method->setAccessible(true); + return $method; + } + + protected function setUp() + { + $this->provider = new Slack([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none', + ]); + } + + public function tearDown() + { + m::close(); + parent::tearDown(); + } + + public function testAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + parse_str($uri['query'], $query); + + $this->assertArrayHasKey('client_id', $query); + $this->assertArrayHasKey('redirect_uri', $query); + $this->assertArrayHasKey('state', $query); + $this->assertArrayHasKey('scope', $query); + $this->assertArrayHasKey('response_type', $query); + $this->assertArrayHasKey('approval_prompt', $query); + $this->assertNotNull($this->provider->getState()); + } + + public function testGetResourceOwnerDetailsUrl() + { + $authUser = json_decode('{"ok": true,"url": "https:\/\/myteam.slack.com\/","team": "My Team","user": "cal","team_id": "T12345","user_id": "U12345"}',true); + $token = m::mock('League\OAuth2\Client\Token\AccessToken', [['access_token' => 'mock_access_token']]); + $token->shouldReceive('__toString')->andReturn('mock_access_token'); + + $provider = m::mock('AdamPaterson\OAuth2\Client\Provider\Slack'); + $provider->shouldReceive('getAuthorizedUser')->andReturn($authUser); + $provider->shouldReceive('getResourceOwnerDetailsUrl')->once()->andReturn('https://slack.com/api/users.info?token=mock_access_token&user=U12345'); + + $url = $provider->getResourceOwnerDetailsUrl($token); + $uri = parse_url($url); + + $this->assertEquals('/api/users.info', $uri['path']); + $this->assertEquals('token=mock_access_token&user=U12345', $uri['query']); + } + + public function testGetAuthorizationUrl() + { + $params = []; + $url = $this->provider->getAuthorizationUrl($params); + $uri = parse_url($url); + + $this->assertEquals('/oauth/authorize', $uri['path']); + } + + public function testGetBaseAccessTokenUrl() + { + $params = []; + $url = $this->provider->getBaseAccessTokenUrl($params); + $uri = parse_url($url); + $this->assertEquals('/api/oauth.access', $uri['path']); + } + + public function testGetAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token", "expires_in": 3600}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $this->assertEquals('mock_access_token', $token->getToken()); + $this->assertLessThanOrEqual(time() + 3600, $token->getExpires()); + $this->assertGreaterThanOrEqual(time(), $token->getExpires()); + $this->assertNull($token->getRefreshToken()); + $this->assertNull($token->getResourceOwnerId()); + } + + public function testCheckResponseThrowsIdentityProviderException() + { + $method = self::getMethod('checkResponse'); + $responseInterface = m::mock('Psr\Http\Message\ResponseInterface'); + $data = ['ok' => false]; + try { + $method->invoke($this->provider, $responseInterface, $data); + } catch (\Exception $e) { + $this->assertEquals(400, $e->getCode()); + $this->assertEquals("Unknown error", $e->getMessage()); + } + } + + public function testGetAuthorizedUserTestUrl() + { + $token = m::mock('League\OAuth2\Client\Token\AccessToken', [['access_token' => 'mock_access_token']]); + $token->shouldReceive('__toString')->andReturn('mock_access_token'); + $url = $this->provider->getAuthorizedUserTestUrl($token); + $uri = parse_url($url); + + $this->assertEquals('/api/auth.test', $uri['path']); + $this->assertEquals('token=mock_access_token', $uri['query']); + } + + public function testGetAuthorizedUserDetails() + { + $url = uniqid(); + $team = uniqid(); + $userName = uniqid(); + $teamId = uniqid(); + $userId = uniqid(); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn('{"ok": true,"url": "'.$url.'","user": "'.$userName.'","team": "'.$team.'","team_id": "'.$teamId.'","user_id": "'.$userId.'"}'); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getAuthorizedUser($token); + + $this->assertEquals($userId, $user->getId()); + $this->assertEquals($url, $user->getUrl()); + $this->assertEquals($url, $user->toArray()['url']); + $this->assertEquals($team, $user->getTeam()); + $this->assertEquals($team, $user->toArray()['team']); + $this->assertEquals($userName, $user->getUser()); + $this->assertEquals($userName, $user->toArray()['user']); + $this->assertEquals($teamId, $user->getTeamId()); + $this->assertEquals($teamId, $user->toArray()['team_id']); + $this->assertEquals($userId, $user->getUserId()); + $this->assertEquals($userId, $user->toArray()['user_id']); + } + + public function testGetResourceOwnerDetails() + { + $id = uniqid(); + $name = uniqid(); + $deleted = false; + $color = uniqid(); + $profile = [ + "first_name" => uniqid(), + "last_name" => uniqid(), + "real_name" => uniqid(), + "email" => uniqid(), + "skype" => uniqid(), + "phone" => uniqid(), + "image_24" => uniqid(), + "image_32" => uniqid(), + "image_48" => uniqid(), + "image_72" => uniqid(), + "image_192" => uniqid() + ]; + + $isAdmin = true; + $isOwner = true; + $has2FA = true; + $hasFiles = true; + + $url = uniqid(); + $userName = uniqid(); + $team = uniqid(); + $teamId = uniqid(); + $userId = uniqid(); + + $accessTokenResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $accessTokenResponse->shouldReceive('getBody')->andReturn('access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}'); + $accessTokenResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + $accessTokenResponse->shouldReceive('getStatusCode')->andReturn(200); + + $authUser = m::mock('Psr\Http\Message\ResponseInterface'); + $authUser->shouldReceive('getBody')->andReturn('{"ok": true,"url": "'.$url.'","user": "'.$userName.'","team": "'.$team.'","team_id": "'.$teamId.'","user_id": "'.$userId.'"}'); + $authUser->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $authUser->shouldReceive('getStatusCode')->andReturn(200); + + $authUserResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $authUserResponse->shouldReceive('getBody')->andReturn('{"ok": true,"url": "'.$url.'","team": "'.$team.'","user": "'.$userName.'","team_id": "'.$teamId.'","user_id": "'.$userId.'"}'); + $authUserResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $authUserResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn('{"ok": true,"user": {"id": "'.$id.'","name": "'.$name.'","deleted": false,"color": "'.$color.'","profile": {"first_name": "'.$profile["first_name"].'","last_name": "'.$profile["last_name"].'","real_name": "'.$profile["real_name"].'","email": "'.$profile["email"].'","skype": "'.$profile["skype"].'","phone": "'.$profile["phone"].'","image_24": "'.$profile["image_24"].'","image_32": "'.$profile["image_32"].'","image_48": "'.$profile["image_48"].'","image_72": "'.$profile["image_72"].'","image_192": "'.$profile["image_192"].'"},"is_admin": true,"is_owner": true,"has_2fa": true,"has_files": true}}'); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(3) + ->andReturn($accessTokenResponse, $authUserResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals($id, $user->getId()); + $this->assertEquals($id, $user->toArray()['user']['id']); + $this->assertEquals($name, $user->getName()); + $this->assertEquals($name, $user->toArray()['user']['name']); + $this->assertEquals($deleted, $user->isDeleted()); + $this->assertEquals($deleted, $user->toArray()['user']['deleted']); + $this->assertEquals($color, $user->getColor()); + $this->assertEquals($color, $user->toArray()['user']['color']); + $this->assertEquals($profile, $user->getProfile()); + $this->assertEquals($profile, $user->toArray()['user']['profile']); + + $this->assertEquals($profile['first_name'], $user->getFirstName()); + $this->assertEquals($profile['first_name'], $user->toArray()['user']['profile']['first_name']); + $this->assertEquals($profile['last_name'], $user->getLastName()); + $this->assertEquals($profile['last_name'], $user->toArray()['user']['profile']['last_name']); + $this->assertEquals($profile['real_name'], $user->getRealName()); + $this->assertEquals($profile['real_name'], $user->toArray()['user']['profile']['real_name']); + $this->assertEquals($profile['email'], $user->getEmail()); + $this->assertEquals($profile['email'], $user->toArray()['user']['profile']['email']); + $this->assertEquals($profile['skype'], $user->getSkype()); + $this->assertEquals($profile['skype'], $user->toArray()['user']['profile']['skype']); + $this->assertEquals($profile['phone'], $user->getPhone()); + $this->assertEquals($profile['phone'], $user->toArray()['user']['profile']['phone']); + $this->assertEquals($profile['image_24'], $user->getImage24()); + $this->assertEquals($profile['image_24'], $user->toArray()['user']['profile']['image_24']); + $this->assertEquals($profile['image_32'], $user->getImage32()); + $this->assertEquals($profile['image_32'], $user->toArray()['user']['profile']['image_32']); + $this->assertEquals($profile['image_48'], $user->getImage48()); + $this->assertEquals($profile['image_48'], $user->toArray()['user']['profile']['image_48']); + $this->assertEquals($profile['image_72'], $user->getImage72()); + $this->assertEquals($profile['image_72'], $user->toArray()['user']['profile']['image_72']); + $this->assertEquals($profile['image_192'], $user->getImage192()); + $this->assertEquals($profile['image_192'], $user->toArray()['user']['profile']['image_192']); + + $this->assertEquals($isAdmin, $user->isAdmin()); + $this->assertEquals($isAdmin, $user->toArray()['user']['is_admin']); + $this->assertEquals($isOwner, $user->isOwner()); + $this->assertEquals($isOwner, $user->toArray()['user']['is_owner']); + $this->assertEquals($has2FA, $user->hasTwoFactorAuthentication()); + $this->assertEquals($has2FA, $user->toArray()['user']['has_2fa']); + $this->assertEquals($hasFiles, $user->hasFiles()); + $this->assertEquals($hasFiles, $user->toArray()['user']['has_files']); + + + } +} \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/autoload.php b/plugins/login-oauth2-extras/vendor/autoload.php new file mode 100644 index 0000000..09a55f9 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/autoload.php @@ -0,0 +1,7 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var ?string */ + private $vendorDir; + + // PSR-4 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array[] + * @psalm-var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixesPsr0 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var string[] + * @psalm-var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var bool[] + * @psalm-var array + */ + private $missingClasses = array(); + + /** @var ?string */ + private $apcuPrefix; + + /** + * @var self[] + */ + private static $registeredLoaders = array(); + + /** + * @param ?string $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + } + + /** + * @return string[] + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array[] + * @psalm-return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return string[] Array of classname => path + * @psalm-return array + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param string[] $classMap Class to filename map + * @psalm-param array $classMap + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $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. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + 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 (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders indexed by their corresponding vendor directories. + * + * @return self[] + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } +} + +/** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + * @private + */ +function includeFile($file) +{ + include $file; +} diff --git a/plugins/login-oauth2-extras/vendor/composer/InstalledVersions.php b/plugins/login-oauth2-extras/vendor/composer/InstalledVersions.php new file mode 100644 index 0000000..d50e0c9 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/composer/InstalledVersions.php @@ -0,0 +1,350 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']); + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints($constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php'; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = require __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + $installed[] = self::$installed; + + return $installed; + } +} diff --git a/plugins/login-oauth2-extras/vendor/composer/LICENSE b/plugins/login-oauth2-extras/vendor/composer/LICENSE new file mode 100644 index 0000000..f27399a --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +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/plugins/login-oauth2-extras/vendor/composer/autoload_classmap.php b/plugins/login-oauth2-extras/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..b26f1b1 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/composer/autoload_classmap.php @@ -0,0 +1,10 @@ + $vendorDir . '/composer/InstalledVersions.php', +); diff --git a/plugins/login-oauth2-extras/vendor/composer/autoload_namespaces.php b/plugins/login-oauth2-extras/vendor/composer/autoload_namespaces.php new file mode 100644 index 0000000..b7fc012 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($vendorDir . '/wohali/oauth2-discord-new/src'), + 'Vertisan\\OAuth2\\Client\\Provider\\' => array($vendorDir . '/vertisan/oauth2-twitch-helix/src'), + 'TheNetworg\\OAuth2\\Client\\' => array($vendorDir . '/thenetworg/oauth2-azure/src'), + 'Stevenmaguire\\OAuth2\\Client\\' => array($vendorDir . '/stevenmaguire/oauth2-keycloak/src'), + 'Omines\\OAuth2\\Client\\' => array($vendorDir . '/omines/oauth2-gitlab/src'), + 'Mrjoops\\OAuth2\\Client\\' => array($vendorDir . '/mrjoops/oauth2-jira/src'), + 'Gravure\\Patreon\\Oauth\\' => array($vendorDir . '/gravure/oauth2-patreon/src'), + 'Grav\\Plugin\\Login\\OAuth2\\' => array($baseDir . '/classes'), + 'Foxworth42\\OAuth2\\Client\\' => array($vendorDir . '/foxworth42/oauth2-okta/src'), + 'Firebase\\JWT\\' => array($vendorDir . '/firebase/php-jwt/src'), + 'AdamPaterson\\OAuth2\\Client\\' => array($vendorDir . '/adam-paterson/oauth2-slack/src'), +); diff --git a/plugins/login-oauth2-extras/vendor/composer/autoload_real.php b/plugins/login-oauth2-extras/vendor/composer/autoload_real.php new file mode 100644 index 0000000..7057b19 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/composer/autoload_real.php @@ -0,0 +1,57 @@ += 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); + if ($useStaticLoader) { + require __DIR__ . '/autoload_static.php'; + + call_user_func(\Composer\Autoload\ComposerStaticInitbd5d628261f1599470d200425791c144::getInitializer($loader)); + } else { + $map = require __DIR__ . '/autoload_namespaces.php'; + foreach ($map as $namespace => $path) { + $loader->set($namespace, $path); + } + + $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); + + return $loader; + } +} diff --git a/plugins/login-oauth2-extras/vendor/composer/autoload_static.php b/plugins/login-oauth2-extras/vendor/composer/autoload_static.php new file mode 100644 index 0000000..77b06e5 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/composer/autoload_static.php @@ -0,0 +1,110 @@ + + array ( + 'Wohali\\OAuth2\\Client\\' => 21, + ), + 'V' => + array ( + 'Vertisan\\OAuth2\\Client\\Provider\\' => 32, + ), + 'T' => + array ( + 'TheNetworg\\OAuth2\\Client\\' => 25, + ), + 'S' => + array ( + 'Stevenmaguire\\OAuth2\\Client\\' => 28, + ), + 'O' => + array ( + 'Omines\\OAuth2\\Client\\' => 21, + ), + 'M' => + array ( + 'Mrjoops\\OAuth2\\Client\\' => 22, + ), + 'G' => + array ( + 'Gravure\\Patreon\\Oauth\\' => 22, + 'Grav\\Plugin\\Login\\OAuth2\\' => 25, + ), + 'F' => + array ( + 'Foxworth42\\OAuth2\\Client\\' => 25, + 'Firebase\\JWT\\' => 13, + ), + 'A' => + array ( + 'AdamPaterson\\OAuth2\\Client\\' => 27, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'Wohali\\OAuth2\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/wohali/oauth2-discord-new/src', + ), + 'Vertisan\\OAuth2\\Client\\Provider\\' => + array ( + 0 => __DIR__ . '/..' . '/vertisan/oauth2-twitch-helix/src', + ), + 'TheNetworg\\OAuth2\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/thenetworg/oauth2-azure/src', + ), + 'Stevenmaguire\\OAuth2\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/stevenmaguire/oauth2-keycloak/src', + ), + 'Omines\\OAuth2\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/omines/oauth2-gitlab/src', + ), + 'Mrjoops\\OAuth2\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/mrjoops/oauth2-jira/src', + ), + 'Gravure\\Patreon\\Oauth\\' => + array ( + 0 => __DIR__ . '/..' . '/gravure/oauth2-patreon/src', + ), + 'Grav\\Plugin\\Login\\OAuth2\\' => + array ( + 0 => __DIR__ . '/../..' . '/classes', + ), + 'Foxworth42\\OAuth2\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/foxworth42/oauth2-okta/src', + ), + 'Firebase\\JWT\\' => + array ( + 0 => __DIR__ . '/..' . '/firebase/php-jwt/src', + ), + 'AdamPaterson\\OAuth2\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/adam-paterson/oauth2-slack/src', + ), + ); + + public static $classMap = array ( + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInitbd5d628261f1599470d200425791c144::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInitbd5d628261f1599470d200425791c144::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInitbd5d628261f1599470d200425791c144::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/plugins/login-oauth2-extras/vendor/composer/installed.json b/plugins/login-oauth2-extras/vendor/composer/installed.json new file mode 100644 index 0000000..7e58b29 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/composer/installed.json @@ -0,0 +1,608 @@ +{ + "packages": [ + { + "name": "adam-paterson/oauth2-slack", + "version": "1.1.3", + "version_normalized": "1.1.3.0", + "source": { + "type": "git", + "url": "https://github.com/adam-paterson/oauth2-slack.git", + "reference": "ccc329eb3036a89d110227a4137e15d4a5661678" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/adam-paterson/oauth2-slack/zipball/ccc329eb3036a89d110227a4137e15d4a5661678", + "reference": "ccc329eb3036a89d110227a4137e15d4a5661678", + "shasum": "" + }, + "require": { + "league/oauth2-client": "1.*|2.*", + "php": ">=5.6.0" + }, + "require-dev": { + "mockery/mockery": "~0.9", + "phpunit/phpunit": "5.6", + "squizlabs/php_codesniffer": "~2.0" + }, + "time": "2017-06-20T14:43:31+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "AdamPaterson\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Adam Paterson", + "email": "hello@adampaterson.co.uk" + } + ], + "description": "Slack OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "Authentication", + "SSO", + "authorization", + "identity", + "idp", + "oauth", + "oauth2", + "single sign on", + "slack", + "slack api" + ], + "support": { + "issues": "https://github.com/adam-paterson/oauth2-slack/issues", + "source": "https://github.com/adam-paterson/oauth2-slack/tree/master" + }, + "install-path": "../adam-paterson/oauth2-slack" + }, + { + "name": "firebase/php-jwt", + "version": "v5.5.1", + "version_normalized": "5.5.1.0", + "source": { + "type": "git", + "url": "https://github.com/firebase/php-jwt.git", + "reference": "83b609028194aa042ea33b5af2d41a7427de80e6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/firebase/php-jwt/zipball/83b609028194aa042ea33b5af2d41a7427de80e6", + "reference": "83b609028194aa042ea33b5af2d41a7427de80e6", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": ">=4.8 <=9" + }, + "suggest": { + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present" + }, + "time": "2021-11-08T20:18:51+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/firebase/php-jwt", + "keywords": [ + "jwt", + "php" + ], + "support": { + "issues": "https://github.com/firebase/php-jwt/issues", + "source": "https://github.com/firebase/php-jwt/tree/v5.5.1" + }, + "install-path": "../firebase/php-jwt" + }, + { + "name": "foxworth42/oauth2-okta", + "version": "v1.0.2", + "version_normalized": "1.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/foxworth42/oauth2-okta.git", + "reference": "0e7c2eb68f57eff8aafc4a3f0a1a1ec1c147c946" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/foxworth42/oauth2-okta/zipball/0e7c2eb68f57eff8aafc4a3f0a1a1ec1c147c946", + "reference": "0e7c2eb68f57eff8aafc4a3f0a1a1ec1c147c946", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0", + "php": ">=7.1.0" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^7.0", + "squizlabs/php_codesniffer": "^3.4" + }, + "time": "2020-09-28T06:28:26+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Foxworth42\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ed Walker", + "email": "github@foxwire.org" + } + ], + "description": "Okta OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "Authentication", + "authorization", + "client", + "oauth", + "oauth2", + "okta" + ], + "support": { + "issues": "https://github.com/foxworth42/oauth2-okta/issues", + "source": "https://github.com/foxworth42/oauth2-okta/tree/v1.0.2" + }, + "install-path": "../foxworth42/oauth2-okta" + }, + { + "name": "gravure/oauth2-patreon", + "version": "dev-master", + "version_normalized": "dev-master", + "source": { + "type": "git", + "url": "https://github.com/gravure/oauth2-patreon.git", + "reference": "32c5bb7c6cdfb0cbb4e396ca8e9cbde447f41f47" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/gravure/oauth2-patreon/zipball/32c5bb7c6cdfb0cbb4e396ca8e9cbde447f41f47", + "reference": "32c5bb7c6cdfb0cbb4e396ca8e9cbde447f41f47", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^1.0 || ^2.0", + "php": "5.6.* || >=7.0" + }, + "time": "2018-02-06T12:41:19+00:00", + "default-branch": true, + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Gravure\\Patreon\\Oauth\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Daniël Klabbers", + "email": "daniel@klabbers.email", + "homepage": "http://luceos.com" + } + ], + "description": "Provides Patreon OAuth 2.0 support for PHP League's OAuth 2.0 Client.", + "keywords": [ + "league", + "oauth2", + "patreon" + ], + "support": { + "issues": "https://github.com/gravure/oauth2-patreon/issues", + "source": "https://github.com/gravure/oauth2-patreon" + }, + "install-path": "../gravure/oauth2-patreon" + }, + { + "name": "mrjoops/oauth2-jira", + "version": "v0.2.4", + "version_normalized": "0.2.4.0", + "source": { + "type": "git", + "url": "https://github.com/mrjoops/oauth2-jira.git", + "reference": "9c270f7a70ea13c8d844676cddf17977991cb347" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/mrjoops/oauth2-jira/zipball/9c270f7a70ea13c8d844676cddf17977991cb347", + "reference": "9c270f7a70ea13c8d844676cddf17977991cb347", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "mockery/mockery": "^1.2", + "phpunit/phpunit": "^5.0", + "squizlabs/php_codesniffer": "^3.3" + }, + "time": "2018-11-11T19:49:42+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Mrjoops\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alexandre Lahure", + "email": "alexandre@lahu.re" + } + ], + "description": "Jira OAuth 2.0 support for the PHP League's OAuth 2.0 Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "jira", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/mrjoops/oauth2-jira/issues", + "source": "https://github.com/mrjoops/oauth2-jira/tree/develop" + }, + "install-path": "../mrjoops/oauth2-jira" + }, + { + "name": "omines/oauth2-gitlab", + "version": "3.4.0", + "version_normalized": "3.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/omines/oauth2-gitlab.git", + "reference": "0c37361c54fae71a85350c445bda1834db5859af" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/omines/oauth2-gitlab/zipball/0c37361c54fae71a85350c445bda1834db5859af", + "reference": "0c37361c54fae71a85350c445bda1834db5859af", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.4.1", + "php": ">=7.2" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.0", + "guzzlehttp/psr7": "^1.6", + "http-interop/http-factory-guzzle": "^1.0", + "m4tthumphrey/php-gitlab-api": "^10.0|^11.0", + "mockery/mockery": "^1.0", + "php-http/guzzle7-adapter": "^0.1", + "phpunit/phpunit": "^8.0|^9.0" + }, + "suggest": { + "m4tthumphrey/php-gitlab-api": "For further API usage using the acquired OAuth2 token" + }, + "time": "2021-02-08T12:15:55+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Omines\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Niels Keurentjes", + "email": "niels.keurentjes@omines.com", + "homepage": "https://www.omines.nl/" + } + ], + "description": "GitLab OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "gitlab", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/omines/oauth2-gitlab/issues", + "source": "https://github.com/omines/oauth2-gitlab/tree/3.4.0" + }, + "install-path": "../omines/oauth2-gitlab" + }, + { + "name": "stevenmaguire/oauth2-keycloak", + "version": "3.0.0", + "version_normalized": "3.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/stevenmaguire/oauth2-keycloak.git", + "reference": "645b84107b82a08cfed9c101081eb8548ea5be11" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/stevenmaguire/oauth2-keycloak/zipball/645b84107b82a08cfed9c101081eb8548ea5be11", + "reference": "645b84107b82a08cfed9c101081eb8548ea5be11", + "shasum": "" + }, + "require": { + "firebase/php-jwt": "~4.0|~5.0", + "league/oauth2-client": "^2.0 <2.3.0" + }, + "require-dev": { + "mockery/mockery": "~0.9", + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~2.0" + }, + "time": "2022-01-23T18:01:00+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Stevenmaguire\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "description": "Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "keycloak", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/stevenmaguire/oauth2-keycloak/issues", + "source": "https://github.com/stevenmaguire/oauth2-keycloak/tree/3.0.0" + }, + "install-path": "../stevenmaguire/oauth2-keycloak" + }, + { + "name": "thenetworg/oauth2-azure", + "version": "v1.4.0", + "version_normalized": "1.4.0.0", + "source": { + "type": "git", + "url": "https://github.com/TheNetworg/oauth2-azure.git", + "reference": "c57dcb63a925c29e744bffa4a079a95680dd5faf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/TheNetworg/oauth2-azure/zipball/c57dcb63a925c29e744bffa4a079a95680dd5faf", + "reference": "c57dcb63a925c29e744bffa4a079a95680dd5faf", + "shasum": "" + }, + "require": { + "firebase/php-jwt": "~3.0||~4.0||~5.0", + "league/oauth2-client": "~2.0", + "php": ">=5.5.0" + }, + "time": "2018-10-02T08:54:26+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "TheNetworg\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jan Hajek", + "email": "jan.hajek@thenetw.org", + "homepage": "https://thenetw.org" + } + ], + "description": "Azure Active Directory OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "SSO", + "aad", + "authorization", + "azure", + "azure active directory", + "client", + "microsoft", + "oauth", + "oauth2", + "windows azure" + ], + "support": { + "issues": "https://github.com/TheNetworg/oauth2-azure/issues", + "source": "https://github.com/TheNetworg/oauth2-azure/tree/master" + }, + "install-path": "../thenetworg/oauth2-azure" + }, + { + "name": "vertisan/oauth2-twitch-helix", + "version": "1.1.2", + "version_normalized": "1.1.2.0", + "source": { + "type": "git", + "url": "https://github.com/vertisan/oauth2-twitch-helix.git", + "reference": "67cac44b4adf113aee026424b435975a026db0e9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/vertisan/oauth2-twitch-helix/zipball/67cac44b4adf113aee026424b435975a026db0e9", + "reference": "67cac44b4adf113aee026424b435975a026db0e9", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.2.1", + "php": ">=5.6.0" + }, + "require-dev": { + "ext-json": "*", + "jakub-onderka/php-parallel-lint": "^1.0", + "mockery/mockery": "^1.2", + "phpunit/phpunit": "^5.7", + "squizlabs/php_codesniffer": "^3.4" + }, + "time": "2022-02-03T20:38:26+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Vertisan\\OAuth2\\Client\\Provider\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paweł Farys", + "email": "pmg.farys@gmail.com", + "homepage": "https://github.com/vertisan" + } + ], + "description": "Twitch (new version Helix) OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "client", + "helix", + "league", + "oauth", + "package", + "twitch" + ], + "support": { + "issues": "https://github.com/vertisan/oauth2-twitch-helix/issues", + "source": "https://github.com/vertisan/oauth2-twitch-helix/tree/1.1.2" + }, + "install-path": "../vertisan/oauth2-twitch-helix" + }, + { + "name": "wohali/oauth2-discord-new", + "version": "1.1.0", + "version_normalized": "1.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/wohali/oauth2-discord-new.git", + "reference": "0dcb5059cded358f55ae566de9621652cf8542c6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/wohali/oauth2-discord-new/zipball/0dcb5059cded358f55ae566de9621652cf8542c6", + "reference": "0dcb5059cded358f55ae566de9621652cf8542c6", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0" + }, + "conflict": { + "team-reflex/oauth2-discord": ">=1.0" + }, + "require-dev": { + "mockery/mockery": "~1.3.0", + "php-parallel-lint/php-parallel-lint": "~0.9", + "phpunit/phpunit": "~8.0", + "squizlabs/php_codesniffer": "^2.0" + }, + "time": "2020-06-12T07:27:09+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Wohali\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Joan Touzet", + "email": "code@atypical.net", + "homepage": "https://github.com/wohali" + } + ], + "description": "Discord OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "discord", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/wohali/oauth2-discord-new/issues", + "source": "https://github.com/wohali/oauth2-discord-new/tree/master" + }, + "install-path": "../wohali/oauth2-discord-new" + } + ], + "dev": true, + "dev-package-names": [] +} diff --git a/plugins/login-oauth2-extras/vendor/composer/installed.php b/plugins/login-oauth2-extras/vendor/composer/installed.php new file mode 100644 index 0000000..b075215 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/composer/installed.php @@ -0,0 +1,151 @@ + array( + 'pretty_version' => 'dev-develop', + 'version' => 'dev-develop', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'reference' => '21ea886e486956d4d163ed21e51c569ac666f750', + 'name' => '__root__', + 'dev' => true, + ), + 'versions' => array( + '__root__' => array( + 'pretty_version' => 'dev-develop', + 'version' => 'dev-develop', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'reference' => '21ea886e486956d4d163ed21e51c569ac666f750', + 'dev_requirement' => false, + ), + 'adam-paterson/oauth2-slack' => array( + 'pretty_version' => '1.1.3', + 'version' => '1.1.3.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../adam-paterson/oauth2-slack', + 'aliases' => array(), + 'reference' => 'ccc329eb3036a89d110227a4137e15d4a5661678', + 'dev_requirement' => false, + ), + 'firebase/php-jwt' => array( + 'pretty_version' => 'v5.5.1', + 'version' => '5.5.1.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../firebase/php-jwt', + 'aliases' => array(), + 'reference' => '83b609028194aa042ea33b5af2d41a7427de80e6', + 'dev_requirement' => false, + ), + 'foxworth42/oauth2-okta' => array( + 'pretty_version' => 'v1.0.2', + 'version' => '1.0.2.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../foxworth42/oauth2-okta', + 'aliases' => array(), + 'reference' => '0e7c2eb68f57eff8aafc4a3f0a1a1ec1c147c946', + 'dev_requirement' => false, + ), + 'gravure/oauth2-patreon' => array( + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'type' => 'library', + 'install_path' => __DIR__ . '/../gravure/oauth2-patreon', + 'aliases' => array( + 0 => '9999999-dev', + ), + 'reference' => '32c5bb7c6cdfb0cbb4e396ca8e9cbde447f41f47', + 'dev_requirement' => false, + ), + 'guzzlehttp/guzzle' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => '*', + ), + ), + 'guzzlehttp/promises' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => '*', + ), + ), + 'guzzlehttp/psr7' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => '*', + ), + ), + 'league/oauth2-client' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => '*', + ), + ), + 'mrjoops/oauth2-jira' => array( + 'pretty_version' => 'v0.2.4', + 'version' => '0.2.4.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../mrjoops/oauth2-jira', + 'aliases' => array(), + 'reference' => '9c270f7a70ea13c8d844676cddf17977991cb347', + 'dev_requirement' => false, + ), + 'omines/oauth2-gitlab' => array( + 'pretty_version' => '3.4.0', + 'version' => '3.4.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../omines/oauth2-gitlab', + 'aliases' => array(), + 'reference' => '0c37361c54fae71a85350c445bda1834db5859af', + 'dev_requirement' => false, + ), + 'paragonie/random_compat' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => '*', + ), + ), + 'psr/http-message' => array( + 'dev_requirement' => false, + 'replaced' => array( + 0 => '*', + ), + ), + 'stevenmaguire/oauth2-keycloak' => array( + 'pretty_version' => '3.0.0', + 'version' => '3.0.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../stevenmaguire/oauth2-keycloak', + 'aliases' => array(), + 'reference' => '645b84107b82a08cfed9c101081eb8548ea5be11', + 'dev_requirement' => false, + ), + 'thenetworg/oauth2-azure' => array( + 'pretty_version' => 'v1.4.0', + 'version' => '1.4.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../thenetworg/oauth2-azure', + 'aliases' => array(), + 'reference' => 'c57dcb63a925c29e744bffa4a079a95680dd5faf', + 'dev_requirement' => false, + ), + 'vertisan/oauth2-twitch-helix' => array( + 'pretty_version' => '1.1.2', + 'version' => '1.1.2.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../vertisan/oauth2-twitch-helix', + 'aliases' => array(), + 'reference' => '67cac44b4adf113aee026424b435975a026db0e9', + 'dev_requirement' => false, + ), + 'wohali/oauth2-discord-new' => array( + 'pretty_version' => '1.1.0', + 'version' => '1.1.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../wohali/oauth2-discord-new', + 'aliases' => array(), + 'reference' => '0dcb5059cded358f55ae566de9621652cf8542c6', + 'dev_requirement' => false, + ), + ), +); diff --git a/plugins/login-oauth2-extras/vendor/composer/platform_check.php b/plugins/login-oauth2-extras/vendor/composer/platform_check.php new file mode 100644 index 0000000..589e9e7 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/composer/platform_check.php @@ -0,0 +1,26 @@ += 70200)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 7.2.0". You are running ' . PHP_VERSION . '.'; +} + +if ($issues) { + if (!headers_sent()) { + header('HTTP/1.1 500 Internal Server Error'); + } + if (!ini_get('display_errors')) { + if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { + fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); + } elseif (!headers_sent()) { + echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; + } + } + trigger_error( + 'Composer detected issues in your platform: ' . implode(' ', $issues), + E_USER_ERROR + ); +} diff --git a/plugins/login-oauth2-extras/vendor/firebase/php-jwt/LICENSE b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/LICENSE new file mode 100644 index 0000000..11c0146 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2011, Neuman Vong + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the copyright holder nor the names of other + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/plugins/login-oauth2-extras/vendor/firebase/php-jwt/README.md b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/README.md new file mode 100644 index 0000000..1d392cd --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/README.md @@ -0,0 +1,289 @@ +[![Build Status](https://travis-ci.org/firebase/php-jwt.png?branch=master)](https://travis-ci.org/firebase/php-jwt) +[![Latest Stable Version](https://poser.pugx.org/firebase/php-jwt/v/stable)](https://packagist.org/packages/firebase/php-jwt) +[![Total Downloads](https://poser.pugx.org/firebase/php-jwt/downloads)](https://packagist.org/packages/firebase/php-jwt) +[![License](https://poser.pugx.org/firebase/php-jwt/license)](https://packagist.org/packages/firebase/php-jwt) + +PHP-JWT +======= +A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to [RFC 7519](https://tools.ietf.org/html/rfc7519). + +Installation +------------ + +Use composer to manage your dependencies and download PHP-JWT: + +```bash +composer require firebase/php-jwt +``` + +Optionally, install the `paragonie/sodium_compat` package from composer if your +php is < 7.2 or does not have libsodium installed: + +```bash +composer require paragonie/sodium_compat +``` + +Example +------- +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +$key = "example_key"; +$payload = array( + "iss" => "http://example.org", + "aud" => "http://example.com", + "iat" => 1356999524, + "nbf" => 1357000000 +); + +/** + * IMPORTANT: + * You must specify supported algorithms for your application. See + * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 + * for a list of spec-compliant algorithms. + */ +$jwt = JWT::encode($payload, $key, 'HS256'); +$decoded = JWT::decode($jwt, new Key($key, 'HS256')); + +print_r($decoded); + +/* + NOTE: This will now be an object instead of an associative array. To get + an associative array, you will need to cast it as such: +*/ + +$decoded_array = (array) $decoded; + +/** + * You can add a leeway to account for when there is a clock skew times between + * the signing and verifying servers. It is recommended that this leeway should + * not be bigger than a few minutes. + * + * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef + */ +JWT::$leeway = 60; // $leeway in seconds +$decoded = JWT::decode($jwt, new Key($key, 'HS256')); +``` +Example with RS256 (openssl) +---------------------------- +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +$privateKey = << "example.org", + "aud" => "example.com", + "iat" => 1356999524, + "nbf" => 1357000000 +); + +$jwt = JWT::encode($payload, $privateKey, 'RS256'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256')); + +/* + NOTE: This will now be an object instead of an associative array. To get + an associative array, you will need to cast it as such: +*/ + +$decoded_array = (array) $decoded; +echo "Decode:\n" . print_r($decoded_array, true) . "\n"; +``` + +Example with a passphrase +------------------------- + +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +// Your passphrase +$passphrase = '[YOUR_PASSPHRASE]'; + +// Your private key file with passphrase +// Can be generated with "ssh-keygen -t rsa -m pem" +$privateKeyFile = '/path/to/key-with-passphrase.pem'; + +// Create a private key of type "resource" +$privateKey = openssl_pkey_get_private( + file_get_contents($privateKeyFile), + $passphrase +); + +$payload = array( + "iss" => "example.org", + "aud" => "example.com", + "iat" => 1356999524, + "nbf" => 1357000000 +); + +$jwt = JWT::encode($payload, $privateKey, 'RS256'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +// Get public key from the private key, or pull from from a file. +$publicKey = openssl_pkey_get_details($privateKey)['key']; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256')); +echo "Decode:\n" . print_r((array) $decoded, true) . "\n"; +``` + +Example with EdDSA (libsodium and Ed25519 signature) +---------------------------- +```php +use Firebase\JWT\JWT; +use Firebase\JWT\Key; + +// Public and private keys are expected to be Base64 encoded. The last +// non-empty line is used so that keys can be generated with +// sodium_crypto_sign_keypair(). The secret keys generated by other tools may +// need to be adjusted to match the input expected by libsodium. + +$keyPair = sodium_crypto_sign_keypair(); + +$privateKey = base64_encode(sodium_crypto_sign_secretkey($keyPair)); + +$publicKey = base64_encode(sodium_crypto_sign_publickey($keyPair)); + +$payload = array( + "iss" => "example.org", + "aud" => "example.com", + "iat" => 1356999524, + "nbf" => 1357000000 +); + +$jwt = JWT::encode($payload, $privateKey, 'EdDSA'); +echo "Encode:\n" . print_r($jwt, true) . "\n"; + +$decoded = JWT::decode($jwt, new Key($publicKey, 'EdDSA')); +echo "Decode:\n" . print_r((array) $decoded, true) . "\n"; +```` + +Using JWKs +---------- + +```php +use Firebase\JWT\JWK; +use Firebase\JWT\JWT; + +// Set of keys. The "keys" key is required. For example, the JSON response to +// this endpoint: https://www.gstatic.com/iap/verify/public_key-jwk +$jwks = ['keys' => []]; + +// JWK::parseKeySet($jwks) returns an associative array of **kid** to private +// key. Pass this as the second parameter to JWT::decode. +// NOTE: The deprecated $supportedAlgorithm must be supplied when parsing from JWK. +JWT::decode($payload, JWK::parseKeySet($jwks), $supportedAlgorithm); +``` + +Changelog +--------- + +#### 5.0.0 / 2017-06-26 +- Support RS384 and RS512. + See [#117](https://github.com/firebase/php-jwt/pull/117). Thanks [@joostfaassen](https://github.com/joostfaassen)! +- Add an example for RS256 openssl. + See [#125](https://github.com/firebase/php-jwt/pull/125). Thanks [@akeeman](https://github.com/akeeman)! +- Detect invalid Base64 encoding in signature. + See [#162](https://github.com/firebase/php-jwt/pull/162). Thanks [@psignoret](https://github.com/psignoret)! +- Update `JWT::verify` to handle OpenSSL errors. + See [#159](https://github.com/firebase/php-jwt/pull/159). Thanks [@bshaffer](https://github.com/bshaffer)! +- Add `array` type hinting to `decode` method + See [#101](https://github.com/firebase/php-jwt/pull/101). Thanks [@hywak](https://github.com/hywak)! +- Add all JSON error types. + See [#110](https://github.com/firebase/php-jwt/pull/110). Thanks [@gbalduzzi](https://github.com/gbalduzzi)! +- Bugfix 'kid' not in given key list. + See [#129](https://github.com/firebase/php-jwt/pull/129). Thanks [@stampycode](https://github.com/stampycode)! +- Miscellaneous cleanup, documentation and test fixes. + See [#107](https://github.com/firebase/php-jwt/pull/107), [#115](https://github.com/firebase/php-jwt/pull/115), + [#160](https://github.com/firebase/php-jwt/pull/160), [#161](https://github.com/firebase/php-jwt/pull/161), and + [#165](https://github.com/firebase/php-jwt/pull/165). Thanks [@akeeman](https://github.com/akeeman), + [@chinedufn](https://github.com/chinedufn), and [@bshaffer](https://github.com/bshaffer)! + +#### 4.0.0 / 2016-07-17 +- Add support for late static binding. See [#88](https://github.com/firebase/php-jwt/pull/88) for details. Thanks to [@chappy84](https://github.com/chappy84)! +- Use static `$timestamp` instead of `time()` to improve unit testing. See [#93](https://github.com/firebase/php-jwt/pull/93) for details. Thanks to [@josephmcdermott](https://github.com/josephmcdermott)! +- Fixes to exceptions classes. See [#81](https://github.com/firebase/php-jwt/pull/81) for details. Thanks to [@Maks3w](https://github.com/Maks3w)! +- Fixes to PHPDoc. See [#76](https://github.com/firebase/php-jwt/pull/76) for details. Thanks to [@akeeman](https://github.com/akeeman)! + +#### 3.0.0 / 2015-07-22 +- Minimum PHP version updated from `5.2.0` to `5.3.0`. +- Add `\Firebase\JWT` namespace. See +[#59](https://github.com/firebase/php-jwt/pull/59) for details. Thanks to +[@Dashron](https://github.com/Dashron)! +- Require a non-empty key to decode and verify a JWT. See +[#60](https://github.com/firebase/php-jwt/pull/60) for details. Thanks to +[@sjones608](https://github.com/sjones608)! +- Cleaner documentation blocks in the code. See +[#62](https://github.com/firebase/php-jwt/pull/62) for details. Thanks to +[@johanderuijter](https://github.com/johanderuijter)! + +#### 2.2.0 / 2015-06-22 +- Add support for adding custom, optional JWT headers to `JWT::encode()`. See +[#53](https://github.com/firebase/php-jwt/pull/53/files) for details. Thanks to +[@mcocaro](https://github.com/mcocaro)! + +#### 2.1.0 / 2015-05-20 +- Add support for adding a leeway to `JWT:decode()` that accounts for clock skew +between signing and verifying entities. Thanks to [@lcabral](https://github.com/lcabral)! +- Add support for passing an object implementing the `ArrayAccess` interface for +`$keys` argument in `JWT::decode()`. Thanks to [@aztech-dev](https://github.com/aztech-dev)! + +#### 2.0.0 / 2015-04-01 +- **Note**: It is strongly recommended that you update to > v2.0.0 to address + known security vulnerabilities in prior versions when both symmetric and + asymmetric keys are used together. +- Update signature for `JWT::decode(...)` to require an array of supported + algorithms to use when verifying token signatures. + + +Tests +----- +Run the tests using phpunit: + +```bash +$ pear install PHPUnit +$ phpunit --configuration phpunit.xml.dist +PHPUnit 3.7.10 by Sebastian Bergmann. +..... +Time: 0 seconds, Memory: 2.50Mb +OK (5 tests, 5 assertions) +``` + +New Lines in private keys +----- + +If your private key contains `\n` characters, be sure to wrap it in double quotes `""` +and not single quotes `''` in order to properly interpret the escaped characters. + +License +------- +[3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause). diff --git a/plugins/login-oauth2-extras/vendor/firebase/php-jwt/composer.json b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/composer.json new file mode 100644 index 0000000..6146e2d --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/composer.json @@ -0,0 +1,36 @@ +{ + "name": "firebase/php-jwt", + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/firebase/php-jwt", + "keywords": [ + "php", + "jwt" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "license": "BSD-3-Clause", + "require": { + "php": ">=5.3.0" + }, + "suggest": { + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present" + }, + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "require-dev": { + "phpunit/phpunit": ">=4.8 <=9" + } +} diff --git a/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/BeforeValidException.php b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/BeforeValidException.php new file mode 100644 index 0000000..c147852 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/BeforeValidException.php @@ -0,0 +1,7 @@ + + * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD + * @link https://github.com/firebase/php-jwt + */ +class JWK +{ + /** + * Parse a set of JWK keys + * + * @param array $jwks The JSON Web Key Set as an associative array + * + * @return array An associative array that represents the set of keys + * + * @throws InvalidArgumentException Provided JWK Set is empty + * @throws UnexpectedValueException Provided JWK Set was invalid + * @throws DomainException OpenSSL failure + * + * @uses parseKey + */ + public static function parseKeySet(array $jwks) + { + $keys = array(); + + if (!isset($jwks['keys'])) { + throw new UnexpectedValueException('"keys" member must exist in the JWK Set'); + } + if (empty($jwks['keys'])) { + throw new InvalidArgumentException('JWK Set did not contain any keys'); + } + + foreach ($jwks['keys'] as $k => $v) { + $kid = isset($v['kid']) ? $v['kid'] : $k; + if ($key = self::parseKey($v)) { + $keys[$kid] = $key; + } + } + + if (0 === \count($keys)) { + throw new UnexpectedValueException('No supported algorithms found in JWK Set'); + } + + return $keys; + } + + /** + * Parse a JWK key + * + * @param array $jwk An individual JWK + * + * @return resource|array An associative array that represents the key + * + * @throws InvalidArgumentException Provided JWK is empty + * @throws UnexpectedValueException Provided JWK was invalid + * @throws DomainException OpenSSL failure + * + * @uses createPemFromModulusAndExponent + */ + public static function parseKey(array $jwk) + { + if (empty($jwk)) { + throw new InvalidArgumentException('JWK must not be empty'); + } + if (!isset($jwk['kty'])) { + throw new UnexpectedValueException('JWK must contain a "kty" parameter'); + } + + switch ($jwk['kty']) { + case 'RSA': + if (!empty($jwk['d'])) { + throw new UnexpectedValueException('RSA private keys are not supported'); + } + if (!isset($jwk['n']) || !isset($jwk['e'])) { + throw new UnexpectedValueException('RSA keys must contain values for both "n" and "e"'); + } + + $pem = self::createPemFromModulusAndExponent($jwk['n'], $jwk['e']); + $publicKey = \openssl_pkey_get_public($pem); + if (false === $publicKey) { + throw new DomainException( + 'OpenSSL error: ' . \openssl_error_string() + ); + } + return $publicKey; + default: + // Currently only RSA is supported + break; + } + } + + /** + * Create a public key represented in PEM format from RSA modulus and exponent information + * + * @param string $n The RSA modulus encoded in Base64 + * @param string $e The RSA exponent encoded in Base64 + * + * @return string The RSA public key represented in PEM format + * + * @uses encodeLength + */ + private static function createPemFromModulusAndExponent($n, $e) + { + $modulus = JWT::urlsafeB64Decode($n); + $publicExponent = JWT::urlsafeB64Decode($e); + + $components = array( + 'modulus' => \pack('Ca*a*', 2, self::encodeLength(\strlen($modulus)), $modulus), + 'publicExponent' => \pack('Ca*a*', 2, self::encodeLength(\strlen($publicExponent)), $publicExponent) + ); + + $rsaPublicKey = \pack( + 'Ca*a*a*', + 48, + self::encodeLength(\strlen($components['modulus']) + \strlen($components['publicExponent'])), + $components['modulus'], + $components['publicExponent'] + ); + + // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption. + $rsaOID = \pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA + $rsaPublicKey = \chr(0) . $rsaPublicKey; + $rsaPublicKey = \chr(3) . self::encodeLength(\strlen($rsaPublicKey)) . $rsaPublicKey; + + $rsaPublicKey = \pack( + 'Ca*a*', + 48, + self::encodeLength(\strlen($rsaOID . $rsaPublicKey)), + $rsaOID . $rsaPublicKey + ); + + $rsaPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" . + \chunk_split(\base64_encode($rsaPublicKey), 64) . + '-----END PUBLIC KEY-----'; + + return $rsaPublicKey; + } + + /** + * DER-encode the length + * + * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See + * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. + * + * @param int $length + * @return string + */ + private static function encodeLength($length) + { + if ($length <= 0x7F) { + return \chr($length); + } + + $temp = \ltrim(\pack('N', $length), \chr(0)); + + return \pack('Ca*', 0x80 | \strlen($temp), $temp); + } +} diff --git a/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/JWT.php b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/JWT.php new file mode 100644 index 0000000..ec1641b --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/JWT.php @@ -0,0 +1,611 @@ + + * @author Anant Narayanan + * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD + * @link https://github.com/firebase/php-jwt + */ +class JWT +{ + const ASN1_INTEGER = 0x02; + const ASN1_SEQUENCE = 0x10; + const ASN1_BIT_STRING = 0x03; + + /** + * When checking nbf, iat or expiration times, + * we want to provide some extra leeway time to + * account for clock skew. + */ + public static $leeway = 0; + + /** + * Allow the current timestamp to be specified. + * Useful for fixing a value within unit testing. + * + * Will default to PHP time() value if null. + */ + public static $timestamp = null; + + public static $supported_algs = array( + 'ES384' => array('openssl', 'SHA384'), + 'ES256' => array('openssl', 'SHA256'), + 'HS256' => array('hash_hmac', 'SHA256'), + 'HS384' => array('hash_hmac', 'SHA384'), + 'HS512' => array('hash_hmac', 'SHA512'), + 'RS256' => array('openssl', 'SHA256'), + 'RS384' => array('openssl', 'SHA384'), + 'RS512' => array('openssl', 'SHA512'), + 'EdDSA' => array('sodium_crypto', 'EdDSA'), + ); + + /** + * Decodes a JWT string into a PHP object. + * + * @param string $jwt The JWT + * @param Key|array|mixed $keyOrKeyArray The Key or array of Key objects. + * If the algorithm used is asymmetric, this is the public key + * Each Key object contains an algorithm and matching key. + * Supported algorithms are 'ES384','ES256', 'HS256', 'HS384', + * 'HS512', 'RS256', 'RS384', and 'RS512' + * @param array $allowed_algs [DEPRECATED] List of supported verification algorithms. Only + * should be used for backwards compatibility. + * + * @return object The JWT's payload as a PHP object + * + * @throws InvalidArgumentException Provided JWT was empty + * @throws UnexpectedValueException Provided JWT was invalid + * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed + * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf' + * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat' + * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim + * + * @uses jsonDecode + * @uses urlsafeB64Decode + */ + public static function decode($jwt, $keyOrKeyArray, array $allowed_algs = array()) + { + $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp; + + if (empty($keyOrKeyArray)) { + throw new InvalidArgumentException('Key may not be empty'); + } + $tks = \explode('.', $jwt); + if (\count($tks) != 3) { + throw new UnexpectedValueException('Wrong number of segments'); + } + list($headb64, $bodyb64, $cryptob64) = $tks; + if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) { + throw new UnexpectedValueException('Invalid header encoding'); + } + if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) { + throw new UnexpectedValueException('Invalid claims encoding'); + } + if (false === ($sig = static::urlsafeB64Decode($cryptob64))) { + throw new UnexpectedValueException('Invalid signature encoding'); + } + if (empty($header->alg)) { + throw new UnexpectedValueException('Empty algorithm'); + } + if (empty(static::$supported_algs[$header->alg])) { + throw new UnexpectedValueException('Algorithm not supported'); + } + + list($keyMaterial, $algorithm) = self::getKeyMaterialAndAlgorithm( + $keyOrKeyArray, + empty($header->kid) ? null : $header->kid + ); + + if (empty($algorithm)) { + // Use deprecated "allowed_algs" to determine if the algorithm is supported. + // This opens up the possibility of an attack in some implementations. + // @see https://github.com/firebase/php-jwt/issues/351 + if (!\in_array($header->alg, $allowed_algs)) { + throw new UnexpectedValueException('Algorithm not allowed'); + } + } else { + // Check the algorithm + if (!self::constantTimeEquals($algorithm, $header->alg)) { + // See issue #351 + throw new UnexpectedValueException('Incorrect key for this algorithm'); + } + } + if ($header->alg === 'ES256' || $header->alg === 'ES384') { + // OpenSSL expects an ASN.1 DER sequence for ES256/ES384 signatures + $sig = self::signatureToDER($sig); + } + + if (!static::verify("$headb64.$bodyb64", $sig, $keyMaterial, $header->alg)) { + throw new SignatureInvalidException('Signature verification failed'); + } + + // Check the nbf if it is defined. This is the time that the + // token can actually be used. If it's not yet that time, abort. + if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) { + throw new BeforeValidException( + 'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->nbf) + ); + } + + // Check that this token has been created before 'now'. This prevents + // using tokens that have been created for later use (and haven't + // correctly used the nbf claim). + if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) { + throw new BeforeValidException( + 'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->iat) + ); + } + + // Check if this token has expired. + if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) { + throw new ExpiredException('Expired token'); + } + + return $payload; + } + + /** + * Converts and signs a PHP object or array into a JWT string. + * + * @param object|array $payload PHP object or array + * @param string|resource $key The secret key. + * If the algorithm used is asymmetric, this is the private key + * @param string $alg The signing algorithm. + * Supported algorithms are 'ES384','ES256', 'HS256', 'HS384', + * 'HS512', 'RS256', 'RS384', and 'RS512' + * @param mixed $keyId + * @param array $head An array with header elements to attach + * + * @return string A signed JWT + * + * @uses jsonEncode + * @uses urlsafeB64Encode + */ + public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null) + { + $header = array('typ' => 'JWT', 'alg' => $alg); + if ($keyId !== null) { + $header['kid'] = $keyId; + } + if (isset($head) && \is_array($head)) { + $header = \array_merge($head, $header); + } + $segments = array(); + $segments[] = static::urlsafeB64Encode(static::jsonEncode($header)); + $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload)); + $signing_input = \implode('.', $segments); + + $signature = static::sign($signing_input, $key, $alg); + $segments[] = static::urlsafeB64Encode($signature); + + return \implode('.', $segments); + } + + /** + * Sign a string with a given key and algorithm. + * + * @param string $msg The message to sign + * @param string|resource $key The secret key + * @param string $alg The signing algorithm. + * Supported algorithms are 'ES384','ES256', 'HS256', 'HS384', + * 'HS512', 'RS256', 'RS384', and 'RS512' + * + * @return string An encrypted message + * + * @throws DomainException Unsupported algorithm or bad key was specified + */ + public static function sign($msg, $key, $alg = 'HS256') + { + if (empty(static::$supported_algs[$alg])) { + throw new DomainException('Algorithm not supported'); + } + list($function, $algorithm) = static::$supported_algs[$alg]; + switch ($function) { + case 'hash_hmac': + return \hash_hmac($algorithm, $msg, $key, true); + case 'openssl': + $signature = ''; + $success = \openssl_sign($msg, $signature, $key, $algorithm); + if (!$success) { + throw new DomainException("OpenSSL unable to sign data"); + } + if ($alg === 'ES256') { + $signature = self::signatureFromDER($signature, 256); + } elseif ($alg === 'ES384') { + $signature = self::signatureFromDER($signature, 384); + } + return $signature; + case 'sodium_crypto': + if (!function_exists('sodium_crypto_sign_detached')) { + throw new DomainException('libsodium is not available'); + } + try { + // The last non-empty line is used as the key. + $lines = array_filter(explode("\n", $key)); + $key = base64_decode(end($lines)); + return sodium_crypto_sign_detached($msg, $key); + } catch (Exception $e) { + throw new DomainException($e->getMessage(), 0, $e); + } + } + } + + /** + * Verify a signature with the message, key and method. Not all methods + * are symmetric, so we must have a separate verify and sign method. + * + * @param string $msg The original message (header and body) + * @param string $signature The original signature + * @param string|resource $key For HS*, a string key works. for RS*, must be a resource of an openssl public key + * @param string $alg The algorithm + * + * @return bool + * + * @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure + */ + private static function verify($msg, $signature, $key, $alg) + { + if (empty(static::$supported_algs[$alg])) { + throw new DomainException('Algorithm not supported'); + } + + list($function, $algorithm) = static::$supported_algs[$alg]; + switch ($function) { + case 'openssl': + $success = \openssl_verify($msg, $signature, $key, $algorithm); + if ($success === 1) { + return true; + } elseif ($success === 0) { + return false; + } + // returns 1 on success, 0 on failure, -1 on error. + throw new DomainException( + 'OpenSSL error: ' . \openssl_error_string() + ); + case 'sodium_crypto': + if (!function_exists('sodium_crypto_sign_verify_detached')) { + throw new DomainException('libsodium is not available'); + } + try { + // The last non-empty line is used as the key. + $lines = array_filter(explode("\n", $key)); + $key = base64_decode(end($lines)); + return sodium_crypto_sign_verify_detached($signature, $msg, $key); + } catch (Exception $e) { + throw new DomainException($e->getMessage(), 0, $e); + } + case 'hash_hmac': + default: + $hash = \hash_hmac($algorithm, $msg, $key, true); + return self::constantTimeEquals($signature, $hash); + } + } + + /** + * Decode a JSON string into a PHP object. + * + * @param string $input JSON string + * + * @return object Object representation of JSON string + * + * @throws DomainException Provided string was invalid JSON + */ + public static function jsonDecode($input) + { + if (\version_compare(PHP_VERSION, '5.4.0', '>=') && !(\defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) { + /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you + * to specify that large ints (like Steam Transaction IDs) should be treated as + * strings, rather than the PHP default behaviour of converting them to floats. + */ + $obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING); + } else { + /** Not all servers will support that, however, so for older versions we must + * manually detect large ints in the JSON string and quote them (thus converting + *them to strings) before decoding, hence the preg_replace() call. + */ + $max_int_length = \strlen((string) PHP_INT_MAX) - 1; + $json_without_bigints = \preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input); + $obj = \json_decode($json_without_bigints); + } + + if ($errno = \json_last_error()) { + static::handleJsonError($errno); + } elseif ($obj === null && $input !== 'null') { + throw new DomainException('Null result with non-null input'); + } + return $obj; + } + + /** + * Encode a PHP object into a JSON string. + * + * @param object|array $input A PHP object or array + * + * @return string JSON representation of the PHP object or array + * + * @throws DomainException Provided object could not be encoded to valid JSON + */ + public static function jsonEncode($input) + { + $json = \json_encode($input); + if ($errno = \json_last_error()) { + static::handleJsonError($errno); + } elseif ($json === 'null' && $input !== null) { + throw new DomainException('Null result with non-null input'); + } + return $json; + } + + /** + * Decode a string with URL-safe Base64. + * + * @param string $input A Base64 encoded string + * + * @return string A decoded string + */ + public static function urlsafeB64Decode($input) + { + $remainder = \strlen($input) % 4; + if ($remainder) { + $padlen = 4 - $remainder; + $input .= \str_repeat('=', $padlen); + } + return \base64_decode(\strtr($input, '-_', '+/')); + } + + /** + * Encode a string with URL-safe Base64. + * + * @param string $input The string you want encoded + * + * @return string The base64 encode of what you passed in + */ + public static function urlsafeB64Encode($input) + { + return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_')); + } + + + /** + * Determine if an algorithm has been provided for each Key + * + * @param Key|array|mixed $keyOrKeyArray + * @param string|null $kid + * + * @throws UnexpectedValueException + * + * @return array containing the keyMaterial and algorithm + */ + private static function getKeyMaterialAndAlgorithm($keyOrKeyArray, $kid = null) + { + if ( + is_string($keyOrKeyArray) + || is_resource($keyOrKeyArray) + || $keyOrKeyArray instanceof OpenSSLAsymmetricKey + ) { + return array($keyOrKeyArray, null); + } + + if ($keyOrKeyArray instanceof Key) { + return array($keyOrKeyArray->getKeyMaterial(), $keyOrKeyArray->getAlgorithm()); + } + + if (is_array($keyOrKeyArray) || $keyOrKeyArray instanceof ArrayAccess) { + if (!isset($kid)) { + throw new UnexpectedValueException('"kid" empty, unable to lookup correct key'); + } + if (!isset($keyOrKeyArray[$kid])) { + throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key'); + } + + $key = $keyOrKeyArray[$kid]; + + if ($key instanceof Key) { + return array($key->getKeyMaterial(), $key->getAlgorithm()); + } + + return array($key, null); + } + + throw new UnexpectedValueException( + '$keyOrKeyArray must be a string|resource key, an array of string|resource keys, ' + . 'an instance of Firebase\JWT\Key key or an array of Firebase\JWT\Key keys' + ); + } + + /** + * @param string $left + * @param string $right + * @return bool + */ + public static function constantTimeEquals($left, $right) + { + if (\function_exists('hash_equals')) { + return \hash_equals($left, $right); + } + $len = \min(static::safeStrlen($left), static::safeStrlen($right)); + + $status = 0; + for ($i = 0; $i < $len; $i++) { + $status |= (\ord($left[$i]) ^ \ord($right[$i])); + } + $status |= (static::safeStrlen($left) ^ static::safeStrlen($right)); + + return ($status === 0); + } + + /** + * Helper method to create a JSON error. + * + * @param int $errno An error number from json_last_error() + * + * @return void + */ + private static function handleJsonError($errno) + { + $messages = array( + JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', + JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON', + JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', + JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', + JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3 + ); + throw new DomainException( + isset($messages[$errno]) + ? $messages[$errno] + : 'Unknown JSON error: ' . $errno + ); + } + + /** + * Get the number of bytes in cryptographic strings. + * + * @param string $str + * + * @return int + */ + private static function safeStrlen($str) + { + if (\function_exists('mb_strlen')) { + return \mb_strlen($str, '8bit'); + } + return \strlen($str); + } + + /** + * Convert an ECDSA signature to an ASN.1 DER sequence + * + * @param string $sig The ECDSA signature to convert + * @return string The encoded DER object + */ + private static function signatureToDER($sig) + { + // Separate the signature into r-value and s-value + list($r, $s) = \str_split($sig, (int) (\strlen($sig) / 2)); + + // Trim leading zeros + $r = \ltrim($r, "\x00"); + $s = \ltrim($s, "\x00"); + + // Convert r-value and s-value from unsigned big-endian integers to + // signed two's complement + if (\ord($r[0]) > 0x7f) { + $r = "\x00" . $r; + } + if (\ord($s[0]) > 0x7f) { + $s = "\x00" . $s; + } + + return self::encodeDER( + self::ASN1_SEQUENCE, + self::encodeDER(self::ASN1_INTEGER, $r) . + self::encodeDER(self::ASN1_INTEGER, $s) + ); + } + + /** + * Encodes a value into a DER object. + * + * @param int $type DER tag + * @param string $value the value to encode + * @return string the encoded object + */ + private static function encodeDER($type, $value) + { + $tag_header = 0; + if ($type === self::ASN1_SEQUENCE) { + $tag_header |= 0x20; + } + + // Type + $der = \chr($tag_header | $type); + + // Length + $der .= \chr(\strlen($value)); + + return $der . $value; + } + + /** + * Encodes signature from a DER object. + * + * @param string $der binary signature in DER format + * @param int $keySize the number of bits in the key + * @return string the signature + */ + private static function signatureFromDER($der, $keySize) + { + // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE + list($offset, $_) = self::readDER($der); + list($offset, $r) = self::readDER($der, $offset); + list($offset, $s) = self::readDER($der, $offset); + + // Convert r-value and s-value from signed two's compliment to unsigned + // big-endian integers + $r = \ltrim($r, "\x00"); + $s = \ltrim($s, "\x00"); + + // Pad out r and s so that they are $keySize bits long + $r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT); + $s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT); + + return $r . $s; + } + + /** + * Reads binary DER-encoded data and decodes into a single object + * + * @param string $der the binary data in DER format + * @param int $offset the offset of the data stream containing the object + * to decode + * @return array [$offset, $data] the new offset and the decoded object + */ + private static function readDER($der, $offset = 0) + { + $pos = $offset; + $size = \strlen($der); + $constructed = (\ord($der[$pos]) >> 5) & 0x01; + $type = \ord($der[$pos++]) & 0x1f; + + // Length + $len = \ord($der[$pos++]); + if ($len & 0x80) { + $n = $len & 0x1f; + $len = 0; + while ($n-- && $pos < $size) { + $len = ($len << 8) | \ord($der[$pos++]); + } + } + + // Value + if ($type == self::ASN1_BIT_STRING) { + $pos++; // Skip the first contents octet (padding indicator) + $data = \substr($der, $pos, $len - 1); + $pos += $len - 1; + } elseif (!$constructed) { + $data = \substr($der, $pos, $len); + $pos += $len; + } else { + $data = null; + } + + return array($pos, $data); + } +} diff --git a/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/Key.php b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/Key.php new file mode 100644 index 0000000..f1ede6f --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/Key.php @@ -0,0 +1,59 @@ +keyMaterial = $keyMaterial; + $this->algorithm = $algorithm; + } + + /** + * Return the algorithm valid for this key + * + * @return string + */ + public function getAlgorithm() + { + return $this->algorithm; + } + + /** + * @return string|resource|OpenSSLAsymmetricKey + */ + public function getKeyMaterial() + { + return $this->keyMaterial; + } +} diff --git a/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/SignatureInvalidException.php b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/SignatureInvalidException.php new file mode 100644 index 0000000..d35dee9 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/firebase/php-jwt/src/SignatureInvalidException.php @@ -0,0 +1,7 @@ + + +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/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/README.md b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/README.md new file mode 100644 index 0000000..964ac80 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/README.md @@ -0,0 +1,32 @@ +# Okta Provider for OAuth 2.0 Client +[![Latest Version](https://img.shields.io/github/release/foxworth42/oauth2-okta.svg?style=flat-square)](https://github.com/foxworth42/oauth2-okta/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Total Downloads](https://img.shields.io/packagist/dt/foxworth42/oauth2-okta.svg?style=flat-square)](https://packagist.org/packages/foxworth42/oauth2-okta) +[![Build Status](https://travis-ci.org/foxworth42/oauth2-okta.svg?branch=master)](https://travis-ci.org/foxworth42/oauth2-okta) +[![Code Coverage](https://img.shields.io/coveralls/foxworth42/oauth2-okta.svg)](https://coveralls.io/r/foxworth42/oauth2-okta) + +This package provides Okta OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +## Installation + +To install, use composer: + +``` +composer require foxworth42/oauth2-okta +``` + +## Usage + +Usage is the same as The League's OAuth client, using `\Foxworth42\OAuth2\Client\Provider\Okta` as the provider. + +You must configure the Issuer URI as the `issuer` parameter. The issuer URI can be found in Okta's admin dashboard under API -> Authorization Servers. + +## Testing + +``` bash +$ ./vendor/bin/phpunit +``` + +## License + +The MIT License (MIT). Please see [License File](https://github.com/foxworth42/oauth2-okta/blob/master/LICENSE) for more information. diff --git a/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/composer.json b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/composer.json new file mode 100644 index 0000000..ee1d29a --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/composer.json @@ -0,0 +1,46 @@ +{ + "name": "foxworth42/oauth2-okta", + "type": "library", + "description": "Okta OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Ed Walker", + "email": "github@foxwire.org" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authentication", + "okta" + ], + "minimum-stability": "stable", + "require": { + "php": ">=7.1.0", + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "phpunit/phpunit": "^7.0", + "php-coveralls/php-coveralls": "^2.1", + "squizlabs/php_codesniffer": "^3.4" + }, + "autoload": { + "psr-4": { + "Foxworth42\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Foxworth42\\OAuth2\\Client\\Test\\": "tests/" + } + }, + "scripts": { + "test": "phpunit", + "check": "phpcs", + "lint": "phpcs", + "lint-fix": "phpcbf" + } +} diff --git a/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/example/index.php b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/example/index.php new file mode 100644 index 0000000..bd6e462 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/example/index.php @@ -0,0 +1,36 @@ +getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: ' . $authUrl); + exit; + +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + // State is invalid, possible CSRF attack in progress + unset($_SESSION['oauth2state']); + exit('Invalid state'); + +} else { + + // Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + + $_SESSION['token'] = serialize($token); + + // Optional: Now you have a token you can look up a users profile data + header('Location: user.php'); +} + diff --git a/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/example/provider.php b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/example/provider.php new file mode 100644 index 0000000..6baafce --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/example/provider.php @@ -0,0 +1,26 @@ +getResourceOwner($token); + + // Use these details to create a new profile + printf('Hello %s!
', $userDetails->getFirstname()); +} catch (Exception $e) { + // Failed to get user details + exit('Something went wrong: ' . $e->getMessage()); +} + +// Use this to interact with an API on the users behalf +echo "Token is: ", $token->getToken(), "
"; + +// Use this to get a new access token if the old one expires +echo "Refresh token is: ", $token->getRefreshToken(), "
"; + +// Number of seconds until the access token will expire, and need refreshing +echo "Expires at ", date('r', $token->getExpires()), "
"; + +// Allow the user to logout +echo 'Logout
'; + diff --git a/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/phpcs.xml.dist b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/phpcs.xml.dist new file mode 100644 index 0000000..bbc806c --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/phpcs.xml.dist @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + src/ + test/ + + diff --git a/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/phpunit.xml.dist b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/phpunit.xml.dist new file mode 100644 index 0000000..fb05784 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/phpunit.xml.dist @@ -0,0 +1,27 @@ + + + + + ./test + + + + + src/ + + + + + + + + diff --git a/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/src/Provider/Okta.php b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/src/Provider/Okta.php new file mode 100644 index 0000000..9afd8fe --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/src/Provider/Okta.php @@ -0,0 +1,105 @@ +issuer . '/' . $this->apiVersion; + } + + /** + * Get authorization url to begin OAuth flow + * + * @link https://developer.okta.com/docs/reference/api/oidc/#authorize + * @return string + */ + public function getBaseAuthorizationUrl() + { + return $this->getBaseApiUrl().'/authorize'; + } + + /** + * Get access token url to retrieve token + * + * @link https://developer.okta.com/docs/reference/api/oidc/#token + * @param array $params + * + * @return string + */ + public function getBaseAccessTokenUrl(array $params) + { + return $this->getBaseApiUrl().'/token'; + } + + /** + * Get provider url to fetch user details + * + * @link https://developer.okta.com/docs/reference/api/oidc/#userinfo + * @param AccessToken $token + * + * @return string + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + return $this->getBaseApiUrl().'/userinfo'; + } + + protected function getAuthorizationParameters(array $options) + { + return parent::getAuthorizationParameters($options); + } + + protected function getDefaultScopes() + { + return [ + 'openid', + 'email', + 'profile' + ]; + } + + protected function getScopeSeparator() + { + return ' '; + } + + protected function checkResponse(ResponseInterface $response, $data) + { + // @codeCoverageIgnoreStart + if (empty($data['error'])) { + return; + } + // @codeCoverageIgnoreEnd + + $code = $response->getStatusCode(); + $error = $data['error']; + + if (is_array($error)) { + $code = $error['code']; + $error = $error['message']; + } + + throw new IdentityProviderException($error, $code, $data); + } + + protected function createResourceOwner(array $response, AccessToken $token) + { + $user = new OktaUser($response); + + return $user; + } +} diff --git a/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/src/Provider/OktaUser.php b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/src/Provider/OktaUser.php new file mode 100644 index 0000000..9e39973 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/foxworth42/oauth2-okta/src/Provider/OktaUser.php @@ -0,0 +1,118 @@ +response = $response; + } + + public function getId() + { + return $this->response['sub']; + } + + /** + * Get preferred display name. + * + * @return string + */ + public function getName() + { + return $this->response['name']; + } + + /** + * Get preferred first name. + * + * @return string + */ + public function getFirstName() + { + return $this->response['given_name']; + } + + /** + * Get preferred last name. + * + * @return string + */ + public function getLastName() + { + return $this->response['family_name']; + } + + /** + * Get locale. + * + * @return string|null + */ + public function getLocale() + { + if (array_key_exists('locale', $this->response)) { + return $this->response['locale']; + } + return null; + } + + /** + * Get email address. + * + * @return string|null + */ + public function getEmail() + { + if (array_key_exists('email', $this->response)) { + return $this->response['email']; + } + return null; + } + + /** + * Get preferred username. + * + * @return string|null + */ + public function getPreferredUsername() + { + if (array_key_exists('preferred_username', $this->response)) { + return $this->response['preferred_username']; + } + return null; + } + + /** + * Get timezone for user. + * + * @return string|null + */ + public function getZoneInfo() + { + if (array_key_exists('zoneinfo', $this->response)) { + return $this->response['zoneinfo']; + } + return null; + } + + /** + * Get user data as an array. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/.editorconfig b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/.editorconfig new file mode 100644 index 0000000..cbb6ac5 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/.editorconfig @@ -0,0 +1,11 @@ +root = true +[*] +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = space +indent_size = 4 +[*.md] +indent_size = 2 +trim_trailing_whitespace = false \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/.gitignore b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/.gitignore new file mode 100644 index 0000000..d1502b0 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/.gitignore @@ -0,0 +1,2 @@ +vendor/ +composer.lock diff --git a/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/LICENSE.md b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/LICENSE.md new file mode 100644 index 0000000..c05e5c8 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Flagrow + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/README.md b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/README.md new file mode 100644 index 0000000..c5d5fcc --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/README.md @@ -0,0 +1,45 @@ +# Patreon provider for the OAuth2 Client + +[![MIT license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/gravure/oauth2-patreon/blob/master/LICENSE.md) +[![Latest Stable Version](https://img.shields.io/packagist/v/gravure/oauth2-patreon.svg)](https://packagist.org/packages/gravure/oauth2-patreon) +[![Total Downloads](https://img.shields.io/packagist/dt/gravure/oauth2-patreon.svg)](https://packagist.org/packages/gravure/oauth2-patreon) +[![Donate](https://img.shields.io/badge/patreon-support-yellow.svg)](https://www.patreon.com/flagrow) +[![Join our Discord server](https://discordapp.com/api/guilds/240489109041315840/embed.png)](https://flagrow.io/join-discord) + +This package provides Patreon OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +## Installation + +To install, use composer: + +```bash +composer require gravure/oauth2-patreon +``` + +## Configuration + +Usage is the same for every League OAuth client provider, using the following provider: + +```php +Gravure\Patreon\Oauth\Provider\Patreon +``` + +## Support our work + +We prefer to keep our work available to everyone. +In order to do so we rely on voluntary contributions on [Patreon](https://www.patreon.com/flagrow). + +## Security + +If you discover a security vulnerability within this package, please send an email to the Gravure team at security@gravure.io. All security vulnerabilities will be promptly addressed. + +Please include as many details as possible to speed up this process. + +## Links + +- [Source code on GitHub](https://github.com/gravure/oauth2-patreon) +- [Changelog](https://github.com/gravure/oauth2-patreon/blob/master/CHANGELOG.md) +- [Report an issue](https://github.com/gravure/oauth2-patreon/issues) +- [Download via Packagist](https://packagist.org/packages/gravure/oauth2-patreon) + +A package by [Gravure](https://gravure.io/). diff --git a/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/composer.json b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/composer.json new file mode 100644 index 0000000..60c2d92 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/composer.json @@ -0,0 +1,35 @@ +{ + "name": "gravure/oauth2-patreon", + "description": "Provides Patreon OAuth 2.0 support for PHP League's OAuth 2.0 Client.", + "keywords": [ + "oauth2", + "league", + "patreon" + ], + "license": "MIT", + "authors": [ + { + "name": "Daniël Klabbers", + "email": "daniel@klabbers.email", + "homepage": "http://luceos.com" + } + ], + "support": { + "issues": "https://github.com/gravure/oauth2-patreon/issues", + "source": "https://github.com/gravure/oauth2-patreon" + }, + "require": { + "php": "5.6.* || >=7.0", + "league/oauth2-client": "^1.0 || ^2.0" + }, + "autoload": { + "psr-4": { + "Gravure\\Patreon\\Oauth\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Gravure\\Patreon\\Oauth\\Tests\\": "tests/" + } + } +} diff --git a/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Exceptions/InvalidResourceException.php b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Exceptions/InvalidResourceException.php new file mode 100644 index 0000000..1cc4ef7 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Exceptions/InvalidResourceException.php @@ -0,0 +1,10 @@ +oauthBaseUrl . 'authorize'; + } + + /** + * Returns the base URL for requesting an access token. + * + * Eg. https://oauth.service.com/token + * + * @param array $params + * @return string + */ + public function getBaseAccessTokenUrl(array $params) + { + return $this->apiBaseUrl . 'token'; + } + + /** + * Returns the URL for requesting the resource owner's details. + * + * @param AccessToken $token + * @return string + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + return $this->apiBaseUrl . 'api/current_user'; + } + + protected function getAuthorizationHeaders($token = null) + { + return $token ? [ + 'Authorization' => 'Bearer ' . $token + ] : []; + } + + /** + * Returns the default scopes used by this provider. + * + * This should only be the scopes that are required to request the details + * of the resource owner, rather than all the available scopes. + * + * @return array + */ + protected function getDefaultScopes() + { + return ['users']; + } + + /** + * Checks a provider response for errors. + * + * @throws IdentityProviderException + * @param ResponseInterface $response + * @param array|string $data Parsed response data + * @return void + */ + protected function checkResponse(ResponseInterface $response, $data) + { + $error = null; + + if (isset($data['error'])) { + $error['detail'] = $data['error']; + $error['code'] = 401; + } + if (isset($data['errors']) && count($data['errors'])) { + $error = array_shift($data['errors']); + } + + if ($error) { + throw new IdentityProviderException( + $error['detail'], + $error['code'], + $response + ); + } + } + + /** + * @return string + */ + protected function getScopeSeparator() + { + return ' '; + } + + /** + * Generates a resource owner object from a successful resource owner + * details request. + * + * @param array $response + * @param AccessToken $token + * @return ResourceOwnerInterface|Patron + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + return Factory::create((array) $response); + } +} diff --git a/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Factory.php b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Factory.php new file mode 100644 index 0000000..33ff2ea --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Factory.php @@ -0,0 +1,79 @@ + Patron::class, + 'pledge' => Pledge::class, + ]; + + /** + * @param array $payload + * @return Resource + */ + public static function create(array $payload) + { + $data = array_key_exists('data', $payload) ? $payload['data'] : $payload; + $type = $data['type']; + $included = array_key_exists('included', $payload) ? $payload['included'] : []; + $relationships = array_key_exists('relationships', $payload) ? $payload['included'] : []; + + if (false === array_key_exists($type, static::$mapping)) { + throw new InvalidResourceException("Resource type $type not mapped."); + } + + $class = static::$mapping[$type]; + + /** @var Resource $resource */ + $resource = new $class; + $resource->id = $data['id']; + $resource->type = $type; + $resource->attributes = $data['attributes']; + + foreach ($relationships as $type => $relationship) { + if (!is_array($relationship['data'])) { + $relationship['data'] = (array) $relationship['data']; + } + + $resource->relationships[$type] = []; + + foreach ($relationship['data'] as $relation) { + if (! isset($relation['type'], $relation['id'])) { + continue; + } + + array_push( + $resource->relationships[$type], + static::retrieveIncluded($relation['type'], $relation['id'], $included) + ); + } + + } + + return $resource; + } + + /** + * @param $type + * @param $id + * @param array $included + * @return null|void + */ + protected static function retrieveIncluded($type, $id, array $included = []) + { + foreach ($included as $resource) { + if ($resource['type'] === $type && $resource['id'] === $id) { + return static::create($resource); + } + } + + return null; + } +} diff --git a/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Patron.php b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Patron.php new file mode 100644 index 0000000..8a01313 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Patron.php @@ -0,0 +1,71 @@ +id; + } + + /** + * @return string + */ + public function getUsername() + { + return $this->attributes['vanity']; + } + + /** + * @return string + */ + public function getAvatar() + { + return $this->attributes['image_url']; + } + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray() + { + return array_merge([ + 'id' => $this->id, + 'type' => $this->type, + ], $this->attributes); + } +} diff --git a/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Pledge.php b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Pledge.php new file mode 100644 index 0000000..94a3615 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/gravure/oauth2-patreon/src/Resources/Pledge.php @@ -0,0 +1,8 @@ +attributes) ? + $this->attributes[$name] : + null; + } +} diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.gitignore b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.gitignore new file mode 100644 index 0000000..fc0f36f --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.gitignore @@ -0,0 +1,50 @@ +# Cache and logs (Symfony2) +/app/cache/* +/app/logs/* +!app/cache/.gitkeep +!app/logs/.gitkeep + +# Email spool folder +/app/spool/* + +# Cache, session files and logs (Symfony3) +/var/cache/* +/var/logs/* +/var/sessions/* +!var/cache/.gitkeep +!var/logs/.gitkeep +!var/sessions/.gitkeep + +# Parameters +/app/config/parameters.yml +/app/config/parameters.ini + +# Managed by Composer +/app/bootstrap.php.cache +/var/bootstrap.php.cache +/bin/* +!bin/console +!bin/symfony_requirements +/vendor/ + +# Assets and user uploads +/web/bundles/ +/web/uploads/ + +# PHPUnit +/app/phpunit.xml +/phpunit.xml + +# Build data +/build/ + +# Composer +/composer.lock +/composer.phar + +# Backup entities generated with doctrine:generate:entities command +**/Entity/*~ + +# Embedded web-server pid file +/.web-server-pid +/nbproject/private/ \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.scrutinizer.yml b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.scrutinizer.yml new file mode 100644 index 0000000..d585107 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.scrutinizer.yml @@ -0,0 +1,35 @@ +filter: + excluded_paths: [test/*] +checks: + php: + code_rating: true + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true +tools: + external_code_coverage: + timeout: 600 + runs: 3 + php_analyzer: true + php_code_coverage: false + php_code_sniffer: + config: + standard: PSR2 + filter: + paths: ['src'] + php_loc: + enabled: true + excluded_dirs: [vendor, test] + php_cpd: + enabled: true + excluded_dirs: [vendor, test] diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.travis.yml b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.travis.yml new file mode 100644 index 0000000..900db89 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/.travis.yml @@ -0,0 +1,32 @@ +language: php + +sudo: false + +php: + - 5.6 + - 7.0 + - 7.1 + - 7.2 + - hhvm + +matrix: + include: + - php: 5.6 + env: 'COMPOSER_FLAGS="--prefer-stable --prefer-lowest"' + allow_failures: + - php: 5.6 + - php: hhvm + fast_finish: true + +before_script: + - travis_retry composer self-update + - travis_retry composer install --no-interaction --prefer-dist + - travis_retry phpenv rehash + +script: + - ./vendor/bin/phpcs --standard=psr2 src/ + - ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover test/ + +after_script: + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover coverage.clover diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/CONTRIBUTING.md b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/CONTRIBUTING.md new file mode 100644 index 0000000..8b979ce --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/CONTRIBUTING.md @@ -0,0 +1,40 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/mrjoops/oauth2-jira). + +## Pull Requests + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow SemVer. Randomly breaking public APIs is not an option. + +- **Create topic branches** - Don't ask us to pull from your master branch. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. + +- **Ensure tests pass!** - Please run the tests (see below) before submitting your pull request, and make sure they pass. We won't accept a patch until all tests pass. + +- **Ensure no coding standards violations** - Please run PHP Code Sniffer using the PSR-2 standard (see below) before submitting your pull request. A violation will cause the build to fail, so please make sure there are no violations. We can't accept a patch if the build fails. + +## Running Tests + +``` bash +$ ./vendor/bin/phpunit +``` + +## Running PHP Code Sniffer + +``` bash +$ ./vendor/bin/phpcs src --standard=psr2 -sp +``` + +**Happy coding**! + diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/LICENSE b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/LICENSE new file mode 100644 index 0000000..4307076 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Alexandre Lahure + +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/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/README.md b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/README.md new file mode 100644 index 0000000..21dfc5a --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/README.md @@ -0,0 +1,125 @@ +# Jira Provider for OAuth 2.0 Client + +[![Latest Version](https://img.shields.io/github/tag/mrjoops/oauth2-jira.svg?style=flat-square)](https://github.com/mrjoops/oauth2-jira/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/mrjoops/oauth2-jira/develop.svg?style=flat-square)](https://travis-ci.org/mrjoops/oauth2-jira) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/mrjoops/oauth2-jira.svg?style=flat-square)](https://scrutinizer-ci.com/g/mrjoops/oauth2-jira/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/mrjoops/oauth2-jira.svg?style=flat-square)](https://scrutinizer-ci.com/g/mrjoops/oauth2-jira) + +This package provides Jira OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +## Installation + +To install, use composer: + +``` +composer require mrjoops/oauth2-jira +``` + +## Usage + +Usage is the same as The League's OAuth client, using `\Mrjoops\OAuth2\Client\Provider\Jira` as the provider. + +### Authorization Code Flow + +```php +$provider = new Mrjoops\OAuth2\Client\Provider\Jira([ + 'clientId' => '{jira-client-id}', + 'clientSecret' => '{jira-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', +]); + +if (!isset($_GET['code'])) { + + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: '.$authUrl); + exit; + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + unset($_SESSION['oauth2state']); + exit('Invalid state'); + +} else { + + // Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the user's details + $user = $provider->getResourceOwner($token); + + // Use these details to create a new profile + printf('Hello %s!', $user->getNickname()); + + } catch (Exception $e) { + + // Failed to get user details + exit('Oh dear...'); + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); +} +``` + +### Managing Scopes + +When creating your Jira authorization URL, you can specify the state and scopes your application may authorize. + +```php +$options = [ + 'state' => 'OPTIONAL_CUSTOM_CONFIGURED_STATE', + 'scope' => ['read:jira-user','read:jira-work] // array or string +]; + +$authorizationUrl = $provider->getAuthorizationUrl($options); +``` +If neither are defined, the provider will utilize internal defaults. + +At the time of authoring this documentation, the [following scopes are available](https://developer.atlassian.com/cloud/jira/platform/oauth-2-authorization-code-grants-3lo-for-apps/#implementing-oauth-2-0-authorization-code-grants). + +- read:jira-user +- read:jira-work +- write:jira-work +- manage:jira-project +- manage:jira-configuration + +### Jira Cloud API call + +Since your Jira Cloud API URL vary, you can get it using the `getApiUrl()` method of the provider. + +```php +$request = $provider->getAuthenticatedRequest( + \Mrjoops\OAuth2\Client\Provider\Jira::METHOD_GET, + $provider->getApiUrl().'/rest/api/3/myself', + $token +); + +``` + +## Testing + +``` bash +$ ./vendor/bin/phpunit +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/mrjoops/oauth2-jira/blob/develop/CONTRIBUTING.md) for details. + +## Credits + +- [Alexandre Lahure](https://github.com/mrjoops) +- [All Contributors](https://github.com/mrjoops/oauth2-jira/contributors) + +## License + +The MIT License (MIT). Please see [License File](https://github.com/mrjoops/oauth2-jira/blob/develop/LICENSE) for more information. diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/composer.json b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/composer.json new file mode 100644 index 0000000..b68413c --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/composer.json @@ -0,0 +1,38 @@ +{ + "name": "mrjoops/oauth2-jira", + "description": "Jira OAuth 2.0 support for the PHP League's OAuth 2.0 Client", + "type": "library", + "require": { + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "phpunit/phpunit": "^5.0", + "mockery/mockery": "^1.2", + "squizlabs/php_codesniffer": "^3.3" + }, + "autoload": { + "psr-4": { + "Mrjoops\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Mrjoops\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "license": "MIT", + "authors": [ + { + "name": "Alexandre Lahure", + "email": "alexandre@lahu.re" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authorisation", + "jira" + ] +} diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/nbproject/project.properties b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/nbproject/project.properties new file mode 100644 index 0000000..06dcf7c --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/nbproject/project.properties @@ -0,0 +1,23 @@ +auxiliary.org-netbeans-modules-php-phpunit.bootstrap_2e_create_2e_tests=false +auxiliary.org-netbeans-modules-php-phpunit.bootstrap_2e_enabled=false +auxiliary.org-netbeans-modules-php-phpunit.bootstrap_2e_path= +auxiliary.org-netbeans-modules-php-phpunit.configuration_2e_enabled=false +auxiliary.org-netbeans-modules-php-phpunit.configuration_2e_path=phpunit.xml +auxiliary.org-netbeans-modules-php-phpunit.customSuite_2e_enabled=false +auxiliary.org-netbeans-modules-php-phpunit.customSuite_2e_path= +auxiliary.org-netbeans-modules-php-phpunit.phpUnit_2e_enabled=true +auxiliary.org-netbeans-modules-php-phpunit.phpUnit_2e_path=vendor/bin/phpunit +auxiliary.org-netbeans-modules-php-phpunit.test_2e_groups_2e_ask=false +auxiliary.org-netbeans-modules-php-phpunit.test_2e_run_2e_all=false +auxiliary.org-netbeans-modules-php-phpunit.test_2e_run_2e_phpunit_2e_only=false +code.analysis.excludes= +ignore.path= +include.path=${php.global.include.path} +php.version=PHP_72 +source.encoding=UTF-8 +src.dir=. +tags.asp=false +tags.short=false +test.src.dir=test +testing.providers=PhpUnit +web.root=. diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/nbproject/project.xml b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/nbproject/project.xml new file mode 100644 index 0000000..e6fc8ff --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/nbproject/project.xml @@ -0,0 +1,9 @@ + + + org.netbeans.modules.php.project + + + oauth2-jira + + + diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/Exception/JiraIdentityProviderException.php b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/Exception/JiraIdentityProviderException.php new file mode 100644 index 0000000..604aeba --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/Exception/JiraIdentityProviderException.php @@ -0,0 +1,54 @@ +getReasonPhrase() + ); + } + + /** + * Creates oauth exception from response. + * + * @param ResponseInterface $response + * @param array $data Parsed response data + * + * @return IdentityProviderException + */ + public static function oauthException(ResponseInterface $response, $data) + { + return static::fromResponse( + $response, + isset($data['error']) ? $data['error'] : $response->getReasonPhrase() + ); + } + + /** + * Creates identity exception from response. + * + * @param ResponseInterface $response + * @param string $message + * + * @return IdentityProviderException + */ + protected static function fromResponse(ResponseInterface $response, $message = null) + { + return new static($message, $response->getStatusCode(), (string) $response->getBody()); + } +} diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/Jira.php b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/Jira.php new file mode 100644 index 0000000..394ed7a --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/Jira.php @@ -0,0 +1,147 @@ +getStatusCode() >= 400) { + throw JiraIdentityProviderException::clientException($response, $data); + } elseif (isset($data['error'])) { + throw JiraIdentityProviderException::oauthException($response, $data); + } + } + + /** + * Generate a user object from a successful user details request. + * + * @param array $response + * @param AccessToken $token + * + * @return \League\OAuth2\Client\Provider\ResourceOwnerInterface + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + return new JiraResourceOwner($response); + } + + /** + * + * @return string URL used for non-OAuth API calls + */ + public function getApiUrl() + { + return $this->apiUrl; + } + + /** + * Get access token url to retrieve token + * + * @param array $params + * + * @return string + */ + public function getBaseAccessTokenUrl(array $params) + { + return 'https://accounts.atlassian.com/oauth/token'; + } + + /** + * Get authorization url to begin OAuth flow + * + * @return string + */ + public function getBaseAuthorizationUrl() + { + return 'https://accounts.atlassian.com/authorize?audience=api.atlassian.com&prompt=consent'; + } + + /** + * Get the default scopes used by this provider. + * + * This should not be a complete list of all scopes, but the minimum + * required for the provider user interface! + * + * @return array + */ + protected function getDefaultScopes() + { + return ['jira:read-user']; + } + + /** + * Get provider url to fetch user details + * + * @param AccessToken $token + * + * @return string + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + $request = $this->getAuthenticatedRequest( + self::METHOD_GET, + 'https://api.atlassian.com/oauth/token/accessible-resources', + $token + ); + + $response = $this->getParsedResponse($request); + + if (false === is_array($response)) { + throw new \UnexpectedValueException( + 'Invalid response received from Authorization Server. Expected JSON.' + ); + } + + $cloudId = $this->getValueByKey($response, '0.id'); + + $this->setApiUrl('https://api.atlassian.com/ex/jira/'.$cloudId); + + return $this->getApiUrl().'/rest/api/3/myself'; + } + + /** + * Returns the string that should be used to separate scopes when building + * the URL for requesting an access token. + * + * @return string Scope separator, defaults to ' ' + */ + protected function getScopeSeparator() + { + return ' '; + } + + /** + * + * @param string $url URL used for non-OAuth API calls + */ + protected function setApiUrl($url) + { + $this->apiUrl = $url; + } +} diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/JiraResourceOwner.php b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/JiraResourceOwner.php new file mode 100644 index 0000000..1a77751 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/src/Provider/JiraResourceOwner.php @@ -0,0 +1,78 @@ +response = $response; + } + + /** + * Get resource owner email + * + * @return string|null + */ + public function getEmail() + { + return $this->getValueByKey($this->response, 'emailAddress'); + } + + /** + * Get resource owner id + * + * @return string|null + */ + public function getId() + { + return $this->getValueByKey($this->response, 'accountId'); + } + + /** + * Get resource owner name + * + * @return string|null + */ + public function getName() + { + return $this->getValueByKey($this->response, 'displayName'); + } + + /** + * Get resource owner nickname + * + * @return string|null + */ + public function getNickname() + { + return $this->getValueByKey($this->response, 'name'); + } + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/test/src/Provider/JiraResourceOwnerTest.php b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/test/src/Provider/JiraResourceOwnerTest.php new file mode 100644 index 0000000..dda82bf --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/test/src/Provider/JiraResourceOwnerTest.php @@ -0,0 +1,74 @@ +response = json_decode(<<response); + + $this->assertEquals($user->getEmail(), 'mia@example.com'); + } + + public function testId() + { + $user = new JiraResourceOwner($this->response); + + $this->assertEquals($user->getId(), '99:27935d01-92a7-4687-8272-a9b8d3b2ae2e'); + } + + public function testName() + { + $user = new JiraResourceOwner($this->response); + + $this->assertEquals($user->getName(), 'Mia Krystof'); + } + + public function testNickname() + { + $user = new JiraResourceOwner($this->response); + + $this->assertEquals($user->getNickname(), 'mia'); + } +} diff --git a/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/test/src/Provider/JiraTest.php b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/test/src/Provider/JiraTest.php new file mode 100644 index 0000000..0bd052d --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/mrjoops/oauth2-jira/test/src/Provider/JiraTest.php @@ -0,0 +1,228 @@ +provider = new \Mrjoops\OAuth2\Client\Provider\Jira([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none', + ]); + } + + public function tearDown() + { + m::close(); + parent::tearDown(); + } + + public function testAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + parse_str($uri['query'], $query); + + $this->assertArrayHasKey('client_id', $query); + $this->assertArrayHasKey('redirect_uri', $query); + $this->assertArrayHasKey('state', $query); + $this->assertArrayHasKey('scope', $query); + $this->assertArrayHasKey('response_type', $query); + $this->assertArrayHasKey('prompt', $query); + $this->assertArrayHasKey('audience', $query); + $this->assertNotNull($this->provider->getState()); + } + + public function testScopes() + { + $scopeSeparator = ' '; + $options = ['scope' => [uniqid(), uniqid()]]; + $query = ['scope' => implode($scopeSeparator, $options['scope'])]; + $url = $this->provider->getAuthorizationUrl($options); + $encodedScope = $this->buildQueryString($query); + $this->assertContains($encodedScope, $url); + } + + public function testGetAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + + $this->assertEquals('/authorize', $uri['path']); + } + + public function testGetBaseAccessTokenUrl() + { + $params = []; + + $url = $this->provider->getBaseAccessTokenUrl($params); + $uri = parse_url($url); + + $this->assertEquals('/oauth/token', $uri['path']); + } + + public function testGetAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody') + ->andReturn('{"access_token":"mock_access_token", "scope":"read:jira-work", "token_type":"bearer"}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $response->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $this->assertEquals('mock_access_token', $token->getToken()); + $this->assertNull($token->getExpires()); + $this->assertNull($token->getRefreshToken()); + $this->assertNull($token->getResourceOwnerId()); + } + + public function testOwnerData() + { + $id = uniqid(); + $email = uniqid(); + $name = uniqid(); + $nickname = uniqid(); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse + ->shouldReceive('getBody') + ->andReturn('access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $resourceResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $resourceResponse->shouldReceive('getBody') + ->andReturn('[{"id":"mock_id","name":"mock_name","avatarUrl":"mock_avatarUrl","scopes":["mock_scopes"]}]'); + $resourceResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $resourceResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody') + ->andReturn(<<shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(3) + ->andReturn($postResponse, $resourceResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals($id, $user->getId()); + $this->assertEquals($id, $user->toArray()['accountId']); + $this->assertEquals($email, $user->getEmail()); + $this->assertEquals($email, $user->toArray()['emailAddress']); + $this->assertEquals($name, $user->getName()); + $this->assertEquals($name, $user->toArray()['displayName']); + $this->assertEquals($nickname, $user->getNickname()); + $this->assertEquals($nickname, $user->toArray()['name']); + } + + public function testExceptionThrownWhenErrorObjectReceived() + { + $status = rand(400, 600); + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"message": "Validation Failed","errors": [{"resource": "Issue","field": "title","code": "missing_field"}]}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn($status); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + + try { + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } catch (\Exception $e) { + $this->assertInstanceOf(\League\OAuth2\Client\Provider\Exception\IdentityProviderException::class, $e); + } + } + + public function testExceptionThrownWhenOAuthErrorReceived() + { + $status = 200; + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"error": "error_collection","error_description": "The code passed is incorrect or expired.","error_uri": "https://docs.atlassian.com/jira/REST/schema/error-collection#"}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn($status); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + + try { + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } catch (\Exception $e) { + $this->assertInstanceOf(\League\OAuth2\Client\Provider\Exception\IdentityProviderException::class, $e); + } + } + + public function testExceptionThrownWhenAskingForResourceOwner() + { + $status = 200; + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('some unexpected response.'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'text/html']); + $postResponse->shouldReceive('getStatusCode')->andReturn($status); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + + $token = new \League\OAuth2\Client\Token\AccessToken(['access_token' => 'mock_access_token']); + + try { + $this->provider->getResourceOwnerDetailsUrl($token); + } catch (\Exception $e) { + $this->assertInstanceOf(\UnexpectedValueException::class, $e); + } + } +} diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.gitignore b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.gitignore new file mode 100644 index 0000000..25efb0f --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.gitignore @@ -0,0 +1,9 @@ +/build +/log +/vendor +.*.cache +composer.phar +composer.lock +infection.json +infection.phar* +phpunit.xml \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.php_cs b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.php_cs new file mode 100644 index 0000000..bf14aa3 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.php_cs @@ -0,0 +1,32 @@ +files() + ->name('*.php') + ->name('*.php') + ->in(__DIR__.'/src') + ->in(__DIR__.'/test') +; + +return PhpCsFixer\Config::create() + ->setRules([ + '@Symfony' => true, + 'array_syntax' => ['syntax' => 'short'], + 'concat_space' => ['spacing' => 'one'], + 'header_comment' => ['header' => $header], + + 'blank_line_before_return' => false, + 'phpdoc_align' => false, + 'phpdoc_separation' => false, + 'phpdoc_var_without_name' => false, + ]) + ->setFinder($finder) + ; diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.scrutinizer.yml b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.scrutinizer.yml new file mode 100644 index 0000000..b18948d --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.scrutinizer.yml @@ -0,0 +1,35 @@ +filter: + excluded_paths: [test/*] +checks: + php: + code_rating: true + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true +tools: + external_code_coverage: + timeout: 600 + runs: 3 + php_analyzer: true + php_code_coverage: false + php_code_sniffer: + config: + standard: PSR2 + filter: + paths: ['src', 'test'] + php_loc: + enabled: true + excluded_dirs: [vendor, test] + php_cpd: + enabled: true + excluded_dirs: [vendor, test] diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.travis.yml b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.travis.yml new file mode 100644 index 0000000..c9d518e --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/.travis.yml @@ -0,0 +1,30 @@ +language: php + +matrix: + include: + - php: 7.2 + - php: 7.3 + - php: 7.4 + - php: 8.0 + - php: 7.2 + env: COMPOSER_FLAGS="--prefer-lowest" + allow_failures: + - php: nightly + +env: + global: + - XDEBUG_MODE=coverage + +before_script: + - travis_retry composer self-update --no-progress + - travis_retry composer update --no-interaction --no-progress $COMPOSER_FLAGS + - travis_retry phpenv rehash + - if [[ ${TRAVIS_PHP_VERSION:0:3} == "8.0" ]]; then bin/install-infection; fi; + +script: + - ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover + - if [[ ${TRAVIS_PHP_VERSION:0:3} == "8.0" ]]; then ./infection.phar --min-msi=60 --threads=4; fi; + +after_script: + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover coverage.clover diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/CHANGELOG.md b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/CHANGELOG.md new file mode 100644 index 0000000..e9229f5 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/CHANGELOG.md @@ -0,0 +1,78 @@ +# Changelog +All notable changes to `oauth2-gitlab` will be documented in this file +This project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] +Nothing yet. + +## [3.4.0] - 2021-02-08 +### Added + - Compatibility with php-gitlab-api v10 + - Test suite compatible with PHP8 + +## [3.3.0] - 2020-02-10 +### Added + - Compatibility with php-gitlab-api v10 + +## [3.2.0] - 2020-02-10 +### Changed + - Updated dependencies to those requiring up to date PHP versions + +### Removed + - Support for outdated and unsupported PHP versions (<7.2) + +## [3.1.2] - 2018-11-23 +### Changed + - Added conflict with `oauth2-client:2.4.0` due to [breaking change upstream](https://github.com/thephpleague/oauth2-client/issues/752) (#6) + +## [3.1.1] - 2018-10-01 +### Added + - PHP 7.2 and nightly added to test suite + - Infection testing added + +### Changed + - Test suite upgraded to PHPUnit 5/7 hybrid + +## [3.1.0] - 2017-11-01 +### Added + - Access scope support was implemented + +## [3.0.0] - 2017-05-31 +### Changed + - **Breaking**: Upgrade Gitlab API from v3 to v4 + - Test suite upgraded from PHPUnit 4 to 5/6 hybrid + +## [2.0.0] - 2017-02-03 +### Added + - PHP 7.1 is now officially supported and tested + +### Changed + - **Breaking**: Upgrade league/oauth2-client to major version 2 + - Included PHP-CS-Fixer + +### Removed + - PHP 5.5 is end of life and no longer supported + +## [1.1.0] - 2016-08-28 +### Added + - Added `getApiClient` method on `GitlabResourceOwner` to get an API connector + +## [1.0.0] - 2016-05-20 +### Changed + - Cleaned up everything after definitive testing for stable release + +## 1.0.0-alpha-1 - 2016-05-16 +### Added + - Original fork, feature complete + +[Unreleased]: https://github.com/omines/oauth2-gitlab/compare/3.4.0...master +[3.4.0]: https://github.com/omines/oauth2-gitlab/compare/3.3.0...3.2.0 +[3.3.0]: https://github.com/omines/oauth2-gitlab/compare/3.2.0...3.3.0 +[3.2.0]: https://github.com/omines/oauth2-gitlab/compare/3.1.2...3.2.0 +[3.1.2]: https://github.com/omines/oauth2-gitlab/compare/3.1.1...3.1.2 +[3.1.1]: https://github.com/omines/oauth2-gitlab/compare/3.1.0...3.1.1 +[3.1.0]: https://github.com/omines/oauth2-gitlab/compare/3.0.0...3.1.0 +[3.0.0]: https://github.com/omines/oauth2-gitlab/compare/2.0.0...3.0.0 +[2.0.0]: https://github.com/omines/oauth2-gitlab/compare/1.1.0...2.0.0 +[1.1.0]: https://github.com/omines/oauth2-gitlab/compare/1.0.0...1.1.0 +[1.0.0]: https://github.com/omines/oauth2-gitlab/compare/1.0.0-alpha.1...1.0.0 diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/CONTRIBUTING.md b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/CONTRIBUTING.md new file mode 100644 index 0000000..c3c5b21 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/CONTRIBUTING.md @@ -0,0 +1,7 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/omines/oauth2-gitlab). Follow +[good standards](http://www.phptherightway.com/), keep code coverage at 100%, and run `vendor/bin/php-cs-fixer fix` +before committing. diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/LICENSE b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/LICENSE new file mode 100644 index 0000000..1cdd1f4 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2021 Omines Internetbureau B.V. / Steven Maguire + +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/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/README.md b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/README.md new file mode 100644 index 0000000..9ee656a --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/README.md @@ -0,0 +1,121 @@ +# GitLab Provider for OAuth 2.0 Client +[![Latest Version](https://img.shields.io/github/release/omines/oauth2-gitlab.svg?style=flat-square)](https://github.com/omines/oauth2-gitlab/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/omines/oauth2-gitlab/master.svg?style=flat-square)](https://travis-ci.org/omines/oauth2-gitlab) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/omines/oauth2-gitlab.svg?style=flat-square)](https://scrutinizer-ci.com/g/omines/oauth2-gitlab/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/omines/oauth2-gitlab.svg?style=flat-square)](https://scrutinizer-ci.com/g/omines/oauth2-gitlab) +[![Total Downloads](https://img.shields.io/packagist/dt/omines/oauth2-gitlab.svg?style=flat-square)](https://packagist.org/packages/omines/oauth2-gitlab) + +This package provides GitLab OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). GitLab 8.17 or later is required. + +## Installation + +To install, use composer: + +``` +composer require omines/oauth2-gitlab +``` + +## Usage + +Usage is similar to the basic OAuth client, using `\Omines\OAuth2\Client\Provider\Gitlab` as the provider. + +### Authorization Code Flow + +```php +$provider = new \Omines\OAuth2\Client\Provider\Gitlab([ + 'clientId' => '{gitlab-client-id}', + 'clientSecret' => '{gitlab-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', + 'domain' => 'https://my.gitlab.example', // Optional base URL for self-hosted +]); + +if (!isset($_GET['code'])) { + + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: '.$authUrl); + exit; + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + unset($_SESSION['oauth2state']); + exit('Invalid state'); + +} else { + + // Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'], + ]); + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the user's details + $user = $provider->getResourceOwner($token); + + // Use these details to create a new profile + printf('Hello %s!', $user->getName()); + + } catch (Exception $e) { + + // Failed to get user details + exit('Oh dear...'); + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); +} +``` + +### Managing Scopes + +When creating your GitLab authorization URL, you can specify the state and scopes your application may authorize. + +```php +$options = [ + 'state' => 'OPTIONAL_CUSTOM_CONFIGURED_STATE', + 'scope' => ['read_user','openid'] // array or string +]; + +$authorizationUrl = $provider->getAuthorizationUrl($options); +``` +If neither are defined, the provider will utilize internal defaults ```'api'```. + + +### Performing API calls + +Install [`m4tthumphrey/php-gitlab-api`](https://packagist.org/packages/m4tthumphrey/php-gitlab-api) to interact with the +Gitlab API after authentication. Either connect manually: + +```php +$client = new \Gitlab\Client(); +$client->setUrl('https://my.gitlab.url/api/v4/'); +$client->authenticate($token->getToken(), \Gitlab\Client::AUTH_OAUTH_TOKEN); +``` +Or call the `getApiClient` method on `GitlabResourceOwner` which does the same implicitly. + +## Testing + +```bash +$ ./vendor/bin/phpunit +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/omines/oauth2-gitlab/blob/master/CONTRIBUTING.md) for details. + + +## Credits + +This code is a modified fork from the [official Github provider](https://github.com/thephpleague/oauth2-github) adapted +for Gitlab use, so many credits go to [Steven Maguire](https://github.com/stevenmaguire). + +## Legal + +This software was developed for internal use at [Omines Full Service Internetbureau](https://www.omines.nl/) +in Eindhoven, the Netherlands. It is shared with the general public under the permissive MIT license, without +any guarantee of fitness for any particular purpose. Refer to the included `LICENSE` file for more details. diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/bin/install-infection b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/bin/install-infection new file mode 100644 index 0000000..f131992 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/bin/install-infection @@ -0,0 +1,8 @@ +#!/bin/sh +cd $(dirname $0)/.. + +wget https://github.com/infection/infection/releases/download/0.21.0/infection.phar +wget https://github.com/infection/infection/releases/download/0.21.0/infection.phar.asc +gpg --keyserver hkps.pool.sks-keyservers.net --recv-keys 493B4AA0 +gpg --with-fingerprint --verify infection.phar.asc infection.phar +chmod +x infection.phar diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/composer.json b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/composer.json new file mode 100644 index 0000000..4429792 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/composer.json @@ -0,0 +1,51 @@ +{ + "name": "omines/oauth2-gitlab", + "description": "GitLab OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Niels Keurentjes", + "email": "niels.keurentjes@omines.com", + "homepage": "https://www.omines.nl/" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authorisation", + "gitlab" + ], + "require": { + "php": ">=7.2", + "league/oauth2-client": "^2.4.1" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^2.0", + "guzzlehttp/psr7": "^1.6", + "http-interop/http-factory-guzzle": "^1.0", + "mockery/mockery": "^1.0", + "m4tthumphrey/php-gitlab-api": "^10.0|^11.0", + "php-http/guzzle7-adapter": "^0.1", + "phpunit/phpunit": "^8.0|^9.0" + }, + "suggest": { + "m4tthumphrey/php-gitlab-api": "For further API usage using the acquired OAuth2 token" + }, + "autoload": { + "psr-4": { + "Omines\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Omines\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + } +} diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/infection.json.dist b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/infection.json.dist new file mode 100644 index 0000000..542f1da --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/infection.json.dist @@ -0,0 +1,12 @@ +{ + "timeout": 10, + "source": { + "directories": [ + "src" + ] + }, + "logs": { + "text": "log/infection.txt", + "perMutator": "log/mutators.md" + } +} \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/phpunit.xml.dist b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/phpunit.xml.dist new file mode 100644 index 0000000..1116871 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/phpunit.xml.dist @@ -0,0 +1,22 @@ + + + + + ./ + + + ./vendor + ./test + + + + + + + + + + ./test/ + + + diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/renovate.json b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/renovate.json new file mode 100644 index 0000000..2c63c08 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/renovate.json @@ -0,0 +1,2 @@ +{ +} diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/Exception/GitlabIdentityProviderException.php b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/Exception/GitlabIdentityProviderException.php new file mode 100644 index 0000000..2317ded --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/Exception/GitlabIdentityProviderException.php @@ -0,0 +1,60 @@ + + */ +class GitlabIdentityProviderException extends IdentityProviderException +{ + /** + * Creates client exception from response. + * + * @param mixed $data Parsed response data + */ + public static function clientException(ResponseInterface $response, $data): IdentityProviderException + { + return static::fromResponse( + $response, + isset($data['message']) ? $data['message'] : $response->getReasonPhrase() + ); + } + + /** + * Creates oauth exception from response. + * + * @param ResponseInterface $response Response received from upstream + * @param array $data Parsed response data + */ + public static function oauthException(ResponseInterface $response, $data): IdentityProviderException + { + return static::fromResponse( + $response, + isset($data['error']) ? $data['error'] : $response->getReasonPhrase() + ); + } + + /** + * Creates identity exception from response. + * + * @param ResponseInterface $response Response received from upstream + * @param string|null $message Parsed message + */ + protected static function fromResponse(ResponseInterface $response, $message = null): IdentityProviderException + { + return new static($message, $response->getStatusCode(), (string) $response->getBody()); + } +} diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/Gitlab.php b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/Gitlab.php new file mode 100644 index 0000000..ed2e034 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/Gitlab.php @@ -0,0 +1,117 @@ + + */ +class Gitlab extends AbstractProvider +{ + use BearerAuthorizationTrait; + + const PATH_API_USER = '/api/v4/user'; + const PATH_AUTHORIZE = '/oauth/authorize'; + const PATH_TOKEN = '/oauth/token'; + const DEFAULT_SCOPE = 'api'; + const SCOPE_SEPARATOR = ' '; + + /** @var string */ + public $domain = 'https://gitlab.com'; + + /** + * Gitlab constructor. + */ + public function __construct(array $options, array $collaborators = []) + { + if (isset($options['domain'])) { + $this->domain = $options['domain']; + } + parent::__construct($options, $collaborators); + } + + /** + * Get authorization url to begin OAuth flow. + */ + public function getBaseAuthorizationUrl(): string + { + return $this->domain . self::PATH_AUTHORIZE; + } + + /** + * Get access token url to retrieve token. + */ + public function getBaseAccessTokenUrl(array $params): string + { + return $this->domain . self::PATH_TOKEN; + } + + /** + * Get provider url to fetch user details. + */ + public function getResourceOwnerDetailsUrl(AccessToken $token): string + { + return $this->domain . self::PATH_API_USER; + } + + /** + * Get the default scopes used by GitLab. + * Current scopes are 'api', 'read_user', 'openid'. + * + * This returns an array with 'api' scope as default. + */ + protected function getDefaultScopes(): array + { + return [self::DEFAULT_SCOPE]; + } + + /** + * GitLab uses a space to separate scopes. + */ + protected function getScopeSeparator(): string + { + return self::SCOPE_SEPARATOR; + } + + /** + * Check a provider response for errors. + * + * @param ResponseInterface $response Parsed response data + * @throws IdentityProviderException + */ + protected function checkResponse(ResponseInterface $response, $data) + { + if ($response->getStatusCode() >= 400) { + throw GitlabIdentityProviderException::clientException($response, $data); + } elseif (isset($data['error'])) { + throw GitlabIdentityProviderException::oauthException($response, $data); + } + } + + /** + * Generate a user object from a successful user details request. + */ + protected function createResourceOwner(array $response, AccessToken $token): ResourceOwnerInterface + { + $user = new GitlabResourceOwner($response, $token); + + return $user->setDomain($this->domain); + } +} diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/GitlabResourceOwner.php b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/GitlabResourceOwner.php new file mode 100644 index 0000000..fda8ff8 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/src/Provider/GitlabResourceOwner.php @@ -0,0 +1,171 @@ + + */ +class GitlabResourceOwner implements ResourceOwnerInterface +{ + const PATH_API = '/api/v4/'; + + /** @var array */ + private $data; + + /** @var string */ + private $domain; + + /** @var AccessToken */ + private $token; + + /** + * Creates new resource owner. + */ + public function __construct(array $response, AccessToken $token) + { + $this->data = $response; + $this->token = $token; + } + + /** + * Returns the identifier of the authorized resource owner. + */ + public function getId(): int + { + return (int) $this->get('id'); + } + + /** + * Returns an authenticated API client. + * + * Requires optional Gitlab API client to be installed. + */ + public function getApiClient(): Client + { + if (!class_exists('\\Gitlab\\Client')) { + throw new \LogicException(__METHOD__ . ' requires package m4tthumphrey/php-gitlab-api to be installed and autoloaded'); // @codeCoverageIgnore + } + $client = new Client(); + $client->setUrl(rtrim($this->domain, '/') . self::PATH_API); + $client->authenticate($this->token->getToken(), Client::AUTH_OAUTH_TOKEN); + + return $client; + } + + public function getDomain(): string + { + return $this->domain; + } + + /** + * @return $this + */ + public function setDomain(string $domain): self + { + $this->domain = $domain; + + return $this; + } + + /** + * The full name of the owner. + */ + public function getName(): string + { + return $this->get('name'); + } + + /** + * Username of the owner. + */ + public function getUsername(): string + { + return $this->get('username'); + } + + /** + * Email address of the owner. + */ + public function getEmail(): string + { + return $this->get('email'); + } + + /** + * URL to the user's avatar. + * + * @return string|null + */ + public function getAvatarUrl(): string + { + return $this->get('avatar_url'); + } + + /** + * URL to the user's profile page. + */ + public function getProfileUrl(): string + { + return $this->get('web_url'); + } + + public function getToken(): AccessToken + { + return $this->token; + } + + /** + * Whether the user is active. + */ + public function isActive(): bool + { + return 'active' === $this->get('state'); + } + + /** + * Whether the user is an admin. + */ + public function isAdmin(): bool + { + return (bool) $this->get('is_admin', false); + } + + /** + * Whether the user is external. + */ + public function isExternal(): bool + { + return (bool) $this->get('external', true); + } + + /** + * Return all of the owner details available as an array. + */ + public function toArray(): array + { + return $this->data; + } + + /** + * @param mixed|null $default + * @return mixed|null + */ + protected function get(string $key, $default = null) + { + return isset($this->data[$key]) ? $this->data[$key] : $default; + } +} diff --git a/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/test/src/Provider/GitlabTest.php b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/test/src/Provider/GitlabTest.php new file mode 100644 index 0000000..bc28acd --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/omines/oauth2-gitlab/test/src/Provider/GitlabTest.php @@ -0,0 +1,225 @@ +provider = new \Omines\OAuth2\Client\Provider\Gitlab([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none', + ]); + } + + public function tearDown(): void + { + m::close(); + parent::tearDown(); + } + + public function testShorthandedSelfhostedConstructor() + { + $provider = new \Omines\OAuth2\Client\Provider\Gitlab([ + 'domain' => 'https://gitlab.example.org', + ]); + $this->assertSame('https://gitlab.example.org', $provider->domain); + } + + public function testAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + parse_str($uri['query'], $query); + + $this->assertArrayHasKey('client_id', $query); + $this->assertArrayHasKey('redirect_uri', $query); + $this->assertArrayHasKey('state', $query); + $this->assertArrayHasKey('scope', $query); + $this->assertArrayHasKey('response_type', $query); + $this->assertArrayHasKey('approval_prompt', $query); + $this->assertNotNull($this->provider->getState()); + } + + public function testScopes() + { + $options = ['scope' => [uniqid(), uniqid()]]; + + $url = $this->provider->getAuthorizationUrl($options); + + $this->assertStringContainsString(rawurlencode(implode(Gitlab::SCOPE_SEPARATOR, $options['scope'])), $url); + } + + public function testGetAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + + $this->assertEquals('/oauth/authorize', $uri['path']); + } + + public function testGetBaseAccessTokenUrl() + { + $params = []; + + $url = $this->provider->getBaseAccessTokenUrl($params); + $uri = parse_url($url); + + $this->assertEquals('/oauth/token', $uri['path']); + } + + public function testGetAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token", "scope":"repo,gist", "token_type":"bearer"}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $response->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $this->assertEquals('mock_access_token', $token->getToken()); + $this->assertNull($token->getExpires()); + $this->assertNull($token->getRefreshToken()); + $this->assertNull($token->getResourceOwnerId()); + } + + public function testSelfHostedGitlabDomainUrls() + { + $this->provider->domain = 'https://gitlab.company.com'; + + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->times(1)->andReturn('access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + $response->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $this->assertEquals($this->provider->domain . '/oauth/authorize', $this->provider->getBaseAuthorizationUrl()); + $this->assertEquals($this->provider->domain . '/oauth/token', $this->provider->getBaseAccessTokenUrl([])); + $this->assertEquals($this->provider->domain . '/api/v4/user', $this->provider->getResourceOwnerDetailsUrl($token)); + //$this->assertEquals($this->provider->domain.'/api/v4/user/emails', $this->provider->urlUserEmails($token)); + } + + public function testUserData() + { + $userdata = [ + 'id' => rand(1000, 9999), + 'name' => uniqid('name'), + 'username' => uniqid('username'), + 'email' => uniqid('email'), + 'avatar_url' => 'https://example.org/' . uniqid('avatar'), + 'web_url' => 'https://example.org/' . uniqid('web'), + 'state' => 'active', + 'is_admin' => true, + 'external' => true, + ]; + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn(json_encode($userdata)); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + /** @var ClientInterface $client */ + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + /* @var GitlabResourceOwner $user */ + $this->assertSame($userdata, $user->toArray()); + $this->assertEquals($userdata['id'], $user->getId()); + $this->assertEquals($userdata['name'], $user->getName()); + $this->assertEquals($userdata['username'], $user->getUsername()); + $this->assertEquals($userdata['email'], $user->getEmail()); + $this->assertEquals($userdata['avatar_url'], $user->getAvatarUrl()); + $this->assertEquals($userdata['web_url'], $user->getProfileUrl()); + $this->assertEquals('https://gitlab.com', $user->getDomain()); + $this->assertEquals('mock_access_token', $user->getToken()->getToken()); + $this->assertTrue($user->isActive()); + $this->assertTrue($user->isAdmin()); + $this->assertTrue($user->isExternal()); + + return $user; + } + + /** + * @depends testUserData + */ + public function testApiClient(GitlabResourceOwner $owner) + { + $client = $owner->getApiClient(); + $this->assertInstanceOf(\Gitlab\Client::class, $client); + } + + public function testExceptionThrownWhenErrorObjectReceived() + { + $status = rand(400, 600); + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"message": "Validation Failed","errors": [{"resource": "Issue","field": "title","code": "missing_field"}]}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn($status); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + + $this->expectException(IdentityProviderException::class); + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } + + public function testExceptionThrownWhenOAuthErrorReceived() + { + $status = 200; + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"error": "bad_verification_code","error_description": "The code passed is incorrect or expired.","error_uri": "https://developer.github.com/v4/oauth/#bad-verification-code"}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn($status); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + + $this->expectException(IdentityProviderException::class); + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } +} diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.gitignore b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.gitignore new file mode 100644 index 0000000..e8c7cb6 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.gitignore @@ -0,0 +1,4 @@ +/build +/vendor +composer.phar +composer.lock \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.scrutinizer.yml b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.scrutinizer.yml new file mode 100644 index 0000000..1f831e8 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.scrutinizer.yml @@ -0,0 +1,35 @@ +filter: + excluded_paths: [test/*] +checks: + php: + code_rating: true + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true +tools: + external_code_coverage: + timeout: 600 + runs: 2 + php_analyzer: true + php_code_coverage: false + php_code_sniffer: + config: + standard: PSR2 + filter: + paths: ['src'] + php_loc: + enabled: true + excluded_dirs: [examples, vendor, test] + php_cpd: + enabled: true + excluded_dirs: [examples, vendor, test] diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.travis.yml b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.travis.yml new file mode 100644 index 0000000..87831a5 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/.travis.yml @@ -0,0 +1,26 @@ +language: php + +sudo: false + +php: + - 5.6 + - 7.0 + - 7.1 + +matrix: + include: + - php: 5.6 + env: 'COMPOSER_FLAGS="--prefer-stable --prefer-lowest"' + +before_script: + - travis_retry composer self-update + - travis_retry composer install --no-interaction --prefer-source --dev + - travis_retry phpenv rehash + +script: + - ./vendor/bin/phpcs --standard=psr2 src/ + - ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover + +after_script: + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover coverage.clover diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/CHANGELOG.md b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/CHANGELOG.md new file mode 100644 index 0000000..e1990de --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/CHANGELOG.md @@ -0,0 +1,74 @@ +# Changelog +All Notable changes to `oauth2-keycloak` will be documented in this file + +## 2.1.0 - 2018-03-12 + +### Added +- Introduce `getLogoutUrl` method on provider to build and return and authorized logout url - thanks @FlxPeters + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 2.0.0 - 2017-01-25 + +### Added +- PHP 7.1 Support + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- PHP 5.5 Support + +### Security +- Nothing + +## 1.0.0 - 2017-01-25 + +Bump for base package parity + +## 0.2.0 - 2016-12-07 + +### Added +- JSON Web Token decryption support + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.1.0 - 2015-08-31 + +### Added +- Initial release! + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/CONTRIBUTING.md b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/CONTRIBUTING.md new file mode 100644 index 0000000..e1e0781 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/stevenmaguire/oauth2-keycloak). + + +## Pull Requests + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow SemVer. Randomly breaking public APIs is not an option. + +- **Create topic branches** - Don't ask us to pull from your master branch. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. + +- **Ensure tests pass!** - Please run the tests (see below) before submitting your pull request, and make sure they pass. We won't accept a patch until all tests pass. + +- **Ensure no coding standards violations** - Please run PHP Code Sniffer using the PSR-2 standard (see below) before submitting your pull request. A violation will cause the build to fail, so please make sure there are no violations. We can't accept a patch if the build fails. + + +## Running Tests + +``` bash +$ ./vendor/bin/phpunit +``` + + +## Running PHP Code Sniffer + +``` bash +$ ./vendor/bin/phpcs src --standard=psr2 -sp +``` + +**Happy coding**! diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/LICENSE b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/LICENSE new file mode 100644 index 0000000..51455e2 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Steven Maguire + +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/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/README.md b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/README.md new file mode 100644 index 0000000..e050a6d --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/README.md @@ -0,0 +1,175 @@ +# Keycloak Provider for OAuth 2.0 Client +[![Latest Version](https://img.shields.io/github/release/stevenmaguire/oauth2-keycloak.svg?style=flat-square)](https://github.com/stevenmaguire/oauth2-keycloak/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/stevenmaguire/oauth2-keycloak/master.svg?style=flat-square)](https://travis-ci.org/stevenmaguire/oauth2-keycloak) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/stevenmaguire/oauth2-keycloak.svg?style=flat-square)](https://scrutinizer-ci.com/g/stevenmaguire/oauth2-keycloak/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/stevenmaguire/oauth2-keycloak.svg?style=flat-square)](https://scrutinizer-ci.com/g/stevenmaguire/oauth2-keycloak) +[![Total Downloads](https://img.shields.io/packagist/dt/stevenmaguire/oauth2-keycloak.svg?style=flat-square)](https://packagist.org/packages/stevenmaguire/oauth2-keycloak) + +This package provides Keycloak OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +## Installation + +To install, use composer: + +``` +composer require stevenmaguire/oauth2-keycloak +``` + +## Usage + +Usage is the same as The League's OAuth client, using `\Stevenmaguire\OAuth2\Client\Provider\Keycloak` as the provider. + +Use `authServerUrl` to specify the Keycloak server URL. You can lookup the correct value from the Keycloak client installer JSON under `auth-server-url`, eg. `http://localhost:8080/auth`. + +Use `realm` to specify the Keycloak realm name. You can lookup the correct value from the Keycloak client installer JSON under `resource`, eg. `master`. + +### Authorization Code Flow + +```php +$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + 'authServerUrl' => '{keycloak-server-url}', + 'realm' => '{keycloak-realm}', + 'clientId' => '{keycloak-client-id}', + 'clientSecret' => '{keycloak-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', + 'encryptionAlgorithm' => 'RS256', // optional + 'encryptionKeyPath' => '../key.pem' // optional + 'encryptionKey' => 'contents_of_key_or_certificate' // optional +]); + +if (!isset($_GET['code'])) { + + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: '.$authUrl); + exit; + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + unset($_SESSION['oauth2state']); + exit('Invalid state, make sure HTTP sessions are enabled.'); + +} else { + + // Try to get an access token (using the authorization coe grant) + try { + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + } catch (Exception $e) { + exit('Failed to get access token: '.$e->getMessage()); + } + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the user's details + $user = $provider->getResourceOwner($token); + + // Use these details to create a new profile + printf('Hello %s!', $user->getName()); + + } catch (Exception $e) { + exit('Failed to get resource owner: '.$e->getMessage()); + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); +} +``` + +### Refreshing a Token + +```php +$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + 'authServerUrl' => '{keycloak-server-url}', + 'realm' => '{keycloak-realm}', + 'clientId' => '{keycloak-client-id}', + 'clientSecret' => '{keycloak-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', +]); + +$token = $provider->getAccessToken('refresh_token', ['refresh_token' => $token->getRefreshToken()]); +``` + +### Handling encryption + +If you've configured your Keycloak instance to use encryption, there are some advanced options available to you. + +#### Configure the provider to use the same encryption algorithm + +```php +$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + // ... + 'encryptionAlgorithm' => 'RS256', +]); +``` + +or + +```php +$provider->setEncryptionAlgorithm('RS256'); +``` + +#### Configure the provider to use the expected decryption public key or certificate + +##### By key value + +```php +$key = "-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----"; +// or +// $key = "-----BEGIN CERTIFICATE-----\n....\n-----END CERTIFICATE-----"; + +$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + // ... + 'encryptionKey' => $key, +]); +``` + +or + +```php +$provider->setEncryptionKey($key); +``` + +##### By key path + +```php +$keyPath = '../key.pem'; + +$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + // ... + 'encryptionKeyPath' => $keyPath, +]); +``` + +or + +```php +$provider->setEncryptionKeyPath($keyPath); +``` + +## Testing + +``` bash +$ ./vendor/bin/phpunit +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/stevenmaguire/oauth2-keycloak/blob/master/CONTRIBUTING.md) for details. + + +## Credits + +- [Steven Maguire](https://github.com/stevenmaguire) +- [Martin Stefan](https://github.com/mstefan21) +- [All Contributors](https://github.com/stevenmaguire/oauth2-keycloak/contributors) + + +## License + +The MIT License (MIT). Please see [License File](https://github.com/stevenmaguire/oauth2-keycloak/blob/master/LICENSE) for more information. diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/composer.json b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/composer.json new file mode 100644 index 0000000..cfafe40 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/composer.json @@ -0,0 +1,44 @@ +{ + "name": "stevenmaguire/oauth2-keycloak", + "description": "Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authorisation", + "keycloak" + ], + "require": { + "league/oauth2-client": "^2.0 <2.3.0", + "firebase/php-jwt": "~4.0|~5.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0", + "mockery/mockery": "~0.9", + "squizlabs/php_codesniffer": "~2.0" + }, + "autoload": { + "psr-4": { + "Stevenmaguire\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Stevenmaguire\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/examples/index.php b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/examples/index.php new file mode 100644 index 0000000..398333f --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/examples/index.php @@ -0,0 +1,53 @@ + '', + 'realm' => '', + 'clientId' => '', + 'clientSecret' => '', + 'redirectUri' => '', + 'encryptionAlgorithm' => null, + 'encryptionKey' => null, + 'encryptionKeyPath' => null +]); + +if (!isset($_GET['code'])) { + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: '.$authUrl); + exit; + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + unset($_SESSION['oauth2state']); + exit('Invalid state, make sure HTTP sessions are enabled.'); +} else { + // Try to get an access token (using the authorization coe grant) + try { + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + } catch (Exception $e) { + exit('Failed to get access token: '.$e->getMessage()); + } + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the user's details + $user = $provider->getResourceOwner($token); + // Use these details to create a new profile + printf('Hello %s!\n
', $user->getName()); + + } catch (Exception $e) { + exit('Failed to get resource owner: '.$e->getMessage()); + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); +} diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/phpunit.xml.dist b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/phpunit.xml.dist new file mode 100644 index 0000000..04d164d --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/phpunit.xml.dist @@ -0,0 +1,38 @@ + + + + + + + + + ./test/ + + + + + ./ + + ./examples + ./vendor + ./test + + + + diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/src/Provider/Exception/EncryptionConfigurationException.php b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/src/Provider/Exception/EncryptionConfigurationException.php new file mode 100644 index 0000000..546d2de --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/src/Provider/Exception/EncryptionConfigurationException.php @@ -0,0 +1,22 @@ +setEncryptionKeyPath($options['encryptionKeyPath']); + unset($options['encryptionKeyPath']); + } + parent::__construct($options, $collaborators); + } + + /** + * Attempts to decrypt the given response. + * + * @param string|array|null $response + * + * @return string|array|null + */ + public function decryptResponse($response) + { + if (!is_string($response)) { + return $response; + } + + if ($this->usesEncryption()) { + return json_decode( + json_encode( + JWT::decode( + $response, + $this->encryptionKey, + array($this->encryptionAlgorithm) + ) + ), + true + ); + } + + throw EncryptionConfigurationException::undeterminedEncryption(); + } + + /** + * Get authorization url to begin OAuth flow + * + * @return string + */ + public function getBaseAuthorizationUrl() + { + return $this->getBaseUrlWithRealm().'/protocol/openid-connect/auth'; + } + + /** + * Get access token url to retrieve token + * + * @param array $params + * + * @return string + */ + public function getBaseAccessTokenUrl(array $params) + { + return $this->getBaseUrlWithRealm().'/protocol/openid-connect/token'; + } + + /** + * Get provider url to fetch user details + * + * @param AccessToken $token + * + * @return string + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + return $this->getBaseUrlWithRealm().'/protocol/openid-connect/userinfo'; + } + + /** + * Builds the logout URL. + * + * @param array $options + * @return string Authorization URL + */ + public function getLogoutUrl(array $options = []) + { + $base = $this->getBaseLogoutUrl(); + $params = $this->getAuthorizationParameters($options); + $query = $this->getAuthorizationQuery($params); + return $this->appendQuery($base, $query); + } + + /** + * Get logout url to logout of session token + * + * @return string + */ + private function getBaseLogoutUrl() + { + return $this->getBaseUrlWithRealm() . '/protocol/openid-connect/logout'; + } + + /** + * Creates base url from provider configuration. + * + * @return string + */ + protected function getBaseUrlWithRealm() + { + return $this->authServerUrl.'/realms/'.$this->realm; + } + + /** + * Get the default scopes used by this provider. + * + * This should not be a complete list of all scopes, but the minimum + * required for the provider user interface! + * + * @return string[] + */ + protected function getDefaultScopes() + { + return ['profile', 'email']; + } + + /** + * Returns the string that should be used to separate scopes when building + * the URL for requesting an access token. + * + * @return string Scope separator, defaults to ',' + */ + protected function getScopeSeparator() + { + return ' '; + } + + + /** + * Check a provider response for errors. + * + * @throws IdentityProviderException + * @param ResponseInterface $response + * @param string $data Parsed response data + * @return void + */ + protected function checkResponse(ResponseInterface $response, $data) + { + if (!empty($data['error'])) { + $error = $data['error'].': '.$data['error_description']; + throw new IdentityProviderException($error, 0, $data); + } + } + + /** + * Generate a user object from a successful user details request. + * + * @param array $response + * @param AccessToken $token + * @return KeycloakResourceOwner + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + return new KeycloakResourceOwner($response); + } + + /** + * Requests and returns the resource owner of given access token. + * + * @param AccessToken $token + * @return KeycloakResourceOwner + * @throws EncryptionConfigurationException + */ + public function getResourceOwner(AccessToken $token) + { + $response = $this->fetchResourceOwnerDetails($token); + + // We are always getting an array. We have to check if it is + // the array we created + if (array_key_exists('jwt', $response)) { + $response = $response['jwt']; + } + + $response = $this->decryptResponse($response); + + return $this->createResourceOwner($response, $token); + } + + /** + * Updates expected encryption algorithm of Keycloak instance. + * + * @param string $encryptionAlgorithm + * + * @return Keycloak + */ + public function setEncryptionAlgorithm($encryptionAlgorithm) + { + $this->encryptionAlgorithm = $encryptionAlgorithm; + + return $this; + } + + /** + * Updates expected encryption key of Keycloak instance. + * + * @param string $encryptionKey + * + * @return Keycloak + */ + public function setEncryptionKey($encryptionKey) + { + $this->encryptionKey = $encryptionKey; + + return $this; + } + + /** + * Updates expected encryption key of Keycloak instance to content of given + * file path. + * + * @param string $encryptionKeyPath + * + * @return Keycloak + */ + public function setEncryptionKeyPath($encryptionKeyPath) + { + try { + $this->encryptionKey = file_get_contents($encryptionKeyPath); + } catch (Exception $e) { + // Not sure how to handle this yet. + } + + return $this; + } + + /** + * Checks if provider is configured to use encryption. + * + * @return bool + */ + public function usesEncryption() + { + return (bool) $this->encryptionAlgorithm && $this->encryptionKey; + } + + /** + * Parses the response according to its content-type header. + * + * @throws UnexpectedValueException + * @param ResponseInterface $response + * @return array + */ + protected function parseResponse(ResponseInterface $response) + { + // We have a problem with keycloak when the userinfo responses + // with a jwt token + // Because it just return a jwt as string with the header + // application/jwt + // This can't be parsed to a array + // Dont know why this function only allow an array as return value... + $content = (string) $response->getBody(); + $type = $this->getContentType($response); + + if (strpos($type, 'jwt') !== false) { + // Here we make the temporary array + return ['jwt' => $content]; + } + + return parent::parseResponse($response); + } +} diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/src/Provider/KeycloakResourceOwner.php b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/src/Provider/KeycloakResourceOwner.php new file mode 100644 index 0000000..b1cca71 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/src/Provider/KeycloakResourceOwner.php @@ -0,0 +1,65 @@ +response = $response; + } + + /** + * Get resource owner id + * + * @return string|null + */ + public function getId() + { + return $this->response['sub'] ?: null; + } + + /** + * Get resource owner email + * + * @return string|null + */ + public function getEmail() + { + return $this->response['email'] ?: null; + } + + /** + * Get resource owner name + * + * @return string|null + */ + public function getName() + { + return $this->response['name'] ?: null; + } + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/test/src/Provider/KeycloakTest.php b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/test/src/Provider/KeycloakTest.php new file mode 100644 index 0000000..4c78b3e --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/stevenmaguire/oauth2-keycloak/test/src/Provider/KeycloakTest.php @@ -0,0 +1,306 @@ +provider = new \Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + 'authServerUrl' => 'http://mock.url/auth', + 'realm' => 'mock_realm', + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none', + ]); + } + + public function tearDown() + { + m::close(); + parent::tearDown(); + } + + public function testAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + parse_str($uri['query'], $query); + + $this->assertArrayHasKey('client_id', $query); + $this->assertArrayHasKey('redirect_uri', $query); + $this->assertArrayHasKey('state', $query); + $this->assertArrayHasKey('scope', $query); + $this->assertArrayHasKey('response_type', $query); + $this->assertArrayHasKey('approval_prompt', $query); + $this->assertNotNull($this->provider->getState()); + } + + public function testEncryptionAlgorithm() + { + $algorithm = uniqid(); + $provider = new \Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + 'encryptionAlgorithm' => $algorithm, + ]); + + $this->assertEquals($algorithm, $provider->encryptionAlgorithm); + + $algorithm = uniqid(); + $provider->setEncryptionAlgorithm($algorithm); + + $this->assertEquals($algorithm, $provider->encryptionAlgorithm); + } + + public function testEncryptionKey() + { + $key = uniqid(); + $provider = new \Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + 'encryptionKey' => $key, + ]); + + $this->assertEquals($key, $provider->encryptionKey); + + $key = uniqid(); + $provider->setEncryptionKey($key); + + $this->assertEquals($key, $provider->encryptionKey); + } + + public function testEncryptionKeyPath() + { + global $mockFileGetContents; + $path = uniqid(); + $key = uniqid(); + $mockFileGetContents = $key; + + $provider = new \Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + 'encryptionKeyPath' => $path, + ]); + + $this->assertEquals($key, $provider->encryptionKey); + + $path = uniqid(); + $key = uniqid(); + $mockFileGetContents = $key; + + $provider->setEncryptionKeyPath($path); + + $this->assertEquals($key, $provider->encryptionKey); + } + + public function testEncryptionKeyPathFails() + { + global $mockFileGetContents; + $path = uniqid(); + $key = uniqid(); + $mockFileGetContents = new \Exception(); + + $provider = new \Stevenmaguire\OAuth2\Client\Provider\Keycloak([ + 'encryptionKeyPath' => $path, + ]); + + $provider->setEncryptionKeyPath($path); + } + + public function testScopes() + { + $scopeSeparator = ','; + $options = ['scope' => [uniqid(), uniqid()]]; + $query = ['scope' => implode($scopeSeparator, $options['scope'])]; + $url = $this->provider->getAuthorizationUrl($options); + $encodedScope = $this->buildQueryString($query); + $this->assertContains($encodedScope, $url); + } + + public function testGetAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + + $this->assertEquals('/auth/realms/mock_realm/protocol/openid-connect/auth', $uri['path']); + } + + public function testGetLogoutUrl() + { + $url = $this->provider->getLogoutUrl(); + $uri = parse_url($url); + + $this->assertEquals('/auth/realms/mock_realm/protocol/openid-connect/logout', $uri['path']); + } + + public function testGetBaseAccessTokenUrl() + { + $params = []; + + $url = $this->provider->getBaseAccessTokenUrl($params); + $uri = parse_url($url); + + $this->assertEquals('/auth/realms/mock_realm/protocol/openid-connect/token', $uri['path']); + } + + public function testGetAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token", "scope":"email", "token_type":"bearer"}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $this->assertEquals('mock_access_token', $token->getToken()); + $this->assertNull($token->getExpires()); + $this->assertNull($token->getRefreshToken()); + $this->assertNull($token->getResourceOwnerId()); + } + + public function testUserData() + { + $userId = rand(1000,9999); + $name = uniqid(); + $nickname = uniqid(); + $email = uniqid(); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn('{"sub": '.$userId.', "name": "'.$name.'", "email": "'.$email.'"}'); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals($userId, $user->getId()); + $this->assertEquals($userId, $user->toArray()['sub']); + $this->assertEquals($name, $user->getName()); + $this->assertEquals($name, $user->toArray()['name']); + $this->assertEquals($email, $user->getEmail()); + $this->assertEquals($email, $user->toArray()['email']); + } + + public function testUserDataWithEncryption() + { + $userId = rand(1000,9999); + $name = uniqid(); + $nickname = uniqid(); + $email = uniqid(); + $jwt = uniqid(); + $algorithm = uniqid(); + $key = uniqid(); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn($jwt); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'application/jwt']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $decoder = \Mockery::mock('overload:Firebase\JWT\JWT'); + $decoder->shouldReceive('decode')->with($jwt, $key, [$algorithm])->andReturn([ + 'sub' => $userId, + 'email' => $email, + 'name' => $name, + ]); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->setEncryptionAlgorithm($algorithm) + ->setEncryptionKey($key) + ->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals($userId, $user->getId()); + $this->assertEquals($userId, $user->toArray()['sub']); + $this->assertEquals($name, $user->getName()); + $this->assertEquals($name, $user->toArray()['name']); + $this->assertEquals($email, $user->getEmail()); + $this->assertEquals($email, $user->toArray()['email']); + } + + /** + * @expectedException Stevenmaguire\OAuth2\Client\Provider\Exception\EncryptionConfigurationException + */ + public function testUserDataFailsWhenEncryptionEncounteredAndNotConfigured() + { + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn(uniqid()); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'application/jwt']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + } + + /** + * @expectedException League\OAuth2\Client\Provider\Exception\IdentityProviderException + */ + public function testErrorResponse() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->andReturn('{"error": "invalid_grant", "error_description": "Code not found"}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } + } +} diff --git a/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/.gitignore b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/.gitignore new file mode 100644 index 0000000..9c9c8f2 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/.gitignore @@ -0,0 +1,5 @@ +/build +/vendor +composer.phar +composer.lock +.DS_Store diff --git a/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/CHANGELOG.md b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/CHANGELOG.md new file mode 100644 index 0000000..689c666 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/CHANGELOG.md @@ -0,0 +1,5 @@ +# Changelog +All Notable changes to `oauth2-azure` will be documented in this file + +## v1.0.0 - 16NOV2015 +- Initial release \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/LICENSE.md b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/LICENSE.md new file mode 100644 index 0000000..196dd86 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 TheNetw.org + +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/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/README.md b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/README.md new file mode 100644 index 0000000..7e84211 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/README.md @@ -0,0 +1,232 @@ +# Azure Active Directory Provider for OAuth 2.0 Client +[![Latest Version](https://img.shields.io/github/release/thenetworg/oauth2-azure.svg?style=flat-square)](https://github.com/thenetworg/oauth2-azure/releases) +[![Total Downloads](https://img.shields.io/packagist/dt/thenetworg/oauth2-azure.svg?style=flat-square)](https://packagist.org/packages/thenetworg/oauth2-azure) +[![Software License](https://img.shields.io/packagist/l/thenetworg/oauth2-azure.svg?style=flat-square)](LICENSE.md) + +This package provides [Azure Active Directory](https://azure.microsoft.com/en-us/services/active-directory/) OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +## Table of Contents +- [Installation](#installation) +- [Usage](#usage) + - [Authorization Code Flow](#authorization-code-flow) + - [Advanced flow](#advanced-flow) + - [Using custom parameters](#using-custom-parameters) + - [**NEW** - Logging out](#logging-out) +- [Making API Requests](#making-api-requests) + - [Variables](#variables) +- [Resource Owner](#resource-owner) +- [Microsoft Graph](#microsoft-graph) +- [**NEW** - Protecting your API - *experimental*](#protecting-your-api---experimental) +- [Azure Active Directory B2C - *experimental*](#azure-active-directory-b2c---experimental) +- [Multipurpose refresh tokens - *experimental*](#multipurpose-refresh-tokens---experimental) +- [Known users](#known-users) +- [Contributing](#contributing) +- [Credits](#credits) +- [Support](#support) +- [License](#license) + +## Installation + +To install, use composer: + +``` +composer require thenetworg/oauth2-azure +``` + +## Usage + +Usage is the same as The League's OAuth client, using `\TheNetworg\OAuth2\Client\Provider\Azure` as the provider. + +### Authorization Code Flow + +```php +$provider = new TheNetworg\OAuth2\Client\Provider\Azure([ + 'clientId' => '{azure-client-id}', + 'clientSecret' => '{azure-client-secret}', + 'redirectUri' => 'https://example.com/callback-url' +]); + +if (!isset($_GET['code'])) { + + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: '.$authUrl); + exit; + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + unset($_SESSION['oauth2state']); + exit('Invalid state'); + +} else { + + // Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'], + 'resource' => 'https://graph.windows.net', + ]); + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the user's details + $me = $provider->get("me", $token); + + // Use these details to create a new profile + printf('Hello %s!', $me['givenName']); + + } catch (Exception $e) { + + // Failed to get user details + exit('Oh dear...'); + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); +} +``` + +#### Advanced flow + +The [Authorization Code Grant Flow](https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx) is a little bit different for Azure Active Directory. Instead of scopes, you specify the resource which you would like to access - there is a param `$provider->authWithResource` which will automatically populate the `resource` param of request with the value of either `$provider->resource` or `$provider->urlAPI`. This feature is mostly intended for v2.0 endpoint of Azure AD (see more [here](https://docs.microsoft.com/en-us/azure/active-directory/develop/azure-ad-endpoint-comparison#scopes-not-resources)). + +#### Using custom parameters + +With [oauth2-client](https://github.com/thephpleague/oauth2-client) of version 1.3.0 and higher, it is now possible to specify custom parameters for the authorization URL, so you can now make use of options like `prompt`, `login_hint` and similar. See the following example of obtaining an authorization URL which will force the user to reauthenticate: +```php +$authUrl = $provider->getAuthorizationUrl([ + 'prompt' => 'login' +]); +``` +You can find additional parameters [here](https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx). + +### Logging out +If you need to quickly generate a logout URL for the user, you can do following: +```php +// Assuming you have provider properly initialized. +$post_logout_redirect_uri = 'https://www.msn.com'; // The logout destination after the user is logged out from their account. +$logoutUrl = $provider->getLogoutUrl($post_logout_redirect_uri); +header('Location: '.$logoutUrl); // Redirect the user to the generated URL +``` + +## Making API Requests + +This library also provides easy interface to make it easier to interact with [Azure Graph API](https://msdn.microsoft.com/en-us/library/azure/hh974476.aspx) and [Microsoft Graph](http://graph.microsoft.io), the following methods are available on `provider` object (it also handles automatic token refresh flow should it be needed during making the request): + +- `get($ref, $accessToken, $headers = [])` +- `post($ref, $body, $accessToken, $headers = [])` +- `put($ref, $body, $accessToken, $headers = [])` +- `delete($ref, $body, $accessToken, $headers = [])` +- `patch($ref, $body, $accessToken, $headers = [])` +- `getObjects($tenant, $ref, $accessToken, $headers = [])` This is used for example for listing large amount of data - where you need to list all users for example - it automatically follows `odata.nextLink` until the end. + - `$tenant` tenant has to be provided since the `odata.nextLink` doesn't contain it. +- `request($method, $ref, $accessToken, $options = [])` See [#36](https://github.com/TheNetworg/oauth2-azure/issues/36) for use case. + +*Please note that if you need to create a custom request, the method getAuthenticatedRequest and getResponse can still be used.* + +### Variables +- `$ref` The URL reference without the leading `/`, for example `myOrganization/groups` +- `$body` The contents of the request, make has to be either string (so make sure to use `json_encode` to encode the request)s or stream (see [Guzzle HTTP](http://docs.guzzlephp.org/en/latest/request-options.html#body)) +- `$accessToken` The access token object obtained by using `getAccessToken` method +- `$headers` Ability to set custom headers for the request (see [Guzzle HTTP](http://docs.guzzlephp.org/en/latest/request-options.html#headers)) + +## Resource Owner +With version 1.1.0 and onward, the Resource Owner information is parsed from the JWT passed in `access_token` by Azure Active Directory. It exposes few attributes and one function. + +**Example:** +```php +$resourceOwner = $provider->getResourceOwner($token); +echo 'Hello, '.$resourceOwner->getFirstName().'!'; +``` +The exposed attributes and function are: +- `getId()` - Gets user's object id - unique for each user +- `getFirstName()` - Gets user's first name +- `getLastName()` - Gets user's family name/surname +- `getTenantId()` - Gets id of tenant which the user is member of +- `getUpn()` - Gets user's User Principal Name, which can be also used as user's e-mail address +- `claim($name)` - Gets any other claim (specified as `$name`) from the JWT, full list can be found [here](https://azure.microsoft.com/en-us/documentation/articles/active-directory-token-and-claims/) + +## Microsoft Graph +Calling [Microsoft Graph](http://graph.microsoft.io/) is very simple with this library. After provider initialization simply change the API URL followingly (replace `v1.0` with your desired version): +```php +$provider->urlAPI = "https://graph.microsoft.com/v1.0/"; +$provider->resource = "https://graph.microsoft.com/"; +``` +After that, when requesting access token, refresh token or so, provide the `resource` with value `https://graph.microsoft.com/` in order to be able to make calls to the Graph (see more about `resource` [here](#advanced-flow)). + +## Protecting your API - *experimental* +With version 1.2.0 you can now use this library to protect your API with Azure Active Directory authentication very easily. The Provider now also exposes `validateAccessToken(string $token)` which lets you pass an access token inside which you for example received in the `Authorization` header of the request on your API. You can use the function followingly (in vanilla PHP): +```php +// Assuming you have already initialized the $provider + +// Obtain the accessToken - in this case, we are getting it from Authorization header +$headers = getallheaders(); +// Assuming you got the value of Authorization header as "Bearer [the_access_token]" we parse it +$authorization = explode(' ', $headers['Authorization']); +$accessToken = $authorization[1]; + +try { + $claims = $provider->validateAccessToken($accessToken); +} catch (Exception $e) { + // Something happened, handle the error +} + +// The access token is valid, you can now proceed with your code. You can also access the $claims as defined in JWT - for example roles, group memberships etc. +``` + +You may also need to access some other resource from the API like the Microsoft Graph to get some additional information. In order to do that, there is `urn:ietf:params:oauth:grant-type:jwt-bearer` grant available ([RFC](https://tools.ietf.org/html/draft-jones-oauth-jwt-bearer-03)). An example (assuming you have the code above working and you have the required permissions configured correctly in the Azure AD application): +```php +$graphAccessToken = $provider->getAccessToken('jwt_bearer', [ + 'resource' => 'https://graph.microsoft.com/v1.0/', + 'assertion' => $accessToken, + 'requested_token_use' => 'on_behalf_of' +]); + +$me = $provider->get('https://graph.microsoft.com/v1.0/me', $graphAccessToken); +print_r($me); +``` +Just to make it easier so you don't have to remember entire name for `grant_type` (`urn:ietf:params:oauth:grant-type:jwt-bearer`), you just use short `jwt_bearer` instead. + +## Azure Active Directory B2C - *experimental* +You can also now very simply make use of [Azure Active Directory B2C](https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-reference-oauth-code/). Before authentication, change the endpoints using `pathAuthorize`, `pathToken` and `scope` and additionally specify your [login policy](https://azure.microsoft.com/en-gb/documentation/articles/active-directory-b2c-reference-policies/). **Please note that the B2C support is still experimental and wasn't fully tested.** +```php +$provider->pathAuthorize = "/oauth2/v2.0/authorize"; +$provider->pathToken = "/oauth2/v2.0/token"; +$provider->scope = ["idtoken"]; + +// Specify custom policy in our authorization URL +$authUrl = $provider->getAuthorizationUrl([ + 'p' => 'b2c_1_siup' +]); +``` + +## Multipurpose refresh tokens - *experimental* +In cause that you need to access multiple resources (like your API and Microsoft Graph), you can use multipurpose [refresh tokens](https://msdn.microsoft.com/en-us/library/azure/dn645538.aspx). Once obtaining a token for first resource, you can simply request another token for different resource like so: +```php +$accessToken2 = $provider->getAccessToken('refresh_token', [ + 'refresh_token' => $accessToken1->getRefreshToken(), + 'resource' => 'http://urlOfYourSecondResource' +]); +``` +At the moment, there is one issue: When you make a call to your API and the token has expired, it will have the value of `$provider->urlAPI` which is obviously wrong for `$accessToken2`. The solution is very simple - set the `$provider->urlAPI` to the resource which you want to call. This issue will be addressed in future release. **Please note that this is experimental and wasn't fully tested.** + +## Known users +If you are using this library and would like to be listed here, please let us know! +- [TheNetworg/DreamSpark-SSO](https://github.com/thenetworg/dreamspark-sso) + +## Contributing +We accept contributions via [Pull Requests on Github](https://github.com/thenetworg/oauth2-azure). + +## Credits +- [Jan Hajek](https://github.com/hajekj) ([TheNetw.org](https://thenetw.org)) +- [Vittorio Bertocci](https://github.com/vibronet) (Microsoft) + - Thanks for the splendid support while implementing #16 +- [All Contributors](https://github.com/thenetworg/oauth2-azure/contributors) + +## Support +If you find a bug or encounter any issue or have a problem/question with this library please create a [new issue](https://github.com/TheNetworg/oauth2-azure/issues). + +## License +The MIT License (MIT). Please see [License File](https://github.com/thenetworg/oauth2-azure/blob/master/LICENSE) for more information. diff --git a/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/composer.json b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/composer.json new file mode 100644 index 0000000..81ea695 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/composer.json @@ -0,0 +1,34 @@ +{ + "name": "thenetworg/oauth2-azure", + "description": "Azure Active Directory OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Jan Hajek", + "email": "jan.hajek@thenetw.org", + "homepage": "https://thenetw.org" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "microsoft", + "windows azure", + "azure", + "azure active directory", + "aad", + "sso" + ], + "require": { + "php": ">=5.5.0", + "league/oauth2-client": "~2.0", + "firebase/php-jwt": "~3.0||~4.0||~5.0" + }, + "autoload": { + "psr-4": { + "TheNetworg\\OAuth2\\Client\\": "src/" + } + } +} diff --git a/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Grant/JwtBearer.php b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Grant/JwtBearer.php new file mode 100644 index 0000000..9c28ac3 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Grant/JwtBearer.php @@ -0,0 +1,18 @@ +grantFactory->setGrant('jwt_bearer', new JwtBearer); + } + + public function getBaseAuthorizationUrl() + { + return $this->urlLogin.$this->tenant.$this->pathAuthorize; + } + + public function getBaseAccessTokenUrl(array $params) + { + return $this->urlLogin.$this->tenant.$this->pathToken; + } + + public function getAccessToken($grant, array $options = []) + { + if($this->authWithResource) { + $options['resource'] = $this->resource ? $this->resource : $this->urlAPI; + } + return parent::getAccessToken($grant, $options); + } + + protected function checkResponse(ResponseInterface $response, $data) + { + if (isset($data['odata.error']) || isset($data['error'])) { + if (isset($data['odata.error']['message']['value'])) { + $message = $data['odata.error']['message']['value']; + } elseif (isset($data['error']['message'])) { + $message = $data['error']['message']; + } elseif ( isset($data['error']) && !is_array( $data['error'] )){ + $message = $data['error']; + } else { + $message = $response->getReasonPhrase(); + } + + throw new IdentityProviderException( + $message, + $response->getStatusCode(), + $response + ); + } + } + + protected function getDefaultScopes() + { + return $this->scope; + } + + protected function getScopeSeparator() + { + return $this->scopeSeparator; + } + + protected function createAccessToken(array $response, AbstractGrant $grant) + { + return new AccessToken($response, $this); + } + + public function getResourceOwner(\League\OAuth2\Client\Token\AccessToken $token) + { + $data = $token->getIdTokenClaims(); + return $this->createResourceOwner($data, $token); + } + + public function getResourceOwnerDetailsUrl(\League\OAuth2\Client\Token\AccessToken $token) + { + return null; + } + + protected function createResourceOwner(array $response, \League\OAuth2\Client\Token\AccessToken $token) + { + return new AzureResourceOwner($response); + } + + public function getObjects($tenant, $ref, &$accessToken, $headers = []) + { + $objects = []; + + $response = null; + do { + if (filter_var($ref, FILTER_VALIDATE_URL) === FALSE) { + $ref = $tenant."/".$ref; + } + + $response = $this->request('get', $ref, $accessToken, ['headers' => $headers]); + $values = $response; + if(isset($response['value'])) $values = $response['value']; + foreach ($values as $value) { + $objects[] = $value; + } + if (isset($response['odata.nextLink'])) { + $ref = $response['odata.nextLink']; + } elseif (isset($response['@odata.nextLink'])) { + $ref = $response['@odata.nextLink']; + } + else { + $ref = null; + } + } while ($ref != null); + + return $objects; + } + + public function get($ref, &$accessToken, $headers = []) + { + $response = $this->request('get', $ref, $accessToken, ['headers' => $headers]); + + return $this->wrapResponse($response); + } + + public function post($ref, $body, &$accessToken, $headers = []) + { + $response = $this->request('post', $ref, $accessToken, ['body' => $body, 'headers' => $headers]); + + return $this->wrapResponse($response); + } + + public function put($ref, $body, &$accessToken, $headers = []) + { + $response = $this->request('put', $ref, $accessToken, ['body' => $body, 'headers' => $headers]); + + return $this->wrapResponse($response); + } + + public function delete($ref, &$accessToken, $headers = []) + { + $response = $this->request('delete', $ref, $accessToken, ['headers' => $headers]); + + return $this->wrapResponse($response); + } + + public function patch($ref, $body, &$accessToken, $headers = []) + { + $response = $this->request('patch', $ref, $accessToken, ['body' => $body, 'headers' => $headers]); + + return $this->wrapResponse($response); + } + + public function request($method, $ref, &$accessToken, $options = []) + { + if ($accessToken->hasExpired()) { + $accessToken = $this->getAccessToken('refresh_token', [ + 'refresh_token' => $accessToken->getRefreshToken() + ]); + } + + $url = null; + if (filter_var($ref, FILTER_VALIDATE_URL) !== FALSE) { + $url = $ref; + } else { + if (strpos($this->urlAPI, "graph.windows.net") === TRUE) { + $tenant = 'common'; + if (property_exists($this, 'tenant')) { + $tenant = $this->tenant; + } + $ref = "$tenant/$ref"; + + $url .= (strrpos($url, "?") === false) ? "?" : "&"; + $url .= "api-version=".$this->API_VERSION; + } + else { + $url = $this->urlAPI.$ref; + } + } + + if(isset($options['body']) && (gettype($options['body']) == 'array' || gettype($options['body']) == 'object')) { + $options['body'] = json_encode($options['body']); + } + if(!isset($options['headers']['Content-Type']) && isset($options['body'])) { + $options['headers']['Content-Type'] = 'application/json'; + } + + $request = $this->getAuthenticatedRequest($method, $url, $accessToken, $options); + $response = $this->getParsedResponse($request); + + return $response; + } + + private function wrapResponse($response) + { + if (empty($response)) { + return null; + } elseif (isset($response['value'])) { + return $response['value']; + } + + return $response; + } + + public function getClientId() + { + return $this->clientId; + } + + /** + * Obtain URL for logging out the user. + * + * @input $post_logout_redirect_uri string The URL which the user should be redirected to after logout + * + * @return string + */ + public function getLogoutUrl($post_logout_redirect_uri) + { + return 'https://login.microsoftonline.com/'.$this->tenant.'/oauth2/logout?post_logout_redirect_uri='.rawurlencode($post_logout_redirect_uri); + } + + /** + * Validate the access token you received in your application. + * + * @input $accessToken string The access token you received in the authorization header. + * + * @return array + */ + public function validateAccessToken($accessToken) + { + $keys = $this->getJwtVerificationKeys(); + $tokenClaims = (array)JWT::decode($accessToken, $keys, ['RS256']); + + if ($this->getClientId() != $tokenClaims['aud'] && $this->getClientId() != $tokenClaims['appid']) { + throw new \RuntimeException("The client_id / audience is invalid!"); + } + if($tokenClaims['nbf'] > time() || $tokenClaims['exp'] < time()) { + // Additional validation is being performed in firebase/JWT itself + throw new \RuntimeException("The id_token is invalid!"); + } + + if($this->tenant == "common") { + $this->tenant = $tokenClaims['tid']; + + $tenant = $this->getTenantDetails($this->tenant); + if($tokenClaims['iss'] != $tenant['issuer']) { + throw new \RuntimeException("Invalid token issuer!"); + } + } + else { + $tenant = $this->getTenantDetails($this->tenant); + if($tokenClaims['iss'] != $tenant['issuer']) { + throw new \RuntimeException("Invalid token issuer!"); + } + } + + return $tokenClaims; + } + + /** + * Get JWT verification keys from Azure Active Directory. + * + * @return array + */ + public function getJwtVerificationKeys() + { + $factory = $this->getRequestFactory(); + $request = $factory->getRequestWithOptions('get', 'https://login.windows.net/common/discovery/keys', []); + + $response = $this->getParsedResponse($request); + + $keys = []; + foreach ($response['keys'] as $i => $keyinfo) { + if (isset($keyinfo['x5c']) && is_array($keyinfo['x5c'])) { + foreach ($keyinfo['x5c'] as $encodedkey) { + $key = "-----BEGIN CERTIFICATE-----\n"; + $key .= wordwrap($encodedkey, 64, "\n", true); + $key .= "\n-----END CERTIFICATE-----"; + $keys[$keyinfo['kid']] = $key; + } + } + } + + return $keys; + } + + /** + * Get the specified tenant's details. + * + * @param string $tenant + * + * @return array + */ + public function getTenantDetails($tenant) + { + $factory = $this->getRequestFactory(); + $request = $factory->getRequestWithOptions('get', 'https://login.windows.net/'.$tenant.'/.well-known/openid-configuration', []); + + $response = $this->getParsedResponse($request); + + return $response; + } +} diff --git a/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Provider/AzureResourceOwner.php b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Provider/AzureResourceOwner.php new file mode 100644 index 0000000..259ef70 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Provider/AzureResourceOwner.php @@ -0,0 +1,97 @@ +data = $data; + } + + /** + * Retrieves id of resource owner. + * + * @return string|null + */ + public function getId() + { + return $this->claim('oid'); + } + + /** + * Retrieves first name of resource owner. + * + * @return string|null + */ + public function getFirstName() + { + return $this->claim('given_name'); + } + + /** + * Retrieves last name of resource owner. + * + * @return string|null + */ + public function getLastName() + { + return $this->claim('family_name'); + } + + /** + * Retrieves user principal name of resource owner. + * + * @return string|null + */ + public function getUpn() + { + return $this->claim('upn'); + } + + /** + * Retrieves tenant id of resource owner. + * + * @return string|null + */ + public function getTenantId() + { + return $this->claim('tid'); + } + + /** + * Returns a field from the parsed JWT data. + * + * @param string $name + * + * @return mixed|null + */ + public function claim($name) + { + return isset($this->data[$name]) ? $this->data[$name] : null; + } + + /** + * Returns all the data obtained about the user. + * + * @return array + */ + public function toArray() + { + return $this->data; + } +} diff --git a/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Token/AccessToken.php b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Token/AccessToken.php new file mode 100644 index 0000000..ab62d65 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/thenetworg/oauth2-azure/src/Token/AccessToken.php @@ -0,0 +1,72 @@ +idToken = $options['id_token']; + + $keys = $provider->getJwtVerificationKeys(); + $idTokenClaims = null; + try { + $tks = explode('.', $this->idToken); + // Check if the id_token contains signature + if(count($tks) == 3 && !empty($tks[2])) { + $idTokenClaims = (array)JWT::decode($this->idToken, $keys, ['RS256']); + } + else { + // The id_token is unsigned (coming from v1.0 endpoint) - https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx + + // Since idToken is not signed, we just do OAuth2 flow without validating the id_token + // // Validate the access_token signature first by parsing it as JWT into claims + // $accessTokenClaims = (array)JWT::decode($options['access_token'], $keys, ['RS256']); + // Then parse the idToken claims only without validating the signature + $idTokenClaims = (array)JWT::jsonDecode(JWT::urlsafeB64Decode($tks[1])); + } + } catch (JWT_Exception $e) { + throw new RuntimeException("Unable to parse the id_token!"); + } + if($provider->getClientId() != $idTokenClaims['aud']) { + throw new RuntimeException("The audience is invalid!"); + } + if($idTokenClaims['nbf'] > time() || $idTokenClaims['exp'] < time()) { + // Additional validation is being performed in firebase/JWT itself + throw new RuntimeException("The id_token is invalid!"); + } + + if($provider->tenant == "common") { + $provider->tenant = $idTokenClaims['tid']; + + $tenant = $provider->getTenantDetails($provider->tenant); + if($idTokenClaims['iss'] != $tenant['issuer']) { + throw new RuntimeException("Invalid token issuer!"); + } + } + else { + $tenant = $provider->getTenantDetails($provider->tenant); + if($idTokenClaims['iss'] != $tenant['issuer']) { + throw new RuntimeException("Invalid token issuer!"); + } + } + + $this->idTokenClaims = $idTokenClaims; + } + } + + public function getIdTokenClaims() + { + return $this->idTokenClaims; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/.gitignore b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/.gitignore new file mode 100644 index 0000000..c55784d --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/.gitignore @@ -0,0 +1,2 @@ +composer.lock +/vendor/ diff --git a/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/.travis.yml b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/.travis.yml new file mode 100644 index 0000000..30c0c81 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/.travis.yml @@ -0,0 +1,17 @@ +language: php + +php: + - 5.6 + - 7.0 + - 7.1 + - 7.2 + - 7.3 + - 7.4 + +cache: + directories: + - $HOME/.composer/cache/files + +before_script: + - composer self-update + - composer install --dev --no-interaction diff --git a/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/LICENCE b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/LICENCE new file mode 100644 index 0000000..268788e --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/LICENCE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Nicolas Eeckeloo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/README.md b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/README.md new file mode 100644 index 0000000..dc94073 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/README.md @@ -0,0 +1,35 @@ +# Twitch Helix Provider for OAuth 2.0 Client + +[![Build Status](https://travis-ci.com/vertisan/oauth2-twitch-helix.svg?branch=master)](https://travis-ci.com/vertisan/oauth2-twitch-helix) +[![Latest Stable Version](https://poser.pugx.org/vertisan/oauth2-twitch-helix/v)](//packagist.org/packages/vertisan/oauth2-twitch-helix) +[![License](https://poser.pugx.org/vertisan/oauth2-twitch-helix/license)](https://packagist.org/packages/vertisan/oauth2-twitch-helix) + +This package provides Twitch (new version Helix) OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +## Installation + +To install, use Composer: + +``` +composer require vertisan/oauth2-twitch-helix +``` + +## Usage + +Usage is the same as The League's OAuth client, using `Vertisan\OAuth2\Client\Provider\TwitchHelix` as the provider. + +```php +$provider = new \Vertisan\OAuth2\Client\Provider\TwitchHelix([ + 'clientId' => "YOUR_CLIENT_ID", + 'clientSecret' => "YOUR_CLIENT_SECRET", + 'redirectUri' => "http://your-redirect-uri-passed-in-twitch-dashboard", +]); +``` +You can also optionally add a `scopes` key to the array passed to the constructor. The available scopes are documented +on the [New Twitch API Reference](https://dev.twitch.tv/docs/api/reference/). + +Testing +--------- +```bash +$ ./vendor/bin/phpunit +``` diff --git a/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/composer.json b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/composer.json new file mode 100644 index 0000000..2abab21 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/composer.json @@ -0,0 +1,41 @@ +{ + "name": "vertisan/oauth2-twitch-helix", + "description": "Twitch (new version Helix) OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "oauth", + "league", + "package", + "twitch", + "client", + "helix" + ], + "license": "MIT", + "authors": [ + { + "name": "Paweł Farys", + "email": "pmg.farys@gmail.com", + "homepage": "https://github.com/vertisan" + } + ], + "require": { + "php": ">=5.6.0", + "league/oauth2-client": "^2.2.1" + }, + "require-dev": { + "phpunit/phpunit": "^5.7", + "mockery/mockery": "^1.2", + "ext-json": "*", + "squizlabs/php_codesniffer": "^3.4", + "jakub-onderka/php-parallel-lint": "^1.0" + }, + "autoload": { + "psr-4": { + "Vertisan\\OAuth2\\Client\\Provider\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Vertisan\\OAuth2\\Client\\Test\\Provider\\": "tests/" + } + } +} diff --git a/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/phpunit.xml b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/phpunit.xml new file mode 100644 index 0000000..9513c90 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/phpunit.xml @@ -0,0 +1,17 @@ + + + + + + ./tests/ + + + \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/src/Exception/TwitchHelixIdentityProviderException.php b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/src/Exception/TwitchHelixIdentityProviderException.php new file mode 100644 index 0000000..47a8633 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/src/Exception/TwitchHelixIdentityProviderException.php @@ -0,0 +1,8 @@ +getConfigurableOptions(); + $configured = array_intersect_key($options, array_flip($possible)); + + foreach ($configured as $key => $value) { + $this->$key = $value; + } + + $options = array_diff_key($options, $configured); + + parent::__construct($options); + } + + protected function getConfigurableOptions() + { + return [ + 'accessTokenMethod', + 'accessTokenResourceOwnerId', + 'scopeSeparator', + 'responseError', + 'responseCode', + 'responseResourceOwnerId', + 'scopes', + ]; + } + + public function getBaseAuthorizationUrl() + { + return $this->domain . self::PATH_AUTHORIZE; + } + + public function getBaseAccessTokenUrl(array $params) + { + return $this->domain . self::PATH_TOKEN; + } + + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + return $this->resourceDomain . self::USER_RESOURCE; + } + + public function getDefaultScopes() + { + return $this->scopes; + } + + protected function getScopeSeparator() + { + return self::SCOPE_SEPARATOR; + } + + protected function checkResponse(ResponseInterface $response, $data) + { + if (!empty($data[$this->responseError])) { + $error = $data[$this->responseError]; + $code = $this->responseCode ? $data[$this->responseCode] : 0; + + throw new TwitchHelixIdentityProviderException($error, $code, $data); + } + } + + protected function createResourceOwner(array $response, AccessToken $token) + { + return new TwitchHelixResourceOwner($response); + } + + protected function getDefaultHeaders() + { + return [ + 'Client-ID' => $this->clientId + ]; + } + + protected function getAuthorizationHeaders($token = null) + { + if ($token === null) { + return []; + } + + return [ + 'Authorization' => 'Bearer '. $token + ]; + } +} diff --git a/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/src/TwitchHelixResourceOwner.php b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/src/TwitchHelixResourceOwner.php new file mode 100644 index 0000000..7a6d2d8 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/src/TwitchHelixResourceOwner.php @@ -0,0 +1,137 @@ +response = $response['data'][0]; + } + + /** + * User’s ID. + * + * @return int + */ + public function getId() + { + return (int) $this->getValueByKey($this->response, 'id'); + } + + /** + * User’s login name. + * + * @return string + */ + public function getLogin() + { + return $this->getValueByKey($this->response, 'login'); + } + + /** + * User’s display name. + * + * @return string + */ + public function getDisplayName() + { + return $this->getValueByKey($this->response, 'display_name'); + } + + /** + * User’s broadcaster type: "partner", "affiliate", or "". + * + * @return string + */ + public function getBroadcasterType() + { + return $this->getValueByKey($this->response, 'broadcaster_type'); + } + + /** + * User’s channel description. + * + * @return string + */ + public function getDescription() + { + return $this->getValueByKey($this->response, 'description'); + } + + /** + * URL of the user’s profile image. + * + * @return string + */ + public function getProfileImageUrl() + { + return $this->getValueByKey($this->response, 'profile_image_url'); + } + + /** + * URL of the user’s offline image. + * + * @return string + */ + public function getOfflineImageUrl() + { + return $this->getValueByKey($this->response, 'offline_image_url'); + } + + /** + * Total number of views of the user’s channel. + * + * @return int + */ + public function getViewCount() + { + return (int) $this->getValueByKey($this->response, 'view_count'); + } + + /** + * User’s email address. Returned if the request includes the user:read:email scope. + * + * @return string + */ + public function getEmail() + { + return $this->getValueByKey($this->response, 'email'); + } + + /** + * User’s type: "staff", "admin", "global_mod", or "". + * + * @return string + */ + public function getType() + { + return $this->getValueByKey($this->response, 'type'); + } + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/tests/TwitchTest.php b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/tests/TwitchTest.php new file mode 100644 index 0000000..86e1ca4 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/vertisan/oauth2-twitch-helix/tests/TwitchTest.php @@ -0,0 +1,117 @@ +provider = new TwitchHelix([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none' + ]); + } + + public function tearDown() + { + m::close(); + parent::tearDown(); + } + + public function testAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + parse_str($uri['query'], $query); + $this->assertArrayHasKey('client_id', $query); + $this->assertArrayHasKey('redirect_uri', $query); + $this->assertArrayHasKey('state', $query); + $this->assertArrayHasKey('scope', $query); + $this->assertArrayHasKey('response_type', $query); + $this->assertArrayHasKey('approval_prompt', $query); + $this->assertNotNull($this->provider->getState()); + } + + public function testScopes() + { + $options = ['scope' => [uniqid('', true), uniqid('', true)]]; + $query = ['scope' => implode(TwitchHelix::SCOPE_SEPARATOR, $options['scope'])]; + $url = $this->provider->getAuthorizationUrl($options); + $this->assertContains($this->buildQueryString($query), $url); + } + + public function testGetAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + $this->assertEquals(TwitchHelix::PATH_AUTHORIZE, $uri['path']); + } + + public function testGetBaseAccessTokenUrl() + { + $params = []; + $url = $this->provider->getBaseAccessTokenUrl($params); + $uri = parse_url($url); + $this->assertEquals(TwitchHelix::PATH_TOKEN, $uri['path']); + } + + public function testGetResourceOwnerDetailsUrl() + { + $token = new AccessToken(['access_token' => 'mock_access_token']); + $url = $this->provider->getResourceOwnerDetailsUrl($token); + $uri = parse_url($url); + $this->assertEquals(TwitchHelix::USER_RESOURCE, $uri['path']); + } + + public function testGetAccessToken() + { + $response = m::mock(ResponseInterface::class); + $response->shouldReceive('getBody') + ->andReturn(json_encode([ + 'access_token' => 'mock_access_token', + 'token_type' => 'bearer', + 'expires_in' => 1000, + 'refresh_token' => 'mock_refresh_token', + ])) + ; + + $response->shouldReceive('getHeader') + ->andReturn(['content-type' => 'json']); + + $response->shouldReceive('getStatusCode') + ->andReturn(200); + + $client = m::mock(ClientInterface::class); + + $client->shouldReceive('send') + ->times(1) + ->andReturn($response); + + $this->provider + ->setHttpClient($client); + + $token = $this->provider + ->getAccessToken('authorization_code', [ + 'code' => 'mock_authorization_code' + ]) + ; + + $this->assertEquals('mock_access_token', $token->getToken()); + $this->assertLessThanOrEqual(time() + 1000, $token->getExpires()); + $this->assertGreaterThanOrEqual(time(), $token->getExpires()); + $this->assertEquals('mock_refresh_token', $token->getRefreshToken()); + $this->assertNull($token->getResourceOwnerId()); + } +} \ No newline at end of file diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.gitignore b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.gitignore new file mode 100644 index 0000000..1de294b --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.gitignore @@ -0,0 +1,10 @@ +*.swp +*~ +.coveralls.yml +build/ +composer.lock +composer.phar +coveralls.phar +test/log +vendor/ +.phpunit.result.cache diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.scrutinizer.yml b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.scrutinizer.yml new file mode 100644 index 0000000..ffefc4c --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.scrutinizer.yml @@ -0,0 +1,36 @@ +filter: + excluded_paths: [test/*] +checks: + php: + code_rating: true + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true +tools: + external_code_coverage: + timeout: 600 + runs: 3 + php_analyzer: true + php_code_coverage: false + php_code_sniffer: + config: + standard: PSR2 + filter: + paths: ['src'] + php_loc: + enabled: true + excluded_dirs: [vendor, test] + php_cpd: + enabled: true + excluded_dirs: [vendor, test] + diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.travis.yml b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.travis.yml new file mode 100644 index 0000000..6232995 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/.travis.yml @@ -0,0 +1,31 @@ +language: php + +sudo: false + +matrix: + include: + - php: 7.2 + - php: 7.3 + - php: 7.4 + - php: nightly + fast_finish: true + allow_failures: + - php: nightly + + +before_script: + - travis_retry composer self-update + - travis_retry composer install --no-interaction --prefer-source + - travis_retry phpenv rehash + +script: + - ./vendor/bin/parallel-lint src test + - ./vendor/bin/phpcs src --standard=psr2 -sp + - ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover + +after_success: + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover coverage.clover + - mkdir -p build/logs + - wget https://github.com/satooshi/php-coveralls/releases/download/v1.0.2/coveralls.phar + - travis_retry php coveralls.phar -x coverage.clover diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/CONTRIBUTING.md b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/CONTRIBUTING.md new file mode 100644 index 0000000..a3c2574 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/CONTRIBUTING.md @@ -0,0 +1,40 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/wohali/oauth2-discord-new). + + +## Pull Requests + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow SemVer. Randomly breaking public APIs is not an option. + +- **Create topic branches** - Don't ask us to pull from your master branch. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. + +- **Ensure tests pass!** - Please run the tests (see below) before submitting your pull request, and make sure they pass. We won't accept a patch until all tests pass. + +- **Ensure no coding standards violations** - Please run PHP Code Sniffer using the PSR-2 standard (see below) before submitting your pull request. A violation will cause the build to fail, so please make sure there are no violations. We can't accept a patch if the build fails. + + +## Testing + +The following tests must pass for a build to be considered successful. If contributing, please ensure these pass before submitting a pull request. Travis CI will be used to enforce a pass before a merge can occur! + +``` bash +$ ./vendor/bin/parallel-lint src test +$ ./vendor/bin/phpunit --coverage-text +$ ./vendor/bin/phpcs src --standard=psr2 -sp +``` + +**Happy coding**! + diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/LICENSE b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/LICENSE new file mode 100644 index 0000000..9c289f2 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2017 Joan Touzet + +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/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/README.md b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/README.md new file mode 100644 index 0000000..90f9521 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/README.md @@ -0,0 +1,204 @@ +# Discord Provider for OAuth 2.0 Client +[![Source Code](http://img.shields.io/badge/source-wohali/oauth2--discord--new-blue.svg?style=flat-square)](https://github.com/wohali/oauth2-discord-new) +[![Latest Version](https://img.shields.io/github/release/wohali/oauth2-discord-new.svg?style=flat-square)](https://github.com/wohali/oauth2-discord-new/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/wohali/oauth2-discord-new/master.svg?style=flat-square)](https://travis-ci.org/wohali/oauth2-discord-new) +[![Scrutinizer](https://img.shields.io/scrutinizer/g/wohali/oauth2-discord-new/master.svg?style=flat-square)](https://scrutinizer-ci.com/g/wohali/oauth2-discord-new) +[![Coverage Status](https://img.shields.io/coveralls/wohali/oauth2-discord-new/master.svg?style=flat-square)](https://coveralls.io/r/wohali/oauth2-discord-new?branch=master) +[![Total Downloads](https://img.shields.io/packagist/dt/wohali/oauth2-discord-new.svg?style=flat-square)](https://packagist.org/packages/wohali/oauth2-discord-new) + +This package provides Discord OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client), v2.0 and up. + +## Requirements + +The following versions of PHP are supported. + +* PHP 7.2 +* PHP 7.3 +* PHP 7.4 + +## Installation + +To install, use composer: + +```bash +$ composer require wohali/oauth2-discord-new +``` + +## Usage + +Usage is the same as The League's OAuth client, using `\Wohali\OAuth2\Client\Provider\Discord` as the provider. + +### Sample Authorization Code Flow + +This self-contained example: + +1. Gets an authorization code +1. Gets an access token using the provided authorization code +1. Looks up the user's profile with the provided access token + +You can try this script by [registering a Discord App](https://discord.com/developers/applications/me/create) with a redirect URI to your server's copy of this sample script. Then, place the Discord app's client id and secret, along with that same URI, into the settings at the top of the script. + +```php +
'); + +$provider = new \Wohali\OAuth2\Client\Provider\Discord([ + 'clientId' => '{discord-client-id}', + 'clientSecret' => '{discord-client-secret}', + 'redirectUri' => '{your-server-uri-to-this-script-here}' +]); + +if (!isset($_GET['code'])) { + + // Step 1. Get authorization code + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: ' . $authUrl); + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + unset($_SESSION['oauth2state']); + exit('Invalid state'); + +} else { + + // Step 2. Get an access token using the provided authorization code + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + + // Show some token details + echo '

Token details:

'; + echo 'Token: ' . $token->getToken() . "
"; + echo 'Refresh token: ' . $token->getRefreshToken() . "
"; + echo 'Expires: ' . $token->getExpires() . " - "; + echo ($token->hasExpired() ? 'expired' : 'not expired') . "
"; + + // Step 3. (Optional) Look up the user's profile with the provided token + try { + + $user = $provider->getResourceOwner($token); + + echo '

Resource owner details:

'; + printf('Hello %s#%s!

', $user->getUsername(), $user->getDiscriminator()); + var_export($user->toArray()); + + } catch (Exception $e) { + + // Failed to get user details + exit('Oh dear...'); + + } +} +``` + +### Managing Scopes + +When creating your Discord authorization URL in Step 1, you can specify the state and scopes your application may authorize. + +```php +$options = [ + 'state' => 'OPTIONAL_CUSTOM_CONFIGURED_STATE', + 'scope' => ['identify', 'email', '...'] // array or string +]; + +$authorizationUrl = $provider->getAuthorizationUrl($options); +``` +If neither are defined, the provider will utilize internal defaults. + +At the time of authoring this documentation, the [following scopes are available](https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes): + +- bot +- connections +- email +- identify +- guilds +- guilds.join +- gdm.join +- messages.read +- rpc +- rpc.api +- rpc.notifications.read +- webhook.incoming + +### Refreshing a Token + +You can refresh an expired token using a refresh token rather than going through the entire process of obtaining a brand new token. To do so, simply reuse the fresh token from your data store to request a refresh: + +```php +// create $provider as in the initial example +$existingAccessToken = getAccessTokenFromYourDataStore(); + +if ($existingAccessToken->hasExpired()) { + $newAccessToken = $provider->getAccessToken('refresh_token', [ + 'refresh_token' => $existingAccessToken->getRefreshToken() + ]); + + // Purge old access token and store new access token to your data store. +} +``` + +### Client Credentials Grant + +Discord provides a client credentials flow for bot developers to get their own bearer tokens for testing purposes. This returns an access token for the *bot owner*: + +```php +// create $provider as in the initial example +try { + + // Try to get an access token using the client credentials grant. + $accessToken = $provider->getAccessToken('client_credentials'); + +} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { + + // Failed to get the access token + exit($e->getMessage()); + +} +``` + +### Bot Authorization + +To authorize a bot, specify a scope of `bot` and set [permissions](https://discord.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags) appropriately: + +```php +// create $provider as in the initial example + +$options = [ + 'scope' => ['bot'], + 'permissions' => 1 +]; + +$authorizationUrl = $provider->getAuthorizationUrl($options); + +// Redirect user to authorization page +header('Location: ' . $authUrl); +``` + +## Testing + +``` bash +$ ./vendor/bin/parallel-lint src test +$ ./vendor/bin/phpcs src --standard=psr2 -sp +$ ./vendor/bin/phpunit --coverage-text +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/wohali/oauth2-discord-new/blob/master/CONTRIBUTING.md) for details. + +## Credits + +- [Joan Touzet](https://github.com/wohali) +- [All Contributors](https://github.com/wohali/oauth2-discord-new/contributors) + +## License + +The MIT License (MIT). Please see [License File](https://github.com/wohali/oauth2-discord-new/blob/master/LICENSE) for more information. diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/composer.json b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/composer.json new file mode 100644 index 0000000..153f15c --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/composer.json @@ -0,0 +1,48 @@ +{ + "name": "wohali/oauth2-discord-new", + "description": "Discord OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Joan Touzet", + "email": "code@atypical.net", + "homepage": "https://github.com/wohali" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authorisation", + "discord" + ], + "require": { + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "phpunit/phpunit": "~8.0", + "mockery/mockery": "~1.3.0", + "squizlabs/php_codesniffer": "^2.0", + "php-parallel-lint/php-parallel-lint": "~0.9" + }, + "autoload": { + "psr-4": { + "Wohali\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Wohali\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "conflict": { + "team-reflex/oauth2-discord": ">=1.0" + } +} + diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/coverage.clover b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/coverage.clover new file mode 100644 index 0000000..f76c4a9 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/coverage.clover @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/phpunit.xml b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/phpunit.xml new file mode 100644 index 0000000..a4c6594 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/phpunit.xml @@ -0,0 +1,35 @@ + + + + + + + + + ./test/ + + + + + ./ + + ./vendor + ./test + + + + + diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/Discord.php b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/Discord.php new file mode 100644 index 0000000..cb1a558 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/Discord.php @@ -0,0 +1,125 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link https://packagist.org/packages/wohali/oauth2-discord-new Packagist + * @link https://github.com/wohali/oauth2-discord-new GitHub + */ + +namespace Wohali\OAuth2\Client\Provider; + +use League\OAuth2\Client\Provider\AbstractProvider; +use League\OAuth2\Client\Token\AccessToken; +use League\OAuth2\Client\Tool\BearerAuthorizationTrait; +use Psr\Http\Message\ResponseInterface; +use Wohali\OAuth2\Client\Provider\Exception\DiscordIdentityProviderException; + +class Discord extends AbstractProvider +{ + use BearerAuthorizationTrait; + + /** + * API Domain + * + * @var string + */ + public $apiDomain = 'https://discord.com/api/v6'; + + /** + * Get authorization URL to begin OAuth flow + * + * @return string + */ + public function getBaseAuthorizationUrl() + { + return $this->apiDomain.'/oauth2/authorize'; + } + + /** + * Get access token URL to retrieve token + * + * @param array $params + * + * @return string + */ + public function getBaseAccessTokenUrl(array $params) + { + return $this->apiDomain.'/oauth2/token'; + } + + /** + * Get provider URL to retrieve user details + * + * @param AccessToken $token + * + * @return string + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + return $this->apiDomain.'/users/@me'; + } + + /** + * Returns the string that should be used to separate scopes when building + * the URL for requesting an access token. + * + * Discord's scope separator is space (%20) + * + * @return string Scope separator + */ + protected function getScopeSeparator() + { + return ' '; + } + + /** + * Get the default scopes used by this provider. + * + * This should not be a complete list of all scopes, but the minimum + * required for the provider user interface! + * + * @return array + */ + protected function getDefaultScopes() + { + return [ + 'identify', + 'email', + 'connections', + 'guilds', + 'guilds.join' + ]; + } + + /** + * Check a provider response for errors. + * + * @throws IdentityProviderException + * @param ResponseInterface @response + * @param array $data Parsed response data + * @return void + */ + protected function checkResponse(ResponseInterface $response, $data) + { + if ($response->getStatusCode() >= 400) { + throw DiscordIdentityProviderException::clientException($response, $data); + } + } + + /** + * Generate a user object from a successful user details request. + * + * @param array $response + * @param AccessToken $token + * @return \League\OAuth2\Client\Provider\ResourceOwnerInterface + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + return new DiscordResourceOwner($response); + } +} diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/DiscordResourceOwner.php b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/DiscordResourceOwner.php new file mode 100644 index 0000000..549948c --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/DiscordResourceOwner.php @@ -0,0 +1,109 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link https://packagist.org/packages/wohali/oauth2-discord-new Packagist + * @link https://github.com/wohali/oauth2-discord-new GitHub + */ + +namespace Wohali\OAuth2\Client\Provider; + +use League\OAuth2\Client\Provider\ResourceOwnerInterface; +use League\OAuth2\Client\Tool\ArrayAccessorTrait; + +class DiscordResourceOwner implements ResourceOwnerInterface +{ + use ArrayAccessorTrait; + + /** + * Raw response + * + * @var array + */ + protected $response; + + /** + * Creates new resource owner. + * + * @param array $response + */ + public function __construct(array $response = array()) + { + $this->response = $response; + } + + /** + * Get resource owner ID + * + * @return string|null + */ + public function getId() + { + return $this->getValueByKey($this->response, 'id'); + } + + /** + * Get resource owner username + * + * @return string|null + */ + public function getUsername() + { + return $this->getValueByKey($this->response, 'username'); + } + + /** + * Get resource owner discriminator + * + * @return string|null + */ + public function getDiscriminator() + { + return $this->getValueByKey($this->response, 'discriminator'); + } + + /** + * Get resource owner avatar hash + * + * @return string|null + */ + public function getAvatarHash() + { + return $this->getValueByKey($this->response, 'avatar'); + } + + /** + * Get resource owner verified flag + * + * @return bool + */ + public function getVerified() + { + return $this->getValueByKey($this->response, 'verified', false); + } + + /** + * Get resource owner email + * + * @return string|null + */ + public function getEmail() + { + return $this->getValueByKey($this->response, 'email'); + } + + /** + * Returns the raw resource owner response. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/Exception/DiscordIdentityProviderException.php b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/Exception/DiscordIdentityProviderException.php new file mode 100644 index 0000000..5f690e8 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/src/Provider/Exception/DiscordIdentityProviderException.php @@ -0,0 +1,49 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link https://packagist.org/packages/wohali/oauth2-discord-new Packagist + * @link https://github.com/wohali/oauth2-discord-new GitHub + */ + +namespace Wohali\OAuth2\Client\Provider\Exception; + +use League\OAuth2\Client\Provider\Exception\IdentityProviderException; +use Psr\Http\Message\ResponseInterface; + +class DiscordIdentityProviderException extends IdentityProviderException +{ + /** + * Creates client exception from response + * + * @param ResponseInterface $response + * @param array $data Parsed response data + * + * @return IdentityProviderException + */ + public static function clientException(ResponseInterface $response, $data) + { + return static::fromResponse( + $response, + isset($data['message']) ? $data['message'] : json_encode($data) + ); + } + + /** + * Creates identity exception from response + * + * @param ResponseInterface $response + * @param string $message + * + * @return IdentityProviderException + */ + protected static function fromResponse(ResponseInterface $response, $message = null) + { + return new static($message, $response->getStatusCode(), (string) $response->getBody()); + } +} diff --git a/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/test/src/Provider/DiscordTest.php b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/test/src/Provider/DiscordTest.php new file mode 100644 index 0000000..8052d75 --- /dev/null +++ b/plugins/login-oauth2-extras/vendor/wohali/oauth2-discord-new/test/src/Provider/DiscordTest.php @@ -0,0 +1,146 @@ +provider = new \Wohali\OAuth2\Client\Provider\Discord([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none' + ]); + } + + public function tearDown(): void + { + m::close(); + parent::tearDown(); + } + + public function testAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + parse_str($uri['query'], $query); + + $this->assertArrayHasKey('client_id', $query); + $this->assertArrayHasKey('redirect_uri', $query); + $this->assertArrayHasKey('state', $query); + $this->assertArrayHasKey('scope', $query); + $this->assertArrayHasKey('response_type', $query); + $this->assertArrayHasKey('approval_prompt', $query); + $this->assertNotNull($this->provider->getState()); + } + + public function testScopes() + { + $scopeSeparator = ' '; + $options = ['scope' => [uniqid(), uniqid()]]; + $query = ['scope' => implode($scopeSeparator, $options['scope'])]; + $url = $this->provider->getAuthorizationUrl($options); + $encodedScope = $this->buildQueryString($query); + $this->assertStringContainsString($encodedScope, $url); + } + + public function testGetAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + + $this->assertEquals('/api/v6/oauth2/authorize', $uri['path']); + } + + public function testGetBaseAccessTokenUrl() + { + $params = []; + + $url = $this->provider->getBaseAccessTokenUrl($params); + $uri = parse_url($url); + + $this->assertEquals('/api/v6/oauth2/token', $uri['path']); + } + + public function testGetAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token", "token_type":"Bearer", "scope": "identify"}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $response->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $this->assertEquals('mock_access_token', $token->getToken()); + $this->assertNull($token->getExpires()); + $this->assertNull($token->getRefreshToken()); + $this->assertNull($token->getResourceOwnerId()); + } + + public function testUserData() + { + $discriminator = rand(1000,9999); + $id = uniqid(); + $name = uniqid(); + $avatar = uniqid(); + $email = uniqid(); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token", "token_type":"Bearer", "scope": "identify"}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn('{"id": "'.$id.'", "username": "'.$name.'", "discriminator": "'.$discriminator.'", "avatar": "'.$avatar.'", "verified": true, "email": "'.$email.'"}'); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals($id, $user->getId()); + $this->assertEquals($id, $user->toArray()['id']); + $this->assertEquals($name, $user->getUsername()); + $this->assertEquals($name, $user->toArray()['username']); + $this->assertEquals($discriminator, $user->getDiscriminator()); + $this->assertEquals($discriminator, $user->toArray()['discriminator']); + $this->assertEquals($avatar, $user->getAvatarHash()); + $this->assertEquals($avatar, $user->toArray()['avatar']); + $this->assertEquals($email, $user->getEmail()); + $this->assertEquals($email, $user->toArray()['email']); + $this->assertEquals(true, $user->getVerified()); + $this->assertEquals(true, $user->toArray()['verified']); + } + + public function testExceptionThrownErrorObjectReceived() + { + $this->expectException(\League\OAuth2\Client\Provider\Exception\IdentityProviderException::class); + $status = rand(400,600); + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"client_id": ["This field is required"]}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'appliction/json']); + $postResponse->shouldReceive('getStatusCode')->andReturn($status); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } +} diff --git a/plugins/login-oauth2/.gitignore b/plugins/login-oauth2/.gitignore new file mode 100644 index 0000000..a09c56d --- /dev/null +++ b/plugins/login-oauth2/.gitignore @@ -0,0 +1 @@ +/.idea diff --git a/plugins/login-oauth2/CHANGELOG.md b/plugins/login-oauth2/CHANGELOG.md new file mode 100644 index 0000000..d1c89ff --- /dev/null +++ b/plugins/login-oauth2/CHANGELOG.md @@ -0,0 +1,116 @@ +# v2.2.4 +## 05/09/2023 + +1. [](#improved) + * Removed a deprecation message for PHP 8.2+ + +# v2.2.3 +## 03/06/2023 + +1. [](#bugfix) + * Fixed an issue with default `access` and `groups` configuration not being merged into user object correctly. + +# v2.2.2 +## 01/02/2023 + +1. [](#bugfix) + * Set `composer.json` to use `^7.3.6 || ^8.0` + downgraded libs for PHP compatibility + +# v2.2.1 +## 12/28/2022 + +1. [](#bugfix) + * Fix for `remember_me` functionality not working with OAuth2 providers (always defaults to `true`) + +# v2.2.0 +## 12/28/2022 + +1. [](#improved) + * Improved Exception to show any invalid providers [#42](https://github.com/trilbymedia/grav-plugin-login-oauth2/pull/42) + * CSS has been improved for better consistency of layout + * Login button text moved to Lang file for easier modification and translation + * Added some debug information for async/post calls to callback + * Updated Vendor libraries to latest +1. [](#bugfix) + * Don't fail with exception when provider name is invalid or empty + * Change `self::getCallbackUrl()` to `static::getCallbackUrl()` to support overriding the method + * Properly support after login redirect logic (was not working as intended) + +# v2.1.1 +## 05/24/2021 + +1. [](#bugfix) + * Fixed Facebook login never showing up [#40](https://github.com/trilbymedia/grav-plugin-login-oauth2/issues/40) + +# v2.1.0 +## 05/13/2021 + +1. [](#new) + * Require **Grav 1.7.0** + * Added configuration option to require existing Grav user + * Assign OAuth2 to existing user [#35](https://github.com/trilbymedia/grav-plugin-login-oauth2/issues/35) +1. [](#improved) + * Code improvements and updates + * Only enable configured oauth2 providers +1. [](#bugfix) + * Google: non-hosted google accounts cannot be used [#25](https://github.com/trilbymedia/grav-plugin-login-oauth2/issues/25) + * Fixed missing translations in the template file [#37](https://github.com/trilbymedia/grav-plugin-login-oauth2/pull/37) + * Fixed login buttons exceeding available width on mobile screens [#31](https://github.com/trilbymedia/grav-plugin-login-oauth2/pull/31) + * Fixed login redirects in admin plugin + +# v2.0.5 +## 12/02/2020 + +1. [](#improved) + * Removed user scope from github by default [#36](https://github.com/trilbymedia/grav-plugin-login-oauth2/pull/36) + +# v2.0.4 +## 06/03/2020 + +1. [](#improved) + * If no provider is enabled for site connections, simply omit the template [#28](https://github.com/trilbymedia/grav-plugin-login-oauth2/pull/28) + * Vendor updates + * Use `UserLogin::defaultRedirectAfterLogin()` helper method + +# v2.0.3 +## 02/24/2019 + +1. [](#improved) + * Added `copy-to-clipboard` support for Callback URIs + * Added support for providers that callback via POST (ie, Apple) + * Fixed issues with saving in Admin 1.7 with strict form validation + +# v2.0.2 +## 04/28/2019 + +1. [](#improved) + * Removed configurable callback URL. + +# v2.0.1 +## 04/28/2019 + +1. [](#bugfix) + * Fixed login version requirements (`~3.0`) [#17](https://github.com/trilbymedia/grav-plugin-login-oauth2/issues/17) + +# v2.0.0 +## 04/26/2019 + +1. [](#new) + * Support for OAuth2 login via Admin plugin + * Support for default groups +1. [](#improved) + * Updated vendor libraries to use latest Google / LinkedIn providers +1. [](#bugfix) + * Fix bad redirect on login error + +# v1.0.1 +## 06/07/2018 + +1. [](#new) + * Added new Hosted Domain option for Google Provider that allows to limit the login per domain [#1](https://github.com/trilbymedia/grav-plugin-login-oauth2/issues/1) + +# v1.0.0 +## 05/18/2018 + +1. [](#new) + * Plugin released diff --git a/plugins/login-oauth2/LICENSE b/plugins/login-oauth2/LICENSE new file mode 100644 index 0000000..d151da3 --- /dev/null +++ b/plugins/login-oauth2/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Trilby Media, LLC + +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/plugins/login-oauth2/README.md b/plugins/login-oauth2/README.md new file mode 100644 index 0000000..722bf2f --- /dev/null +++ b/plugins/login-oauth2/README.md @@ -0,0 +1,317 @@ +# Login OAuth2 Plugin + +The **Login OAuth2** Plugin for [Grav CMS](http://github.com/getgrav/grav) allows user authentication against an OAuth2 Authentication Provider. This plugin makes use of [The League OAuth2 Client](http://oauth2-client.thephpleague.com/) + +Currently the core plugin supports the following providers: + +* **Facebook** - https://developers.facebook.com/docs/facebook-login/web +* **GitHub** - https://developer.github.com/apps/building-oauth-apps/creating-an-oauth-app/ +* **Google** - https://developers.google.com/identity/protocols/OpenIDConnect +* **Instagram** - https://www.instagram.com/developer/authentication/ +* **LinkedIn** - https://developer.linkedin.com/docs/oauth2 + +It's also possible to extend this plugin an create a new AOauth2 for specific providers. + +## Callback URL + +When you setup your OAuth provider application, you will need to provide a Callback URL. Grav passes this as part of the OAuth2 request process, but it needs to match the configuration on the server side. Typically, when logging in via the the frontend **site**, the URL will look something like this: + +```text +http://yoursite.com/task:callback.oauth2 +``` + +Where `http://yoursite.com` is the URL of your Grav-based site. If you are using SSL, then this URL will be: + +```text +https://yoursite.com/task:callback.oauth2 +``` + +If you use the OAuth2 plugin to login to the **admin** side of your Grav site, your callback URL will look like this: + +```text +http://yoursite.com/admin/task:callback.oauth2 +``` + +Where `http://yoursite.com/admin` is the URL you use to log into the admin plugin. Again, if you have this under SSL, you would need to use `https://` rather than `http://`. Some OAuth2 providers allow you to use provide multiple callback URLs, and in this case you can use the same application setup with multiple URLs, to work with the **site** and the **admin** and potentially `http://` and `https://` URLs. However, some providers only allow a single callback URL, and in these cases you need to create multiple OAuth2 applications to handle each callback URL. + + +## Installation + +Installing the Login OAuth2 plugin can be done in one of two ways. The GPM (Grav Package Manager) installation method enables you to quickly and easily install the plugin with a simple terminal command, while the manual method enables you to do so via a zip file. + +### GPM Installation (Preferred) + +The simplest way to install this plugin is via the [Grav Package Manager (GPM)](http://learn.getgrav.org/advanced/grav-gpm) through your system's terminal (also called the command line). From the root of your Grav install type: + + bin/gpm install login-oauth2 + +This will install the Login OAuth2 plugin into your `/user/plugins` directory within Grav. Its files can be found under `/your/site/grav/user/plugins/login-oauth2`. + +### Manual Installation + +To install this plugin, just download the zip version of this repository and unzip it under `/your/site/grav/user/plugins`. Then, rename the folder to `login-oauth2`. You can find these files on [GitHub](https://github.com/trilbymedia/grav-plugin-login-oauth2) or via [GetGrav.org](http://getgrav.org/downloads/plugins#extras). + +You should now have all the plugin files under + + /your/site/grav/user/plugins/login-oauth2 + +Before configuring this plugin, you should copy the `user/plugins/login-oauth2/login-oauth2.yaml` to `user/config/plugins/login-oauth2.yaml` and only edit that copy. + +### Admin Installation + +If you use the admin plugin, you can install directly through the admin plugin by browsing the to `Plugins` in the sidebar menu and clicking on the `Add` button. + +Configuring the Login OAuth2 plugin is as easy as navigating to the `Plugins` manager, and editing the configuration options. + +## Configuration Options + +The default configuration and an explanation of available options: + +```yaml +enabled: true + +built_in_css: true +button_style: row +require_grav_user: false +save_grav_user: false +store_provider_data: true +default_access_levels: + access: + site: + login: true +default_groups: + +providers: + github: + enabled: true + client_id: '' + client_secret: '' + options: + scope: ['user', 'user:email'] + + instagram: + enabled: true + client_id: '' + client_secret: '' + options: + scope: ['basic', 'likes', 'comments'] + host: 'https://api.instagram.com' + + facebook: + enabled: true + app_id: '' + app_secret: '' + options: + scope: ['email', 'public_profile', 'user_hometown'] + graph_api_version: 'v2.10' + + google: + enabled: true + client_id: '' + client_secret: '' + hd: '*' + options: + scope: ['email', 'profile'] + avatar_size: 200 + + linkedin: + enabled: true + client_id: '' + client_secret: '' + options: + scope: ['r_basicprofile','r_emailaddress'] + + + +admin: + enabled: false + built_in_css: true + button_style: row + + providers: + github: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['user', 'user:email'] + + instagram: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['basic', 'likes', 'comments'] + host: 'https://api.instagram.com' + + facebook: + enabled: false + app_id: '' + app_secret: '' + options: + scope: ['email', 'public_profile', 'user_hometown'] + graph_api_version: 'v2.10' + + google: + enabled: false + client_id: '' + client_secret: '' + hd: '*' + options: + scope: ['email', 'profile'] + avatar_size: 200 + + linkedin: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['r_basicprofile','r_emailaddress'] +``` + +### Server Settings + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enables the plugin | [default: `true`] \| `false`| +|built_in_css|Enables the plugin-provided CSS to be loaded| [default: `true`] \| `false`| +|button_style|If you want to provide your own custom CSS, feel free to disable the CSS provided by the plugin| [default: `row`] \| `square`| +|require_grav_user|Allow oauth login only for existing users | `true` \| [default: `false`] | +|save_grav_user|Store the grav user account as a local YAML account | `true` \| [default: `false`] | +|store_provider_data|If storing a local Grav user, you can also store OAuth2 Provider data so its available in Grav| `true` \| [default: `false`] | +|default_access_levels.access|You can find more information on access levels in the https://learn.getgrav.org/advanced/groups-and-permissions#permissions|[default: `site: { login: true }`]| +|default_groups| You can find more information on access levels in the https://learn.getgrav.org/advanced/groups-and-permissions#permissions|[default: `[]`]| + + +### OAuth2 Providers + +#### GitHub + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| [default: `true`] \| `false` | +|client_id|The **Client ID** Provided by GitHub when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by GitHub when you register an application for OAuth2 authentication | `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['user', 'user:email', 'repo']` | + +#### Instagram + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| [default: `true`] \| `false` | +|client_id|The **Client ID** Provided by Instagram when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by Instagram when you register an application for OAuth2 authentication | `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['basic', 'likes', 'comments']` | +|host|The host address of the Instagram OAuth2 API service _[don't change this unless you know what you are doing]_| e.g. `https://api.instagram.com` | + +#### Facebook + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| [default: `true`] \| `false` | +|app_id|The **App ID** Provided by Facebook when you register an application for OAuth2 authentication | `` | +|app_secret|The **App Secret** Provided by Facebook when you register an application for OAuth2 authentication | `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['email', 'public_profile', 'user_hometown']` | +|graph_api_version|The Graph AP version to use _[don't change this unless you know what you are doing]_. | e.g. `v2.10` | + +#### Google + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| [default: `true`] \| `false` | +|client_id|The **Client ID** Provided by Google when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by Google when you register an application for OAuth2 authentication | `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['email', 'profile']` | +|avatar_size|The size in pixels of the avatar URL to store | e.g. `200` | + +#### Instagram + +|Key |Description | Values | +|:---------------------|:---------------------------|:-------| +|enabled|Enable or disable this specific provider. This stops its showing as an valid login option| [default: `true`] \| `false` | +|client_id|The **Client ID** Provided by Instagram when you register an application for OAuth2 authentication | `` | +|client_secret|The **Client Secret** Provided by Instagram when you register an application for OAuth2 authentication | `` | +|scope|An array of strings that define the OAuth2 scope. These can enable retrieving more data, but often require more permissions | e.g. `['r_basicprofile','r_emailaddress']` | + + +> Note that if you use the admin plugin, a file with your configuration will be saved in the `user/config/plugins/login-oauth2.yaml`. + +### Usage + +Once properly configured, the functionality of the OAuth2 plugin is simple for the user. The login form will display `enabled` OAuth2 Providers, and the user can click on one which will then redirect them to the provider to authenticate and `accept` the permissions requested via the `scope` fields. Upon completion of this process, the user will then be redirected back to the site where they will now be logged in. + +#### OAuth2 User Data + +Any user data available via the `scope` provider options will be retrieved. Core fields like `username`, and `email` will be stored on the Grav user object, and anything else that is provider-specific can be optionally stored as well. By default, the Grav user object **is not** persisted to a physical Grav account YAML file, instead it's just kept in session temporarily. + +#### Storing Grav User + +By default the OAuth2 plugin does not store any local user information. Upon successfully authenticating against the OAuth2 user, a user is created and is available during the session. However, upon returning, the user must re-authenticate and the OAuth2 data is retrieved again. + +If you want to be able to set user data (extra fields, or specific user access) for a particular user, you can enable the `save_grav_user` option, and this will create a local Grav user in the `accounts/` folder. This is a local record of the user and attributes can be set here. + +> NOTE: Any attribute stored under the provider key (e.g. `github:`) in the user account file will be overwritten by the plugin during the next login. This information is always in sync with latest data from the provider. +> +> Also note that the password will never be stored in the Grav user under `accounts/`. + +#### OAuth2 to Grav Access Mapping + +The OAuth2 plugin provides a flexible way to map your OAuth2 users into Grav. + +> For Groups and Access mapping to work properly a valid `search_dn`, `query_dn` and `group_query` is required. + +The default configuration for `default_access_levels.access` looks like: + +```yaml +user: + site: + login: true +``` + +In order for a front-end user to be able to log into a Grav site the minimum of `site: [login: true]` is required. You can of course configure this with any access settings you wish to provide. + +It is not advised to provide any `admin` access via OAuth2 accounts, but if you wish a particular OAuth user to be able to log into the admin, you should enable the `save_grav_user` option, so the userdata is persisted as a Grav Account YAML file, and then manually add the desired permissions. These **will not** be reset to the default values on each login. + +> NOTE: See the [Groups and Permissions Documentation](https://learn.getgrav.org/advanced/groups-and-permissions?target=_blank) for more information about how Grav permissions work in conjunction with access levels and groups. + +### Admin Notes + +New in version `2.0` is the support for OAuth2 providers to be able to login via the admin. After careful consideration, we decided to provide configuration options for both `Site` and `Admin` as there are some providers that need to have a unique **OAuth2 Application** setup for each unique callback. This is important because by default, Grav uses a different session for both `Site` and `Admin`. Therefore you need a unique callback, one that goes to the frontend site, and one to the admin. This means we have to provide a way to have unique application settings for both `Site` and `Admin`. + +There are some providers such as **Discord** and **GitLab** that actually allow for multiple callback URLs to be registered. In this case, simply copy over the same `client_id` and `client_secret` for both `Site` and `Admin`. + +Also, if you have the `system.session.split` option set to `false`, you are effectively sharing the session between `Site` and `Admin`, and again, you can share the `Site` configuration, but they need to be entered into both sets of options. + +For admin logins to be useful, you need to ensure you set `store_grav_user: true` (which is not default behavior). This will ensure that when you login, a local accounts `.yaml` file will be create in `user/accounts/` folder. A this point you can manually add the admin access required to log into the admin by directly editing the `.yaml` file that was auto-created during the login process: + +```yaml + access: + admin: + login: true + super: true + site: + login: true +``` + +Of course adjust this `access.admin:` settings to whatever you need, but **NEVER** set this in the `default_access_levels:` setting for the plugin, or every user will have admin access. You want to maintain control over who can access and who can't, especially those logging in with OAuth2 providers as there is no control over 'who' can sign in. + +### Troubleshooting + +To get a quick state of your OAuth2 configuration, you can simply dump out the Grav user on a temporary _secure_ page: + +```markdown +--- +title: OAuth2 Test +cache_enabled: false +process: + twig: true +access: + site.login: true +--- + +# Grav User + +{{ vardump(grav.user) }} +``` + + diff --git a/plugins/login-oauth2/blueprints.yaml b/plugins/login-oauth2/blueprints.yaml new file mode 100644 index 0000000..ca84dbe --- /dev/null +++ b/plugins/login-oauth2/blueprints.yaml @@ -0,0 +1,707 @@ +name: Login OAuth2 +type: login-oauth2 +slug: form +version: 2.2.4 +description: OAuth2 Client Plugin to integrate with Grav's Login +icon: plug +author: + name: Trilby Media, LLC + email: hello@trilby.media +homepage: https://trilby.media +keywords: grav, plugin, oauth2, login, social +bugs: https://github.com/trilbymedia/grav-plugin-login-oauth2/issues +docs: https://github.com/trilbymedia/grav-plugin-login-oauth2/blob/develop/README.md +license: MIT +dependencies: + - { name: grav, version: '>=1.7.0' } + - { name: login, version: '>=3.4' } + +form: + validation: strict + fields: + enabled: + type: toggle + label: Plugin Status + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + debug: + type: toggle + label: Extra Debugging + highlight: 0 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + site_callback_url: + type: text + disabled: true + copy_to_clipboard: true + label: PLUGIN_LOGIN_OAUTH2.SITE_CALLBACK_URI + help: PLUGIN_LOGIN_OAUTH2.SITE_CALLBACK_URI_HELP + data-default@: ['Grav\Plugin\Login\OAuth2\Providers\BaseProvider::getCallbackUri', false] + + admin_callback_url: + type: text + disabled: true + copy_to_clipboard: true + label: PLUGIN_LOGIN_OAUTH2.ADMIN_CALLBACK_URI + help: PLUGIN_LOGIN_OAUTH2.ADMIN_CALLBACK_URI_HELP + data-default@: ['Grav\Plugin\Login\OAuth2\Providers\BaseProvider::getCallbackUri', true] + + oauth2_tabs: + type: tabs + + fields: + + tab_1: + type: tab + title: PLUGIN_LOGIN_OAUTH2.CONFIGURATION + fields: + + built_in_css: + type: toggle + label: PLUGIN_LOGIN_OAUTH2.BUILTIN_CSS + highlight: 1 + default: 1 + help: PLUGIN_LOGIN_OAUTH2.BUILTIN_CSS_HELP + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + + button_style: + type: select + label: PLUGIN_LOGIN_OAUTH2.BUTTON_STYLE + default: row + size: medium + help: PLUGIN_LOGIN_OAUTH2.BUTTON_STYLE_HELP + options: + row: Horizontal Row + square: Square Block + + require_grav_user: + type: toggle + label: PLUGIN_LOGIN_OAUTH2.REQUIRE_GRAV_USER + help: PLUGIN_LOGIN_OAUTH2.REQUIRE_GRAV_USER_DESC + highlight: 0 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + save_grav_user: + type: toggle + label: PLUGIN_LOGIN_OAUTH2.SAVE_GRAV_USER + help: PLUGIN_LOGIN_OAUTH2.SAVE_GRAV_USER_DESC + highlight: 0 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + store_provider_data: + type: toggle + label: PLUGIN_LOGIN_OAUTH2.STORE_OAUTH2_USER + help: PLUGIN_LOGIN_OAUTH2.STORE_OAUTH2_USER_DESC + highlight: 1 + default: 1 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + default_access_levels.access: + type: textarea + label: PLUGIN_LOGIN_OAUTH2.DEFAULT_ACCESS_LEVELS + yaml: true + size: large + validate: + required: true + + default_groups: + type: selectize + size: large + placeholder: "e.g. administrators, publishers" + label: PLUGIN_LOGIN_OAUTH2.DEFAULT_GROUPS + help: PLUGIN_LOGIN_OAUTH2.DEFAULT_GROUPS_HELP + markdown: true + description: PLUGIN_LOGIN_OAUTH2.DEFAULT_ACCESS_LEVELS_DESC + classes: fancy + validate: + type: commalist + + tab_admin: + type: tab + title: PLUGIN_LOGIN_OAUTH2.ADMIN + + fields: + + admin.enabled: + type: toggle + label: PLUGIN_LOGIN_OAUTH2.ADMIN_ENABLED + highlight: 0 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.built_in_css: + type: toggle + label: PLUGIN_LOGIN_OAUTH2.BUILTIN_CSS + highlight: 1 + default: 1 + help: PLUGIN_LOGIN_OAUTH2.BUILTIN_CSS_HELP + options: + 1: PLUGIN_ADMIN.ENABLED + 0: PLUGIN_ADMIN.DISABLED + validate: + type: bool + + admin.button_style: + type: select + label: PLUGIN_LOGIN_OAUTH2.BUTTON_STYLE + default: row + size: medium + help: PLUGIN_LOGIN_OAUTH2.BUTTON_STYLE_HELP + options: + row: Horizontal Row + square: Square Block + + tab_2: + type: tab + title: PLUGIN_LOGIN_OAUTH2.PROVIDERS + + fields: + + github: + type: fieldset + title: GitHub + collapsible: true + + fields: + + github_columns: + type: columns + + fields: + + github_column_left: + type: column + + fields: + + github.site: + type: display + style: vertical + content: '

Site

' + + providers.github.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.github.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.github.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.github.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + github_column_right: + type: column + + fields: + + github.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.github.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.github.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.github.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.github.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.github.description: + type: display + style: vertical + content: '[ GitHub OAuth2 from the official documentation](https://developer.github.com/apps/building-oauth-apps/creating-an-oauth-app/?target=_blank)' + markdown: true + + + instagram: + type: fieldset + title: Instagram + collapsible: true + + fields: + + instagram_columns: + type: columns + + fields: + + instagram_column_left: + type: column + + fields: + + instagram.site: + type: display + style: vertical + content: '

Site

' + + providers.instagram.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.instagram.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.instagram.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.instagram.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.instagram.options.host: + type: text + label: PLUGIN_LOGIN_OAUTH2.HOST + + + instagram_column_right: + type: column + + fields: + + instagram.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.instagram.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.instagram.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.instagram.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.instagram.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + admin.providers.instagram.options.host: + type: text + label: PLUGIN_LOGIN_OAUTH2.HOST + + providers.instagram.description: + type: display + style: vertical + content: '[ Instagram OAuth2 from the official documentation](https://www.instagram.com/developer/authentication/?target=_blank)' + markdown: true + + facebook: + type: fieldset + title: Facebook + collapsible: true + + fields: + + facebook_columns: + type: columns + + fields: + + facebook_column_left: + type: column + + fields: + + facebook.site: + type: display + style: vertical + content: '

Site

' + + providers.facebook.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.facebook.app_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.APP_ID + + providers.facebook.app_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.APP_SECRET + + providers.facebook.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.facebook.options.graph_api_version: + type: text + size: x-small + label: PLUGIN_LOGIN_OAUTH2.GRAPH_API_VERSION + + facebook_column_right: + type: column + + fields: + + facebook.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.facebook.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.facebook.app_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.APP_ID + + admin.providers.facebook.app_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.APP_SECRET + + admin.providers.facebook.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + admin.providers.facebook.options.graph_api_version: + type: text + size: x-small + label: PLUGIN_LOGIN_OAUTH2.GRAPH_API_VERSION + + providers.facebook.description: + type: display + style: vertical + content: '[ Facebook OAuth2 from the official documentation](https://developers.facebook.com/docs/facebook-login/web?target=_blank)' + markdown: true + + google: + type: fieldset + title: Google + collapsible: true + + fields: + + google_columns: + type: columns + + fields: + + google_column_left: + type: column + + fields: + + google.site: + type: display + style: vertical + content: '

Site

' + + providers.google.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.google.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.google.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.google.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + providers.google.options.hd: + type: text + label: PLUGIN_LOGIN_OAUTH2.RESTRICT_DOMAIN + placeholder: domain.com + + providers.google.options.avatar_size: + type: number + size: x-small + append: px + label: PLUGIN_LOGIN_OAUTH2.AVATAR_SIZE + + + google_column_right: + type: column + + fields: + + google.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.google.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.google.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.google.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.google.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + admin.providers.google.options.hd: + type: text + label: PLUGIN_LOGIN_OAUTH2.RESTRICT_DOMAIN + placeholder: domain.com + + admin.providers.google.options.avatar_size: + type: number + size: x-small + append: px + label: PLUGIN_LOGIN_OAUTH2.AVATAR_SIZE + + providers.google.description: + type: display + style: vertical + content: '[ Google OAuth2 from the official documentation](https://developers.google.com/identity/protocols/OpenIDConnect?target=_blank)' + markdown: true + + linkedin: + type: fieldset + title: LinkedIn + collapsible: true + + fields: + + linkedin_columns: + type: columns + + fields: + + linkedin_column_left: + type: column + + fields: + + linkedin.site: + type: display + style: vertical + content: '

Site

' + + providers.linkedin.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + providers.linkedin.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + providers.linkedin.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + providers.linkedin.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + linkedin_column_right: + type: column + + fields: + + linkedin.admin: + type: display + style: vertical + content: '

Admin

' + + admin.providers.linkedin.enabled: + type: toggle + label: Enabled + highlight: 1 + default: 0 + options: + 1: Enabled + 0: Disabled + validate: + type: bool + + admin.providers.linkedin.client_id: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_ID + + admin.providers.linkedin.client_secret: + type: text + label: PLUGIN_LOGIN_OAUTH2.CLIENT_SECRET + + admin.providers.linkedin.options.scope: + type: selectize + size: large + label: PLUGIN_LOGIN_OAUTH2.SCOPE + classes: fancy + validate: + type: commalist + + + providers.linkedin.description: + type: display + style: vertical + content: '[ LinkedIn OAuth2 from the official documentation](https://developer.linkedin.com/docs/oauth2?target=_blank)' + markdown: true + + tab_3: + type: tab + title: PLUGIN_LOGIN_OAUTH2.DOCUMENTATION + + fields: + + oauth2_instructions: + type: display + markdown: true + style: vertical + file: 'plugins://login-oauth2/README.md' diff --git a/plugins/login-oauth2/classes/OAuth2.php b/plugins/login-oauth2/classes/OAuth2.php new file mode 100644 index 0000000..c42b834 --- /dev/null +++ b/plugins/login-oauth2/classes/OAuth2.php @@ -0,0 +1,85 @@ +config = (array)(Grav::instance()['config']->get('plugins.login-oauth2') ?? []); + $this->admin = (bool)$admin; + } + + public function getConfig(): array + { + return $this->config; + } + + public function isAdmin(): bool + { + return $this->admin; + } + + public function addEnabledProviders(): void + { + if ($this->admin) { + $providers = (array)($this->config['admin']['providers'] ?? []); + } else { + $providers = (array)($this->config['providers'] ?? []); + } + + foreach ($providers as $provider => $options) { + if (ProviderFactory::checkIfActive($provider, $options)) { + $this->addProvider($provider, $options); + } + } + } + + /** + * @param string $provider + * @param array|null $options + */ + public function addProvider(string $provider, array $options = null): void + { + $this->providers[$provider] = $options; + } + + public function getProviders(): array + { + return $this->providers; + } + + /** + * @param string $provider + * @return mixed|null + */ + public function getProviderOptions(string $provider) + { + return $this->providers[$provider] ?? null; + } + + /** + * @param string $provider + * @return bool + */ + public function isValidProvider(?string $provider): bool + { + if (is_null($provider)) { + return false; + } + return array_key_exists($provider, $this->providers); + } +} \ No newline at end of file diff --git a/plugins/login-oauth2/classes/ProviderFactory.php b/plugins/login-oauth2/classes/ProviderFactory.php new file mode 100644 index 0000000..df826ef --- /dev/null +++ b/plugins/login-oauth2/classes/ProviderFactory.php @@ -0,0 +1,38 @@ +initProvider($options); + + return $class; + } + + public static function checkIfActive($provider, array $options = []): bool + { + $provider_classname = 'Grav\\Plugin\\Login\\OAuth2\\Providers\\' . ucfirst($provider) . 'Provider'; + + if (!class_exists($provider_classname)) { + throw new \RuntimeException('Invalid OAuth2 provider:' . $provider); + } + + return $provider_classname::checkIfActive($options); + } +} diff --git a/plugins/login-oauth2/classes/Providers/BaseProvider.php b/plugins/login-oauth2/classes/Providers/BaseProvider.php new file mode 100644 index 0000000..304380f --- /dev/null +++ b/plugins/login-oauth2/classes/Providers/BaseProvider.php @@ -0,0 +1,139 @@ +isAdmin(); + $this->config = new Data(Grav::instance()['config']->get('plugins.login-oauth2' . ($admin ? '.admin' : ''))); + $this->state = 'LOGIN_OAUTH2_' . Utils::generateRandomString(15); + } + + /** + * Initialize Provider + * + * @param array $options + */ + public function initProvider(array $options): void + { + $options['redirectUri'] = static::getCallbackUri(); + $this->provider = new $this->classname($options); + } + + /** + * @return string + */ + public function getName(): string + { + return $this->name; + } + + /** + * @return string + */ + public function getState(): string + { + return $this->state; + } + + /** + * @param string $state + * @return $this + */ + public function setState(string $state) + { + $this->state = $state; + + return $this; + } + + /** + * @return AbstractProvider + */ + public function getProvider(): AbstractProvider + { + return $this->provider; + } + + /** + * @param string $admin + * @return string + */ + public static function getCallbackUri(string $admin = 'auto'): string + { + if ($admin === 'auto') { + $admin = Grav::instance()['oauth2']->isAdmin(); + } + + $callback_uri = ($admin ? Grav::instance()['config']->get('plugins.admin.route', '') : '') . static::CALLBACK_URI; + + $base_url = rtrim(Grav::instance()['uri']->rootUrl(true), '/'); + + return $base_url . '/' . ltrim($callback_uri, '/'); + } + + /** + * Requests an access token using a specified grant and option set. + * + * @param mixed $grant + * @param array $options + * @return AccessTokenInterface + * @throws IdentityProviderException + */ + public function getAccessToken($grant, array $options = []): AccessTokenInterface + { + $this->token = $this->provider->getAccessToken($grant, $options); + + return $this->token; + } + + /** + * Requests and returns the resource owner of given access token. + * + * @param AccessToken $token + * @return ResourceOwnerInterface + */ + public function getResourceOwner(AccessToken $token): ResourceOwnerInterface + { + return $this->provider->getResourceOwner($token); + } +} diff --git a/plugins/login-oauth2/classes/Providers/FacebookProvider.php b/plugins/login-oauth2/classes/Providers/FacebookProvider.php new file mode 100644 index 0000000..f9b17c0 --- /dev/null +++ b/plugins/login-oauth2/classes/Providers/FacebookProvider.php @@ -0,0 +1,73 @@ + $this->config->get('providers.facebook.app_id'), + 'clientSecret' => $this->config->get('providers.facebook.app_secret'), + 'graphApiVersion' => $this->config->get('providers.facebook.options.graph_api_version') + ]; + + parent::initProvider($options); + } + + /** + * @return string + */ + public function getAuthorizationUrl(): string + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.facebook.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + /** + * @param ResourceOwnerInterface|FacebookUser $user + * @return array + */ + public function getUserData(ResourceOwnerInterface $user): array + { + \assert($user instanceof FacebookUser); + + $hometown = $user->getHometown(); + + return [ + 'id' => $user->getId(), + 'login' => $user->getEmail(), + 'fullname' => $user->getName(), + 'email' => $user->getEmail(), + 'facebook' => [ + 'avatar_url' => $user->getPictureUrl(), + 'location' => $hometown ? $hometown['name'] : '' + ] + ]; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2/classes/Providers/GithubProvider.php b/plugins/login-oauth2/classes/Providers/GithubProvider.php new file mode 100644 index 0000000..894f180 --- /dev/null +++ b/plugins/login-oauth2/classes/Providers/GithubProvider.php @@ -0,0 +1,106 @@ + $this->config->get('providers.github.client_id'), + 'clientSecret' => $this->config->get('providers.github.client_secret'), + ]; + + parent::initProvider($options); + } + + /** + * @return string + */ + public function getAuthorizationUrl(): string + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.github.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + /** + * @param ResourceOwnerInterface|GithubResourceOwner $user + * @return array + */ + public function getUserData(ResourceOwnerInterface $user): array + { + \assert($user instanceof GithubResourceOwner); + + $data = $user->toArray(); + + return [ + 'id' => $user->getId(), + 'login' => $data['login'], + 'fullname' => $user->getName(), + 'email' => $this->getEmail($user), + 'github' => [ + 'location' => $data['location'], + 'company' => $data['company'], + 'avatar_url' => $data['avatar_url'], + ] + ]; + } + + /** + * Handle regular email + * + * @param ResourceOwnerInterface|GithubResourceOwner $user + * @return string|null + */ + public function getEmail(ResourceOwnerInterface $user) + { + \assert($user instanceof GithubResourceOwner); + + $email = $user->getEmail(); + + if (null === $email) { + $url = $this->provider->getResourceOwnerDetailsUrl($this->token); + $request = $this->provider->getAuthenticatedRequest( + 'GET', + $url . '/emails', + $this->token + ); + + $response = $this->provider->getResponse($request); + $emails = json_decode($response->getBody()->getContents()); + + $filtered = array_filter($emails, function($email) { + return $email->primary && $email->verified; + }); + + $email = $filtered ? array_shift($filtered)->email : null; + } + + return $email; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2/classes/Providers/GoogleProvider.php b/plugins/login-oauth2/classes/Providers/GoogleProvider.php new file mode 100644 index 0000000..57b5925 --- /dev/null +++ b/plugins/login-oauth2/classes/Providers/GoogleProvider.php @@ -0,0 +1,90 @@ + $this->config->get('providers.google.client_id'), + 'clientSecret' => $this->config->get('providers.google.client_secret'), + ]; + $hd = $this->config->get('providers.google.options.hd'); + if ($hd) { + $options['hostedDomain'] = $this->config->get('providers.google.options.hd'); + } + + parent::initProvider($options); + } + + /** + * @return string + */ + public function getAuthorizationUrl(): string + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.google.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + /** + * @param ResourceOwnerInterface|GoogleUser $user + * @return array + */ + public function getUserData(ResourceOwnerInterface $user): array + { + \assert($user instanceof GoogleUser); + + return [ + 'id' => $user->getId(), + 'login' => $user->getEmail(), + 'fullname' => $user->getName(), + 'email' => $user->getEmail(), + 'google' => [ + 'avatar_url' => $this->getAvatar($user), + ] + ]; + } + + /** + * @param ResourceOwnerInterface|GoogleUser $user + * @return string + */ + public function getAvatar(ResourceOwnerInterface $user): string + { + \assert($user instanceof GoogleUser); + + $avatar = $user->getAvatar() ?? ''; + if ($avatar) { + $avatarSize = (int)$this->config->get('plugins.login-oauth2.providers.google.options.avatar_size', 200); + $avatar = preg_replace("/\?sz=\d{1,}$/", '?sz=' . $avatarSize, $avatar); + } + + return $avatar; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2/classes/Providers/InstagramProvider.php b/plugins/login-oauth2/classes/Providers/InstagramProvider.php new file mode 100644 index 0000000..1350131 --- /dev/null +++ b/plugins/login-oauth2/classes/Providers/InstagramProvider.php @@ -0,0 +1,69 @@ + $this->config->get('providers.instagram.client_id'), + 'clientSecret' => $this->config->get('providers.instagram.client_secret'), + 'host' => $this->config->get('providers.instagram.options.host') + ]; + + parent::initProvider($options); + } + + /** + * @return string + */ + public function getAuthorizationUrl(): string + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.instagram.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + /** + * @param ResourceOwnerInterface|InstagramResourceOwner $user + * @return array + */ + public function getUserData(ResourceOwnerInterface $user): array + { + \assert($user instanceof InstagramResourceOwner); + + return [ + 'id' => $user->getId(), + 'login' => $user->getNickname(), + 'fullname' => $user->getName(), + 'instagram' => [ + 'avatar_url' => $user->getImageurl(), + ] + ]; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2/classes/Providers/LinkedinProvider.php b/plugins/login-oauth2/classes/Providers/LinkedinProvider.php new file mode 100644 index 0000000..76009ac --- /dev/null +++ b/plugins/login-oauth2/classes/Providers/LinkedinProvider.php @@ -0,0 +1,71 @@ + $this->config->get('providers.linkedin.client_id'), + 'clientSecret' => $this->config->get('providers.linkedin.client_secret'), + ]; + + parent::initProvider($options); + } + + /** + * @return string + */ + public function getAuthorizationUrl(): string + { + $options = ['state' => $this->state]; + $options['scope'] = $this->config->get('providers.linkedin.options.scope'); + + return $this->provider->getAuthorizationUrl($options); + } + + /** + * @param ResourceOwnerInterface|LinkedInResourceOwner $user + * @return array + */ + public function getUserData(ResourceOwnerInterface $user): array + { + \assert($user instanceof LinkedInResourceOwner); + + return [ + 'id' => $user->getId(), + 'login' => $user->getEmail(), + 'fullname' => $user->getFirstName() . ' ' . $user->getLastName(), + 'email' => $user->getEmail(), + 'linkedin' => [ + 'avatar_url' => $user->getImageurl(), + 'headline' => $user->getDescription(), + 'location' => $user->getLocation(), + ] + ]; + } +} \ No newline at end of file diff --git a/plugins/login-oauth2/classes/Providers/ProviderInterface.php b/plugins/login-oauth2/classes/Providers/ProviderInterface.php new file mode 100644 index 0000000..a1e5c4d --- /dev/null +++ b/plugins/login-oauth2/classes/Providers/ProviderInterface.php @@ -0,0 +1,73 @@ +=5.5" + }, + "require-dev": { + "symfony/phpunit-bridge": "^4.4 || ^5.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.5-dev" + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/1.5.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "time": "2022-08-28T14:55:35+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "2.4.3", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "67c26b443f348a51926030c83481b85718457d3d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/67c26b443f348a51926030c83481b85718457d3d", + "reference": "67c26b443f348a51926030c83481b85718457d3d", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.1", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.29 || ^9.5.23" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/2.4.3" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "time": "2022-10-26T14:07:24+00:00" + }, + { + "name": "jakeasmith/http_build_url", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/jakeasmith/http_build_url.git", + "reference": "93c273e77cb1edead0cf8bcf8cd2003428e74e37" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/jakeasmith/http_build_url/zipball/93c273e77cb1edead0cf8bcf8cd2003428e74e37", + "reference": "93c273e77cb1edead0cf8bcf8cd2003428e74e37", + "shasum": "" + }, + "type": "library", + "autoload": { + "files": [ + "src/http_build_url.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jake A. Smith", + "email": "theman@jakeasmith.com" + } + ], + "description": "Provides functionality for http_build_url() to environments without pecl_http.", + "support": { + "issues": "https://github.com/jakeasmith/http_build_url/issues", + "source": "https://github.com/jakeasmith/http_build_url" + }, + "time": "2017-05-01T15:36:40+00:00" + }, + { + "name": "league/oauth2-client", + "version": "2.6.1", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-client.git", + "reference": "2334c249907190c132364f5dae0287ab8666aa19" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-client/zipball/2334c249907190c132364f5dae0287ab8666aa19", + "reference": "2334c249907190c132364f5dae0287ab8666aa19", + "shasum": "" + }, + "require": { + "guzzlehttp/guzzle": "^6.0 || ^7.0", + "paragonie/random_compat": "^1 || ^2 || ^9.99", + "php": "^5.6 || ^7.0 || ^8.0" + }, + "require-dev": { + "mockery/mockery": "^1.3.5", + "php-parallel-lint/php-parallel-lint": "^1.3.1", + "phpunit/phpunit": "^5.7 || ^6.0 || ^9.5", + "squizlabs/php_codesniffer": "^2.3 || ^3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-2.x": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alex Bilbie", + "email": "hello@alexbilbie.com", + "homepage": "http://www.alexbilbie.com", + "role": "Developer" + }, + { + "name": "Woody Gilk", + "homepage": "https://github.com/shadowhand", + "role": "Contributor" + } + ], + "description": "OAuth 2.0 Client Library", + "keywords": [ + "Authentication", + "SSO", + "authorization", + "identity", + "idp", + "oauth", + "oauth2", + "single sign on" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-client/issues", + "source": "https://github.com/thephpleague/oauth2-client/tree/2.6.1" + }, + "time": "2021-12-22T16:42:49+00:00" + }, + { + "name": "league/oauth2-facebook", + "version": "2.2.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-facebook.git", + "reference": "ec6d62a00b548c6cd56d7b734346b9e6befbfbbb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-facebook/zipball/ec6d62a00b548c6cd56d7b734346b9e6befbfbbb", + "reference": "ec6d62a00b548c6cd56d7b734346b9e6befbfbbb", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0", + "php": ">=7.3" + }, + "require-dev": { + "ext-json": "*", + "mockery/mockery": "~1.3.0", + "phpunit/phpunit": "^9.4", + "squizlabs/php_codesniffer": "~3.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Sammy Kaye Powers", + "email": "me@sammyk.me", + "homepage": "http://www.sammyk.me" + } + ], + "description": "Facebook OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "Authentication", + "authorization", + "client", + "facebook", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-facebook/issues", + "source": "https://github.com/thephpleague/oauth2-facebook/tree/2.2.0" + }, + "time": "2022-02-24T18:45:07+00:00" + }, + { + "name": "league/oauth2-github", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-github.git", + "reference": "e63d64f3ec167c09232d189c6b0c397458a99357" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-github/zipball/e63d64f3ec167c09232d189c6b0c397458a99357", + "reference": "e63d64f3ec167c09232d189c6b0c397458a99357", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "mockery/mockery": "~0.9", + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "description": "Github OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "github", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-github/issues", + "source": "https://github.com/thephpleague/oauth2-github/tree/master" + }, + "time": "2017-01-26T01:14:51+00:00" + }, + { + "name": "league/oauth2-google", + "version": "4.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-google.git", + "reference": "db6d8ad67cdd7d014a1e5dd5c204a319a966de86" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-google/zipball/db6d8ad67cdd7d014a1e5dd5c204a319a966de86", + "reference": "db6d8ad67cdd7d014a1e5dd5c204a319a966de86", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0", + "php": ">=7.3" + }, + "require-dev": { + "eloquent/phony-phpunit": "^6.0 || ^7.1", + "phpunit/phpunit": "^8.0 || ^9.0", + "squizlabs/php_codesniffer": "^3.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Woody Gilk", + "email": "woody.gilk@gmail.com", + "homepage": "http://shadowhand.me" + } + ], + "description": "Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "Authentication", + "authorization", + "client", + "google", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-google/issues", + "source": "https://github.com/thephpleague/oauth2-google/tree/4.0.0" + }, + "time": "2021-03-04T21:12:06+00:00" + }, + { + "name": "league/oauth2-instagram", + "version": "3.1.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-instagram.git", + "reference": "8de83b72498862979c3f296a17b9fc7fdf728622" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-instagram/zipball/8de83b72498862979c3f296a17b9fc7fdf728622", + "reference": "8de83b72498862979c3f296a17b9fc7fdf728622", + "shasum": "" + }, + "require": { + "jakeasmith/http_build_url": "^1.0", + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "mockery/mockery": "~1.3.1", + "phpunit/phpunit": ">=8.0", + "squizlabs/php_codesniffer": "^3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "description": "Instagram OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "instagram", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-instagram/issues", + "source": "https://github.com/thephpleague/oauth2-instagram/tree/3.1.0" + }, + "time": "2022-02-09T20:30:57+00:00" + }, + { + "name": "league/oauth2-linkedin", + "version": "5.1.2", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-linkedin.git", + "reference": "f9ab661ca37884067ca286412b6c17304d3c2fac" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-linkedin/zipball/f9ab661ca37884067ca286412b6c17304d3c2fac", + "reference": "f9ab661ca37884067ca286412b6c17304d3c2fac", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "ext-json": "*", + "mockery/mockery": "~0.9", + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "description": "LinkedIn OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "linkedin", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-linkedin/issues", + "source": "https://github.com/thephpleague/oauth2-linkedin/tree/5.1.2" + }, + "time": "2020-04-20T13:59:44+00:00" + }, + { + "name": "paragonie/random_compat", + "version": "v9.99.100", + "source": { + "type": "git", + "url": "https://github.com/paragonie/random_compat.git", + "reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/random_compat/zipball/996434e5492cb4c3edcb9168db6fbb1359ef965a", + "reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a", + "shasum": "" + }, + "require": { + "php": ">= 7" + }, + "require-dev": { + "phpunit/phpunit": "4.*|5.*", + "vimeo/psalm": "^1" + }, + "suggest": { + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + }, + "type": "library", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "polyfill", + "pseudorandom", + "random" + ], + "support": { + "email": "info@paragonie.com", + "issues": "https://github.com/paragonie/random_compat/issues", + "source": "https://github.com/paragonie/random_compat" + }, + "time": "2020-10-15T08:29:30+00:00" + }, + { + "name": "psr/http-client", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client/tree/master" + }, + "time": "2020-06-29T06:28:15+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "shasum": "" + }, + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "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 interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory/tree/master" + }, + "time": "2019-04-30T12:38:16+00:00" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "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" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "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" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/master" + }, + "time": "2016-08-06T14:39:51+00:00" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "time": "2019-03-08T08:55:37+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v2.5.2", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/e8b495ea28c1d97b5e0c121748d6f9b53d075c66", + "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.5-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v2.5.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-01-02T09:53:40+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": "^7.3.6 || ^8.0", + "ext-json": "*" + }, + "platform-dev": [], + "plugin-api-version": "2.3.0" +} diff --git a/plugins/login-oauth2/css/login-oauth2.css b/plugins/login-oauth2/css/login-oauth2.css new file mode 100644 index 0000000..ddd0c55 --- /dev/null +++ b/plugins/login-oauth2/css/login-oauth2.css @@ -0,0 +1,106 @@ +.form-oauth2 p { + font-size: inherit !important; } + +.form-oauth2 button { + background: none; + color: #fff; + border: 0; + font-family: inherit; + cursor: pointer; + outline: inherit; + display: flex; + margin-bottom: 4px; + border-radius: 3px; } + .form-oauth2 button svg { + fill: #fff; } + +.form-oauth2 button.facebook { + background: #3B5998; } + .form-oauth2 button.facebook:hover { + background: #2d4373; } + +.form-oauth2 button.github { + background: #181717; } + .form-oauth2 button.github:hover { + background: #323030; } + +.form-oauth2 button.google { + background: #4285F4; } + .form-oauth2 button.google:hover { + background: #1266f1; } + +.form-oauth2 button.instagram { + background: #E4405F; } + .form-oauth2 button.instagram:hover { + background: #d31e40; } + +.form-oauth2 button.linkedin { + background: #0077B5; } + .form-oauth2 button.linkedin:hover { + background: #005582; } + +.form-oauth2.square-style button { + display: inline-flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 10px; + min-width: 120px; } + +.form-oauth2.square-style svg { + width: 36px; + height: 36px; } + +.form-oauth2.square-style span { + display: block; + font-size: 110%; + margin: 0.5rem 0 0; } + +.form-oauth2.button-style button, .form-oauth2.row-style button { + flex-direction: row; + align-items: center; + justify-content: center; + min-width: 150px; + width: 100%; + padding: 10px; } + +.form-oauth2.button-style svg, .form-oauth2.row-style svg { + width: 24px; + height: 24px; + vertical-align: middle; } + +.form-oauth2.button-style span, .form-oauth2.row-style span { + display: inline-block; + font-size: 110%; + margin: 0 0 0 10px; + vertical-align: middle; + min-width: 100px; + text-align: left; } + +.form-oauth2 .oauth2-or { + display: flex; + margin: 1rem 0; } + .form-oauth2 .oauth2-or span { + display: block; + margin: 0; } + .form-oauth2 .oauth2-or span.line { + border-bottom: 2px solid #eee; + flex-grow: 1; } + .form-oauth2 .oauth2-or span.or { + padding: 0 15px; + margin-bottom: -15px; + font-size: 150%; + color: #999; + text-align: center; } + +#admin-login .form-oauth2 { + text-align: center; + padding-top: 1rem; } + #admin-login .form-oauth2 > p:first-child { + display: none; } + #admin-login .form-oauth2 .oauth2-or { + opacity: 0.6; + margin-bottom: -0.5rem; } + #admin-login .form-oauth2 .oauth2-or span.line { + opacity: 0.2; + border-bottom-width: 1px; } diff --git a/plugins/login-oauth2/languages/en.yaml b/plugins/login-oauth2/languages/en.yaml new file mode 100644 index 0000000..41f01a3 --- /dev/null +++ b/plugins/login-oauth2/languages/en.yaml @@ -0,0 +1,43 @@ +PLUGIN_LOGIN_OAUTH2: + CONFIGURATION: "Configuration" + DOCUMENTATION: "Instructions" + PROVIDERS: "OAuth2 Providers" + BUILTIN_CSS: "Enable built-in CSS" + BUILTIN_CSS_HELP: "If you want to provide your own custom CSS, feel free to disable the CSS provided by the plugin" + BUTTON_STYLE: "Button Style" + BUTTON_STYLE_HELLP: "If using built-in CSS, you can pick from either row or square display types for the OAUTH buttons" + SITE_CALLBACK_URI: "Site Callback URI" + SITE_CALLBACK_URI_HELP: "This is the URI that the provider will call when it has authenticated the user remotely." + REQUIRE_GRAV_USER: "Require Existing Grav user" + REQUIRE_GRAV_USER_DESC: "Deny login if user isn't an already registered user of the site" + SAVE_GRAV_USER: "Save Grav user" + SAVE_GRAV_USER_DESC: "Saves the logged in user as a local Grav account" + STORE_OAUTH2_USER: "Store Provider data" + STORE_OAUTH2_USER_DESC: "You can also store Provider data on the logged in user object to use in Grav" + DEFAULT_ACCESS_LEVELS: "Default Access Levels" + DEFAULT_ACCESS_LEVELS_DESC: "You can find more information on access levels in the [Grav Groups & Permissions](https://learn.getgrav.org/advanced/groups-and-permissions#permissions) documentation" + CLIENT_ID: "Client ID" + CLIENT_SECRET: "Client Secret" + SCOPE: "Scope" + HOST: "Host" + APP_ID: "App ID" + APP_SECRET: "App Secret" + GRAPH_API_VERSION: "Graph API Version" + AVATAR_SIZE: "Avatar Size" + RESTRICT_DOMAIN: "Hosted Domain" + ADMIN: "Admin" + ADMIN_ENABLED: "Enabled in Admin" + ADMIN_CALLBACK_URI: "Admin Callback URI" + ADMIN_CALLBACK_URI_HELP: "This is the admin callback URI. It should be prefixed with your current admin path" + DEFAULT_GROUPS: "Default Groups" + DEAFULT_GROUPS_HELP: "Here you can assign default groups to assign users to when logging in" + LOGIN_MESSAGE: "Login with one of these available social accounts..." + OR: "or" + ERROR_EXISTING_ACCOUNT: "You have already an account using %s, please use it to login" + ERROR_NO_ACCOUNT: "You do not have user account in the site for %s" + OAUTH2_LOGIN_FAILED: "OAuth2 %s Login Failed: %s" + BUTTON_FACEBOOK: Facebook + BUTTON_GITHUB: GitHub + BUTTON_GOOGLE: Google + BUTTON_INSTAGRAM: Instagram + BUTTON_LINKEDIN: LinkedIn diff --git a/plugins/login-oauth2/login-oauth2.php b/plugins/login-oauth2/login-oauth2.php new file mode 100644 index 0000000..905311c --- /dev/null +++ b/plugins/login-oauth2/login-oauth2.php @@ -0,0 +1,490 @@ + [ + ['onPluginsInitialized', 0] + ], + ]; + } + + /** + * [onPluginsInitialized:100000] Composer autoload. + * + * @return ClassLoader + */ + public function autoload(): ClassLoader + { + return require __DIR__ . '/vendor/autoload.php'; + } + + public function onTwigLoader(): void + { + $media_paths = $this->grav['locator']->findResources('plugins://login-oauth2/media'); + foreach(array_reverse($media_paths) as $images_path) { + $this->grav['twig']->addPath($images_path, 'oauth2-media'); + } + } + + /** + * [onTwigTemplatePaths] Add twig paths to plugin templates. + */ + public function onTwigTemplatePaths(): void + { + $twig = $this->grav['twig']; + $twig->twig_paths[] = __DIR__ . '/templates'; + } + + public function onTwigSiteVariables(): void + { + // add CSS for frontend if required + if ((!$this->isAdmin() && $this->config->get('plugins.login-oauth2.built_in_css')) || + ($this->admin && $this->config->get('plugins.login-oauth2.admin.built_in_css'))) { + $this->grav['assets']->add('plugin://login-oauth2/css/login-oauth2.css'); + } + } + + /** + * Initialize the plugin + */ + public function onPluginsInitialized(): void + { + if ($this->isAdmin()) { + if (!$this->grav['config']->get('plugins.login-oauth2.admin.enabled')) { + // Don't proceed if we are in the admin plugin + return; + } + $this->admin = true; + } + + $this->enable([ + 'onTask.login.oauth2' => ['loginRedirect', 0], + 'onTask.callback.oauth2' => ['loginCallback', 0], + 'onTask.delete.oauth2' => ['loginDataDelete', 0], + 'onTwigLoader' => ['onTwigLoader', 0], + 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0], + 'onTwigSiteVariables' => ['onTwigSiteVariables', 0], + 'onLoginPage' => ['onLoginPage', 10], + 'onUserLoginAuthenticate' => ['userLoginAuthenticate', 1000], + 'onUserLoginFailure' => ['userLoginFailure', 0], + 'onUserLogin' => ['userLogin', 0], + 'onUserLogout' => ['userLogout', 0], + 'onOAuth2Username' => ['onOAuth2Username', 0], + ] + ); + + // Check to ensure login plugin is enabled. + if (!$this->config->get('plugins.login.enabled')) { + throw new RuntimeException('The Login plugin needs to be installed and enabled'); + } + + $this->debug = $this->config->get('plugins.login-oauth2.debug', false); + + $isAdmin = $this->admin; + $this->grav['oauth2'] = static function () use ($isAdmin) { + // Add OAuth2 object to Grav + $oauth2 = new OAuth2($isAdmin); + $oauth2->addEnabledProviders(); + + return $oauth2; + }; + } + + /** + * Add navigation item to the admin plugin + */ + public function onLoginPage(): void + { + if ($this->grav['oauth2']->getProviders()) { + $this->grav['login']->addProviderLoginTemplate('login-oauth2/login-oauth2.html.twig'); + } + } + + /** + * Task: login.oauth2 + */ + public function loginRedirect(): void + { + /** @var OAuth2 $oauth2 */ + $oauth2 = $this->grav['oauth2']; + + $user = $this->grav['user'] ?? null; + if ($user && $user->authorized) { + throw new RuntimeException('You have already been logged in', 403); + } + + $provider_name = isset($_POST['oauth2']) ? htmlspecialchars(strip_tags($_POST['oauth2']), ENT_QUOTES, 'UTF-8') : null; + + if (!isset($provider_name)) { + throw new RuntimeException('Bad Request', 400); + } + + if ($oauth2->isValidProvider($provider_name)) { + + $provider = ProviderFactory::create($provider_name, $oauth2->getProviderOptions($provider_name)); + + /** @var Session $session */ + $session = $this->grav['session']; + $session->oauth2_state = $provider->getState(); + $session->oauth2_provider = $provider_name; + if ($this->isAdmin()) { + $redirect = (string)$this->grav['admin']->request->getUri(); + } else { + if ($this->config->get('plugins.login.redirect_after_login')) { + $redirect = (string) $this->config->get('plugins.login.route_after_login'); + } else { + /** @var Uri $uri */ + $request = $this->grav['request']; + $redirect = (string) $request->getUri(); + } + } + $session->redirect_after_login = $redirect; + + $authorizationUrl = $provider->getAuthorizationUrl(); + + $this->grav->redirect($authorizationUrl); + } + } + + /** + * Task: callback.oauth2 + */ + public function loginCallback(): void + { + /** @var Login $login */ + $login = $this->grav['login']; + + /** @var OAuth2 $oauth2 */ + $oauth2 = $this->grav['oauth2']; + + /** @var Session $session */ + $session = $this->grav['session']; + + $this->debug("session: " . json_encode($session->getAll())); + + $provider_name = $session->oauth2_provider; + $login_redirect = $session->redirect_after_login; + + /** @var Language $t */ + $t = $this->grav['language']; + /** @var Message $messages */ + $messages = $this->grav['messages']; + + $is_valid = $oauth2->isValidProvider($provider_name); + + $this->debug("provider: $provider_name - redirect: $login_redirect - is_valid: $is_valid"); + + if ($provider_name && $oauth2->isValidProvider($provider_name)) { + $state = isset($_GET['state']) ? htmlspecialchars(strip_tags($_GET['state']), ENT_QUOTES, 'UTF-8') : null; + if (empty($state)) { + $state = isset($_POST['state']) ? htmlspecialchars(strip_tags($_POST['state']), ENT_QUOTES, 'UTF-8') : null; + } + + $this->debug("sent state: $state, stored state: $session->oauth2_state"); + + if (empty($state) || ($state !== $session->oauth2_state)) { + unset($session->oauth2_state); + $this->debug("Error: $session->oauth2_state != $state"); + $messages->add($t->translate('PLUGIN_LOGIN.LOGIN_FAILED'), 'error'); + } else { + // Fire Login process. + $event = $login->login( + ['rememberme' => true], + ['admin' => $this->isAdmin(), 'remember_me' => true, 'oauth2' => true, 'provider' => $provider_name], + ['authorize' => $this->isAdmin() ? 'admin.login' : 'site.login', 'return_event' => true]); + + // Note: session variables have been reset! + $user = $event->getUser(); + if ($user->authorized) { + $event->defMessage('PLUGIN_LOGIN.LOGIN_SUCCESSFUL', 'info'); + + if ($this->isAdmin()) { + $event->defRedirect($login_redirect ?? '/'); + } else { + $event->defRedirect( + $login_redirect + ?: LoginPlugin::defaultRedirectAfterLogin() + ?: $this->grav['uri']->referrer('/') + ); + } + } elseif ($user->authenticated) { + $event->defMessage('PLUGIN_LOGIN.ACCESS_DENIED', 'error'); + + if ($this->isAdmin()) { + $event->defRedirect($login_redirect ?? '/'); + } else { + $event->defRedirect($this->grav['config']->get('plugins.login.route_unauthorized', '/')); + } + } else { + $event->defMessage('PLUGIN_LOGIN.LOGIN_FAILED', 'error'); + + if ($this->isAdmin()) { + $event->defRedirect($login_redirect ?? '/'); + } else { + $event->defRedirect($this->grav['config']->get('plugins.login.route', '/')); + } + } + + $message = $event->getMessage(); + if ($message) { + /** @var Debugger $debugger */ + $debugger = $this->grav['debugger']; + $debugger->addMessage($t->translate($message), 'debug'); + + $messages->add($t->translate($message), $event->getMessageType()); + } + + $redirect = $event->getRedirect(); + if ($redirect) { + $this->grav->redirect($redirect, $event->getRedirectCode()); + } + } + } else { + $this->grav->redirect($login_redirect ?? '/'); + } + + $uri = $this->grav['uri']; + $redirect = $uri->url(true); + $this->grav->redirect($redirect); + } + + function loginDataDelete() + { + /** @var Login $login */ + $login = $this->grav['login']; + + /** @var OAuth2 $oauth2 */ + $oauth2 = $this->grav['oauth2']; + + /** @var Session $session */ + $session = $this->grav['session']; + + $this->debug("session: " . json_encode($session->getAll())); + + $provider_name = $session->oauth2_provider; + $login_redirect = $session->redirect_after_login; + + /** @var Language $t */ + $t = $this->grav['language']; + /** @var Message $messages */ + $messages = $this->grav['messages']; + + $is_valid = $oauth2->isValidProvider($provider_name); + + $this->debug("provider: $provider_name - redirect: $login_redirect - is_valid: $is_valid"); + } + + + public function userLoginAuthenticate(UserLoginEvent $event): void + { + // Second parameter of Login::login() call. + $options = $event->getOptions(); + + if (isset($options['oauth2'])) { + $code = isset($_GET['code']) ? htmlspecialchars(strip_tags($_GET['code']), ENT_QUOTES, 'UTF-8') : null; + if (!$code) { + $code = isset($_POST['code']) ? htmlspecialchars(strip_tags($_POST['code']), ENT_QUOTES, 'UTF-8') : null; + } + + $provider_name = $options['provider']; + + $provider = ProviderFactory::create($provider_name, $options); + + try { + // Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken('authorization_code', ['code' => $code]); + + // We got an access token, let's now get the user's details + $user = $provider->getResourceOwner($token); + $userdata = $provider->getUserData($user); + + $userdata_event = new Event( + [ + 'userdata' => $userdata, + 'oauth2user' => $user, + 'provider' => $provider, + 'token' => $token + ] + ); + $this->grav->fireEvent('onOAuth2Userdata', $userdata_event); + // Set again with any event-based modifications + $userdata = $userdata_event['userdata']; + + $username_event = new Event( + [ + 'userdata' => $userdata, + 'oauth2user' => $user, + 'provider' => $provider, + 'token' => $token + ] + ); + // Get username from an event to allow you to modify oauth2 filename + $this->grav->fireEvent('onOAuth2Username', $username_event); + + $username = $username_event['username']; + + /** @var UserCollectionInterface $accounts */ + $accounts = $this->grav['accounts']; + $grav_user = $accounts->load($username); + + // If username cannot be found, fall back to email address. + $exists = $grav_user->exists(); + if (!$exists) { + $found_user = $accounts->find($userdata['email'], ['email']); + if ($found_user->exists()) { + $grav_user = $found_user; + $exists = true; + } + } + + // Make sure we're using the same provider, multiple providers are not supported. + if ($exists) { + $provider_test = $grav_user->get('provider'); + if ($provider_test && $provider_test !== $provider_name) { + throw new RuntimeException($this->translate('PLUGIN_LOGIN_OAUTH2.ERROR_EXISTING_ACCOUNT', $provider_test)); + } + } + + if ($this->config->get('plugins.login-oauth2.require_grav_user', false) && !$exists) { + throw new RuntimeException($this->translate('PLUGIN_LOGIN_OAUTH2.ERROR_NO_ACCOUNT', $username)); + } + + // Add token to user + $grav_user->set('token', json_encode($token, JSON_THROW_ON_ERROR)); + + // Set provider + $grav_user->set('provider', $provider_name); + + // Default Access levels + $current_access = $grav_user->get('access'); + if (!$current_access) { + $access = $this->config->get('plugins.login-oauth2.default_access_levels.access', []); + if (count($access) > 0) { + $grav_user->set('access', $access); + } + } + + // Default Groups + $current_groups = $grav_user->get('groups'); + if (!$current_groups) { + $groups = $this->config->get('plugins.login-oauth2.default_groups', []); + if (count($groups) > 0) { + $grav_user->set('groups', $groups); + } + } + + // Remove Provider Userdata if configured + if (!$this->config->get('plugins.login-oauth2.store_provider_data', false)) { + unset($userdata[$provider_name]); + } + + $grav_user->merge($userdata); + + $this->debug("userdata: " . json_encode($userdata)); + + // Save Grav user if so configured + if ($this->config->get('plugins.login-oauth2.save_grav_user', false)) { + $grav_user->save(); + } + + $event->setUser($grav_user); + + // Do something... + $event->setStatus($event::AUTHENTICATION_SUCCESS); + $event->stopPropagation(); + } catch (Exception $e) { + $event->setMessage($this->translate('PLUGIN_LOGIN_OAUTH2.OAUTH2_LOGIN_FAILED', ucfirst($provider_name), $e->getMessage()), 'error'); + $event->setStatus($event::AUTHENTICATION_FAILURE); + } + } + } + + public function onOAuth2Username(Event $event): void + { + $userdata = $event['userdata']; + $provider = $event['provider']; + $provider_name = strtolower($provider->getName()); + + $username_parts = [$provider_name, $userdata['id'], $userdata['login']]; + $username = implode('.', $username_parts); + + $event['username'] = $username; + + $event->stopPropagation(); + } + + public function userLoginFailure(UserLoginEvent $event): void + { + // This gets fired if user fails to log in. + } + + public function userLogin(UserLoginEvent $event): void + { + + } + + public function userLogout(UserLoginEvent $event): void + { + // This gets fired on user logout. + } + + /** + * @param mixed ...$args + * @return string + */ + private function translate(...$args): string + { + /** @var Language $language */ + $language = $this->grav['language']; + + return $language->translate($args); + } + + private function debug($message): void + { + if ($this->debug) { + $this->grav['log']->debug($message); + } + } +} diff --git a/plugins/login-oauth2/login-oauth2.yaml b/plugins/login-oauth2/login-oauth2.yaml new file mode 100644 index 0000000..6c4c5a9 --- /dev/null +++ b/plugins/login-oauth2/login-oauth2.yaml @@ -0,0 +1,98 @@ +enabled: true +debug: false +built_in_css: true +button_style: row +require_grav_user: false +save_grav_user: false +store_provider_data: true +default_access_levels: + access: + site: + login: true +default_groups: +providers: + github: + enabled: true + client_id: '' + client_secret: '' + options: + scope: ['user:email'] + + instagram: + enabled: true + client_id: '' + client_secret: '' + options: + scope: ['basic', 'likes', 'comments'] + host: 'https://api.instagram.com' + + facebook: + enabled: true + app_id: '' + app_secret: '' + options: + scope: ['email', 'public_profile', 'user_hometown'] + graph_api_version: 'v2.10' + + google: + enabled: true + client_id: '' + client_secret: '' + options: + scope: ['email', 'profile'] + avatar_size: 200 + hd: '*' + + linkedin: + enabled: true + client_id: '' + client_secret: '' + options: + scope: ['r_basicprofile','r_emailaddress'] + + + +admin: + enabled: false + built_in_css: true + button_style: row + + providers: + github: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['user', 'user:email'] + + instagram: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['basic', 'likes', 'comments'] + host: 'https://api.instagram.com' + + facebook: + enabled: false + app_id: '' + app_secret: '' + options: + scope: ['email', 'public_profile', 'user_hometown'] + graph_api_version: 'v2.10' + + google: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['email', 'profile'] + avatar_size: 200 + hd: '*' + + linkedin: + enabled: false + client_id: '' + client_secret: '' + options: + scope: ['r_basicprofile','r_emailaddress'] diff --git a/plugins/login-oauth2/media/facebook.svg b/plugins/login-oauth2/media/facebook.svg new file mode 100644 index 0000000..f55ef35 --- /dev/null +++ b/plugins/login-oauth2/media/facebook.svg @@ -0,0 +1 @@ +Facebook icon \ No newline at end of file diff --git a/plugins/login-oauth2/media/github.svg b/plugins/login-oauth2/media/github.svg new file mode 100644 index 0000000..2f9e2d9 --- /dev/null +++ b/plugins/login-oauth2/media/github.svg @@ -0,0 +1 @@ +GitHub icon \ No newline at end of file diff --git a/plugins/login-oauth2/media/google.svg b/plugins/login-oauth2/media/google.svg new file mode 100644 index 0000000..e5fffc7 --- /dev/null +++ b/plugins/login-oauth2/media/google.svg @@ -0,0 +1 @@ +Google icon \ No newline at end of file diff --git a/plugins/login-oauth2/media/instagram.svg b/plugins/login-oauth2/media/instagram.svg new file mode 100644 index 0000000..a0fed10 --- /dev/null +++ b/plugins/login-oauth2/media/instagram.svg @@ -0,0 +1 @@ +Instagram icon \ No newline at end of file diff --git a/plugins/login-oauth2/media/linkedin.svg b/plugins/login-oauth2/media/linkedin.svg new file mode 100644 index 0000000..f8a94ef --- /dev/null +++ b/plugins/login-oauth2/media/linkedin.svg @@ -0,0 +1 @@ +LinkedIn icon \ No newline at end of file diff --git a/plugins/login-oauth2/scss/login-oauth2.scss b/plugins/login-oauth2/scss/login-oauth2.scss new file mode 100644 index 0000000..0a1a18f --- /dev/null +++ b/plugins/login-oauth2/scss/login-oauth2.scss @@ -0,0 +1,158 @@ +$facebook_color: #3B5998; +$github_color: #181717; +$google_color: #4285F4; +$instagram_color: #E4405F; +$linkedin_color: #0077B5; +$label_color: #fff; + +.form-oauth2 { + + p { + font-size: inherit !important; + } + + button { + background: none; + color: $label_color; + border: 0; + font-family: inherit; + cursor: pointer; + outline: inherit; + display: flex; + margin-bottom: 4px; + border-radius: 3px; + + svg { + fill: $label_color; + } + + } + + button.facebook { + background: $facebook_color; + &:hover { + background: darken($facebook_color, 10%); + } + } + + button.github { + background: $github_color; + &:hover { + background: lighten($github_color, 10%); + } + } + + button.google { + background: $google_color; + &:hover { + background: darken($google_color, 10%); + } + } + + button.instagram { + background: $instagram_color; + &:hover { + background: darken($instagram_color, 10%); + } + } + + button.linkedin { + background: $linkedin_color; + &:hover { + background: darken($linkedin_color, 10%); + } + } + + &.square-style { + button { + display: inline-flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 10px; + min-width: 120px; + } + + svg { + width: 36px; + height: 36px; + } + + span { + display: block; + font-size: 110%; + margin: 0.5rem 0 0; + } + } + + &.button-style, &.row-style { + button { + flex-direction: row; + align-items: center; + justify-content: center; + min-width: 150px; + width: 100%; + padding: 10px; + } + svg { + width: 24px; + height: 24px; + vertical-align: middle; + } + + span { + display: inline-block; + font-size: 110%; + margin: 0 0 0 10px; + vertical-align: middle; + min-width: 100px; + text-align: left; + } + } + + .oauth2-or { + display: flex; + margin: 1rem 0; + + span { + display: block; + margin: 0; + + + &.line { + border-bottom: 2px solid #eee; + flex-grow: 1; + } + + &.or { + padding: 0 15px; + margin-bottom: -15px; + font-size: 150%; + color: #999; + text-align: center; + } + } + } + + +} + +#admin-login .form-oauth2 { + text-align: center; + + padding-top: 1rem; + + > p:first-child { + display: none; + } + + .oauth2-or { + opacity: 0.6; + margin-bottom: -0.5rem; + + span.line { + opacity: 0.2; + border-bottom-width: 1px; + } + } +} diff --git a/plugins/login-oauth2/templates/login-oauth2/login-oauth2.html.twig b/plugins/login-oauth2/templates/login-oauth2/login-oauth2.html.twig new file mode 100644 index 0000000..87e511c --- /dev/null +++ b/plugins/login-oauth2/templates/login-oauth2/login-oauth2.html.twig @@ -0,0 +1,17 @@ +{% set providers = grav.oauth2.providers %} +{% set style = grav.oauth2.isAdmin() ? grav.oauth2.config.admin.button_style : grav.oauth2.config.button_style %} +{% set style_class = style == 'row' ? 'row-style' : 'square-style' %} +
+

{{ 'PLUGIN_LOGIN_OAUTH2.LOGIN_MESSAGE'|t }}

+
+ {% for name, provider in providers %} + {% include 'login-oauth2/providers/' ~ name ~ '.html.twig' %} + {% endfor %} + +
+
+ + {{ 'PLUGIN_LOGIN_OAUTH2.OR'|t }} + +
+
diff --git a/plugins/login-oauth2/templates/login-oauth2/providers/facebook.html.twig b/plugins/login-oauth2/templates/login-oauth2/providers/facebook.html.twig new file mode 100644 index 0000000..0c64cba --- /dev/null +++ b/plugins/login-oauth2/templates/login-oauth2/providers/facebook.html.twig @@ -0,0 +1,4 @@ + \ No newline at end of file diff --git a/plugins/login-oauth2/templates/login-oauth2/providers/github.html.twig b/plugins/login-oauth2/templates/login-oauth2/providers/github.html.twig new file mode 100644 index 0000000..deb9b3f --- /dev/null +++ b/plugins/login-oauth2/templates/login-oauth2/providers/github.html.twig @@ -0,0 +1,4 @@ + diff --git a/plugins/login-oauth2/templates/login-oauth2/providers/google.html.twig b/plugins/login-oauth2/templates/login-oauth2/providers/google.html.twig new file mode 100644 index 0000000..7cf8e84 --- /dev/null +++ b/plugins/login-oauth2/templates/login-oauth2/providers/google.html.twig @@ -0,0 +1,4 @@ + \ No newline at end of file diff --git a/plugins/login-oauth2/templates/login-oauth2/providers/instagram.html.twig b/plugins/login-oauth2/templates/login-oauth2/providers/instagram.html.twig new file mode 100644 index 0000000..4c58920 --- /dev/null +++ b/plugins/login-oauth2/templates/login-oauth2/providers/instagram.html.twig @@ -0,0 +1,4 @@ + \ No newline at end of file diff --git a/plugins/login-oauth2/templates/login-oauth2/providers/linkedin.html.twig b/plugins/login-oauth2/templates/login-oauth2/providers/linkedin.html.twig new file mode 100644 index 0000000..174215e --- /dev/null +++ b/plugins/login-oauth2/templates/login-oauth2/providers/linkedin.html.twig @@ -0,0 +1,4 @@ + \ No newline at end of file diff --git a/plugins/login-oauth2/vendor/autoload.php b/plugins/login-oauth2/vendor/autoload.php new file mode 100644 index 0000000..8e3c3f9 --- /dev/null +++ b/plugins/login-oauth2/vendor/autoload.php @@ -0,0 +1,25 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var ?string */ + private $vendorDir; + + // PSR-4 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array[] + * @psalm-var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixesPsr0 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var string[] + * @psalm-var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var bool[] + * @psalm-var array + */ + private $missingClasses = array(); + + /** @var ?string */ + private $apcuPrefix; + + /** + * @var self[] + */ + private static $registeredLoaders = array(); + + /** + * @param ?string $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return string[] + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array[] + * @psalm-return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return string[] Array of classname => path + * @psalm-return array + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param string[] $classMap Class to filename map + * @psalm-param array $classMap + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $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. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + (self::$includeFile)($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + 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 (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders indexed by their corresponding vendor directories. + * + * @return self[] + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } + + private static function initializeIncludeClosure(): void + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = static function($file) { + include $file; + }; + } +} diff --git a/plugins/login-oauth2/vendor/composer/InstalledVersions.php b/plugins/login-oauth2/vendor/composer/InstalledVersions.php new file mode 100644 index 0000000..c6b54af --- /dev/null +++ b/plugins/login-oauth2/vendor/composer/InstalledVersions.php @@ -0,0 +1,352 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']); + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints($constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php'; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = require __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + $installed[] = self::$installed; + + return $installed; + } +} diff --git a/plugins/login-oauth2/vendor/composer/LICENSE b/plugins/login-oauth2/vendor/composer/LICENSE new file mode 100644 index 0000000..f27399a --- /dev/null +++ b/plugins/login-oauth2/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +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/plugins/login-oauth2/vendor/composer/autoload_classmap.php b/plugins/login-oauth2/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..0fb0a2c --- /dev/null +++ b/plugins/login-oauth2/vendor/composer/autoload_classmap.php @@ -0,0 +1,10 @@ + $vendorDir . '/composer/InstalledVersions.php', +); diff --git a/plugins/login-oauth2/vendor/composer/autoload_files.php b/plugins/login-oauth2/vendor/composer/autoload_files.php new file mode 100644 index 0000000..7fee352 --- /dev/null +++ b/plugins/login-oauth2/vendor/composer/autoload_files.php @@ -0,0 +1,14 @@ + $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php', + 'c964ee0ededf28c96ebd9db5099ef910' => $vendorDir . '/guzzlehttp/promises/src/functions_include.php', + '6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php', + 'b45b351e6b6f7487d819961fef2fda77' => $vendorDir . '/jakeasmith/http_build_url/src/http_build_url.php', +); diff --git a/plugins/login-oauth2/vendor/composer/autoload_namespaces.php b/plugins/login-oauth2/vendor/composer/autoload_namespaces.php new file mode 100644 index 0000000..15a2ff3 --- /dev/null +++ b/plugins/login-oauth2/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'), + 'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'), + 'League\\OAuth2\\Client\\' => array($vendorDir . '/league/oauth2-client/src', $vendorDir . '/league/oauth2-facebook/src', $vendorDir . '/league/oauth2-github/src', $vendorDir . '/league/oauth2-google/src', $vendorDir . '/league/oauth2-instagram/src', $vendorDir . '/league/oauth2-linkedin/src'), + 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), + 'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'), + 'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'), + 'Grav\\Plugin\\Login\\OAuth2\\' => array($baseDir . '/classes'), +); diff --git a/plugins/login-oauth2/vendor/composer/autoload_real.php b/plugins/login-oauth2/vendor/composer/autoload_real.php new file mode 100644 index 0000000..75752b6 --- /dev/null +++ b/plugins/login-oauth2/vendor/composer/autoload_real.php @@ -0,0 +1,50 @@ +register(true); + + $filesToLoad = \Composer\Autoload\ComposerStaticInit9e88f6b49322b6bce97c12c41764fc52::$files; + $requireFile = static function ($fileIdentifier, $file) { + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + + require $file; + } + }; + foreach ($filesToLoad as $fileIdentifier => $file) { + ($requireFile)($fileIdentifier, $file); + } + + return $loader; + } +} diff --git a/plugins/login-oauth2/vendor/composer/autoload_static.php b/plugins/login-oauth2/vendor/composer/autoload_static.php new file mode 100644 index 0000000..69a50ca --- /dev/null +++ b/plugins/login-oauth2/vendor/composer/autoload_static.php @@ -0,0 +1,86 @@ + __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php', + 'c964ee0ededf28c96ebd9db5099ef910' => __DIR__ . '/..' . '/guzzlehttp/promises/src/functions_include.php', + '6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', + '37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php', + 'b45b351e6b6f7487d819961fef2fda77' => __DIR__ . '/..' . '/jakeasmith/http_build_url/src/http_build_url.php', + ); + + public static $prefixLengthsPsr4 = array ( + 'P' => + array ( + 'Psr\\Http\\Message\\' => 17, + 'Psr\\Http\\Client\\' => 16, + ), + 'L' => + array ( + 'League\\OAuth2\\Client\\' => 21, + ), + 'G' => + array ( + 'GuzzleHttp\\Psr7\\' => 16, + 'GuzzleHttp\\Promise\\' => 19, + 'GuzzleHttp\\' => 11, + 'Grav\\Plugin\\Login\\OAuth2\\' => 25, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'Psr\\Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-factory/src', + 1 => __DIR__ . '/..' . '/psr/http-message/src', + ), + 'Psr\\Http\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-client/src', + ), + 'League\\OAuth2\\Client\\' => + array ( + 0 => __DIR__ . '/..' . '/league/oauth2-client/src', + 1 => __DIR__ . '/..' . '/league/oauth2-facebook/src', + 2 => __DIR__ . '/..' . '/league/oauth2-github/src', + 3 => __DIR__ . '/..' . '/league/oauth2-google/src', + 4 => __DIR__ . '/..' . '/league/oauth2-instagram/src', + 5 => __DIR__ . '/..' . '/league/oauth2-linkedin/src', + ), + 'GuzzleHttp\\Psr7\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src', + ), + 'GuzzleHttp\\Promise\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/promises/src', + ), + 'GuzzleHttp\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src', + ), + 'Grav\\Plugin\\Login\\OAuth2\\' => + array ( + 0 => __DIR__ . '/../..' . '/classes', + ), + ); + + public static $classMap = array ( + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInit9e88f6b49322b6bce97c12c41764fc52::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit9e88f6b49322b6bce97c12c41764fc52::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInit9e88f6b49322b6bce97c12c41764fc52::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/plugins/login-oauth2/vendor/composer/installed.json b/plugins/login-oauth2/vendor/composer/installed.json new file mode 100644 index 0000000..3dbff26 --- /dev/null +++ b/plugins/login-oauth2/vendor/composer/installed.json @@ -0,0 +1,1088 @@ +{ + "packages": [ + { + "name": "guzzlehttp/guzzle", + "version": "7.5.0", + "version_normalized": "7.5.0.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "b50a2a1251152e43f6a37f0fa053e730a67d25ba" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/b50a2a1251152e43f6a37f0fa053e730a67d25ba", + "reference": "b50a2a1251152e43f6a37f0fa053e730a67d25ba", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.5", + "guzzlehttp/psr7": "^1.9 || ^2.4", + "php": "^7.2.5 || ^8.0", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.1", + "ext-curl": "*", + "php-http/client-integration-tests": "^3.0", + "phpunit/phpunit": "^8.5.29 || ^9.5.23", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "time": "2022-08-28T15:39:27+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "7.5-dev" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/7.5.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/guzzle" + }, + { + "name": "guzzlehttp/promises", + "version": "1.5.2", + "version_normalized": "1.5.2.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "b94b2807d85443f9719887892882d0329d1e2598" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/b94b2807d85443f9719887892882d0329d1e2598", + "reference": "b94b2807d85443f9719887892882d0329d1e2598", + "shasum": "" + }, + "require": { + "php": ">=5.5" + }, + "require-dev": { + "symfony/phpunit-bridge": "^4.4 || ^5.1" + }, + "time": "2022-08-28T14:55:35+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.5-dev" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/1.5.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/promises" + }, + { + "name": "guzzlehttp/psr7", + "version": "2.4.3", + "version_normalized": "2.4.3.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "67c26b443f348a51926030c83481b85718457d3d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/67c26b443f348a51926030c83481b85718457d3d", + "reference": "67c26b443f348a51926030c83481b85718457d3d", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.1", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.29 || ^9.5.23" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "time": "2022-10-26T14:07:24+00:00", + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/2.4.3" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/psr7" + }, + { + "name": "jakeasmith/http_build_url", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/jakeasmith/http_build_url.git", + "reference": "93c273e77cb1edead0cf8bcf8cd2003428e74e37" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/jakeasmith/http_build_url/zipball/93c273e77cb1edead0cf8bcf8cd2003428e74e37", + "reference": "93c273e77cb1edead0cf8bcf8cd2003428e74e37", + "shasum": "" + }, + "time": "2017-05-01T15:36:40+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/http_build_url.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jake A. Smith", + "email": "theman@jakeasmith.com" + } + ], + "description": "Provides functionality for http_build_url() to environments without pecl_http.", + "install-path": "../jakeasmith/http_build_url" + }, + { + "name": "league/oauth2-client", + "version": "2.6.1", + "version_normalized": "2.6.1.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-client.git", + "reference": "2334c249907190c132364f5dae0287ab8666aa19" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-client/zipball/2334c249907190c132364f5dae0287ab8666aa19", + "reference": "2334c249907190c132364f5dae0287ab8666aa19", + "shasum": "" + }, + "require": { + "guzzlehttp/guzzle": "^6.0 || ^7.0", + "paragonie/random_compat": "^1 || ^2 || ^9.99", + "php": "^5.6 || ^7.0 || ^8.0" + }, + "require-dev": { + "mockery/mockery": "^1.3.5", + "php-parallel-lint/php-parallel-lint": "^1.3.1", + "phpunit/phpunit": "^5.7 || ^6.0 || ^9.5", + "squizlabs/php_codesniffer": "^2.3 || ^3.0" + }, + "time": "2021-12-22T16:42:49+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-2.x": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alex Bilbie", + "email": "hello@alexbilbie.com", + "homepage": "http://www.alexbilbie.com", + "role": "Developer" + }, + { + "name": "Woody Gilk", + "homepage": "https://github.com/shadowhand", + "role": "Contributor" + } + ], + "description": "OAuth 2.0 Client Library", + "keywords": [ + "Authentication", + "SSO", + "authorization", + "identity", + "idp", + "oauth", + "oauth2", + "single sign on" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-client/issues", + "source": "https://github.com/thephpleague/oauth2-client/tree/2.6.1" + }, + "install-path": "../league/oauth2-client" + }, + { + "name": "league/oauth2-facebook", + "version": "2.2.0", + "version_normalized": "2.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-facebook.git", + "reference": "ec6d62a00b548c6cd56d7b734346b9e6befbfbbb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-facebook/zipball/ec6d62a00b548c6cd56d7b734346b9e6befbfbbb", + "reference": "ec6d62a00b548c6cd56d7b734346b9e6befbfbbb", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0", + "php": ">=7.3" + }, + "require-dev": { + "ext-json": "*", + "mockery/mockery": "~1.3.0", + "phpunit/phpunit": "^9.4", + "squizlabs/php_codesniffer": "~3.0" + }, + "time": "2022-02-24T18:45:07+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Sammy Kaye Powers", + "email": "me@sammyk.me", + "homepage": "http://www.sammyk.me" + } + ], + "description": "Facebook OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "Authentication", + "authorization", + "client", + "facebook", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-facebook/issues", + "source": "https://github.com/thephpleague/oauth2-facebook/tree/2.2.0" + }, + "install-path": "../league/oauth2-facebook" + }, + { + "name": "league/oauth2-github", + "version": "2.0.0", + "version_normalized": "2.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-github.git", + "reference": "e63d64f3ec167c09232d189c6b0c397458a99357" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-github/zipball/e63d64f3ec167c09232d189c6b0c397458a99357", + "reference": "e63d64f3ec167c09232d189c6b0c397458a99357", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "mockery/mockery": "~0.9", + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~2.0" + }, + "time": "2017-01-26T01:14:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "description": "Github OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "github", + "oauth", + "oauth2" + ], + "install-path": "../league/oauth2-github" + }, + { + "name": "league/oauth2-google", + "version": "4.0.0", + "version_normalized": "4.0.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-google.git", + "reference": "db6d8ad67cdd7d014a1e5dd5c204a319a966de86" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-google/zipball/db6d8ad67cdd7d014a1e5dd5c204a319a966de86", + "reference": "db6d8ad67cdd7d014a1e5dd5c204a319a966de86", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0", + "php": ">=7.3" + }, + "require-dev": { + "eloquent/phony-phpunit": "^6.0 || ^7.1", + "phpunit/phpunit": "^8.0 || ^9.0", + "squizlabs/php_codesniffer": "^3.0" + }, + "time": "2021-03-04T21:12:06+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Woody Gilk", + "email": "woody.gilk@gmail.com", + "homepage": "http://shadowhand.me" + } + ], + "description": "Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "Authentication", + "authorization", + "client", + "google", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-google/issues", + "source": "https://github.com/thephpleague/oauth2-google/tree/4.0.0" + }, + "install-path": "../league/oauth2-google" + }, + { + "name": "league/oauth2-instagram", + "version": "3.1.0", + "version_normalized": "3.1.0.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-instagram.git", + "reference": "8de83b72498862979c3f296a17b9fc7fdf728622" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-instagram/zipball/8de83b72498862979c3f296a17b9fc7fdf728622", + "reference": "8de83b72498862979c3f296a17b9fc7fdf728622", + "shasum": "" + }, + "require": { + "jakeasmith/http_build_url": "^1.0", + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "mockery/mockery": "~1.3.1", + "phpunit/phpunit": ">=8.0", + "squizlabs/php_codesniffer": "^3.0" + }, + "time": "2022-02-09T20:30:57+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "description": "Instagram OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "instagram", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-instagram/issues", + "source": "https://github.com/thephpleague/oauth2-instagram/tree/3.1.0" + }, + "install-path": "../league/oauth2-instagram" + }, + { + "name": "league/oauth2-linkedin", + "version": "5.1.2", + "version_normalized": "5.1.2.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-linkedin.git", + "reference": "f9ab661ca37884067ca286412b6c17304d3c2fac" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-linkedin/zipball/f9ab661ca37884067ca286412b6c17304d3c2fac", + "reference": "f9ab661ca37884067ca286412b6c17304d3c2fac", + "shasum": "" + }, + "require": { + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "ext-json": "*", + "mockery/mockery": "~0.9", + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~2.0" + }, + "time": "2020-04-20T13:59:44+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "description": "LinkedIn OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "keywords": [ + "authorisation", + "authorization", + "client", + "linkedin", + "oauth", + "oauth2" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-linkedin/issues", + "source": "https://github.com/thephpleague/oauth2-linkedin/tree/5.1.2" + }, + "install-path": "../league/oauth2-linkedin" + }, + { + "name": "paragonie/random_compat", + "version": "v9.99.100", + "version_normalized": "9.99.100.0", + "source": { + "type": "git", + "url": "https://github.com/paragonie/random_compat.git", + "reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/random_compat/zipball/996434e5492cb4c3edcb9168db6fbb1359ef965a", + "reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a", + "shasum": "" + }, + "require": { + "php": ">= 7" + }, + "require-dev": { + "phpunit/phpunit": "4.*|5.*", + "vimeo/psalm": "^1" + }, + "suggest": { + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + }, + "time": "2020-10-15T08:29:30+00:00", + "type": "library", + "installation-source": "dist", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "polyfill", + "pseudorandom", + "random" + ], + "support": { + "email": "info@paragonie.com", + "issues": "https://github.com/paragonie/random_compat/issues", + "source": "https://github.com/paragonie/random_compat" + }, + "install-path": "../paragonie/random_compat" + }, + { + "name": "psr/http-client", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0" + }, + "time": "2020-06-29T06:28:15+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client/tree/master" + }, + "install-path": "../psr/http-client" + }, + { + "name": "psr/http-factory", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be", + "shasum": "" + }, + "require": { + "php": ">=7.0.0", + "psr/http-message": "^1.0" + }, + "time": "2019-04-30T12:38:16+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 interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory/tree/master" + }, + "install-path": "../psr/http-factory" + }, + { + "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" + ], + "install-path": "../psr/http-message" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "version_normalized": "3.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "time": "2019-03-08T08:55:37+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "install-path": "../ralouphie/getallheaders" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v2.5.2", + "version_normalized": "2.5.2.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/e8b495ea28c1d97b5e0c121748d6f9b53d075c66", + "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2022-01-02T09:53:40+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.5-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v2.5.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "install-path": "../symfony/deprecation-contracts" + } + ], + "dev": true, + "dev-package-names": [] +} diff --git a/plugins/login-oauth2/vendor/composer/installed.php b/plugins/login-oauth2/vendor/composer/installed.php new file mode 100644 index 0000000..0f06bd5 --- /dev/null +++ b/plugins/login-oauth2/vendor/composer/installed.php @@ -0,0 +1,185 @@ + array( + 'name' => 'trilbymedia/grav-plugin-login-oauth2', + 'pretty_version' => 'dev-develop', + 'version' => 'dev-develop', + 'reference' => 'a9c6f7cd807e1ed817b09ac4182453f9c70f8998', + 'type' => 'grav-plugin', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => true, + ), + 'versions' => array( + 'guzzlehttp/guzzle' => array( + 'pretty_version' => '7.5.0', + 'version' => '7.5.0.0', + 'reference' => 'b50a2a1251152e43f6a37f0fa053e730a67d25ba', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/guzzle', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/promises' => array( + 'pretty_version' => '1.5.2', + 'version' => '1.5.2.0', + 'reference' => 'b94b2807d85443f9719887892882d0329d1e2598', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/promises', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'guzzlehttp/psr7' => array( + 'pretty_version' => '2.4.3', + 'version' => '2.4.3.0', + 'reference' => '67c26b443f348a51926030c83481b85718457d3d', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/psr7', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'jakeasmith/http_build_url' => array( + 'pretty_version' => '1.0.1', + 'version' => '1.0.1.0', + 'reference' => '93c273e77cb1edead0cf8bcf8cd2003428e74e37', + 'type' => 'library', + 'install_path' => __DIR__ . '/../jakeasmith/http_build_url', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/oauth2-client' => array( + 'pretty_version' => '2.6.1', + 'version' => '2.6.1.0', + 'reference' => '2334c249907190c132364f5dae0287ab8666aa19', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/oauth2-client', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/oauth2-facebook' => array( + 'pretty_version' => '2.2.0', + 'version' => '2.2.0.0', + 'reference' => 'ec6d62a00b548c6cd56d7b734346b9e6befbfbbb', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/oauth2-facebook', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/oauth2-github' => array( + 'pretty_version' => '2.0.0', + 'version' => '2.0.0.0', + 'reference' => 'e63d64f3ec167c09232d189c6b0c397458a99357', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/oauth2-github', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/oauth2-google' => array( + 'pretty_version' => '4.0.0', + 'version' => '4.0.0.0', + 'reference' => 'db6d8ad67cdd7d014a1e5dd5c204a319a966de86', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/oauth2-google', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/oauth2-instagram' => array( + 'pretty_version' => '3.1.0', + 'version' => '3.1.0.0', + 'reference' => '8de83b72498862979c3f296a17b9fc7fdf728622', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/oauth2-instagram', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'league/oauth2-linkedin' => array( + 'pretty_version' => '5.1.2', + 'version' => '5.1.2.0', + 'reference' => 'f9ab661ca37884067ca286412b6c17304d3c2fac', + 'type' => 'library', + 'install_path' => __DIR__ . '/../league/oauth2-linkedin', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'paragonie/random_compat' => array( + 'pretty_version' => 'v9.99.100', + 'version' => '9.99.100.0', + 'reference' => '996434e5492cb4c3edcb9168db6fbb1359ef965a', + 'type' => 'library', + 'install_path' => __DIR__ . '/../paragonie/random_compat', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-client' => array( + 'pretty_version' => '1.0.1', + 'version' => '1.0.1.0', + 'reference' => '2dfb5f6c5eff0e91e20e913f8c5452ed95b86621', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-client', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-client-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/http-factory' => array( + 'pretty_version' => '1.0.1', + 'version' => '1.0.1.0', + 'reference' => '12ac7fcd07e5b077433f5f2bee95b3a771bf61be', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-factory', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-factory-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'psr/http-message' => array( + 'pretty_version' => '1.0.1', + 'version' => '1.0.1.0', + 'reference' => 'f6561bf28d520154e4b0ec72be95418abe6d9363', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-message', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'psr/http-message-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'ralouphie/getallheaders' => array( + 'pretty_version' => '3.0.3', + 'version' => '3.0.3.0', + 'reference' => '120b605dfeb996808c31b6477290a714d356e822', + 'type' => 'library', + 'install_path' => __DIR__ . '/../ralouphie/getallheaders', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'symfony/deprecation-contracts' => array( + 'pretty_version' => 'v2.5.2', + 'version' => '2.5.2.0', + 'reference' => 'e8b495ea28c1d97b5e0c121748d6f9b53d075c66', + 'type' => 'library', + 'install_path' => __DIR__ . '/../symfony/deprecation-contracts', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'trilbymedia/grav-plugin-login-oauth2' => array( + 'pretty_version' => 'dev-develop', + 'version' => 'dev-develop', + 'reference' => 'a9c6f7cd807e1ed817b09ac4182453f9c70f8998', + 'type' => 'grav-plugin', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/plugins/login-oauth2/vendor/composer/platform_check.php b/plugins/login-oauth2/vendor/composer/platform_check.php new file mode 100644 index 0000000..0109125 --- /dev/null +++ b/plugins/login-oauth2/vendor/composer/platform_check.php @@ -0,0 +1,26 @@ += 70306)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 7.3.6". You are running ' . PHP_VERSION . '.'; +} + +if ($issues) { + if (!headers_sent()) { + header('HTTP/1.1 500 Internal Server Error'); + } + if (!ini_get('display_errors')) { + if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { + fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); + } elseif (!headers_sent()) { + echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; + } + } + trigger_error( + 'Composer detected issues in your platform: ' . implode(' ', $issues), + E_USER_ERROR + ); +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/CHANGELOG.md b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/CHANGELOG.md new file mode 100644 index 0000000..12949ba --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/CHANGELOG.md @@ -0,0 +1,1519 @@ +# Change Log + +Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. + +## 7.5.0 - 2022-08-28 + +### Added + +- Support PHP 8.2 +- Add request to delay closure params + +## 7.4.5 - 2022-06-20 + +* Fix change in port should be considered a change in origin +* Fix `CURLOPT_HTTPAUTH` option not cleared on change of origin + +## 7.4.4 - 2022-06-09 + +* Fix failure to strip Authorization header on HTTP downgrade +* Fix failure to strip the Cookie header on change in host or HTTP downgrade + +## 7.4.3 - 2022-05-25 + +* Fix cross-domain cookie leakage + +## 7.4.2 - 2022-03-20 + +### Fixed + +- Remove curl auth on cross-domain redirects to align with the Authorization HTTP header +- Reject non-HTTP schemes in StreamHandler +- Set a default ssl.peer_name context in StreamHandler to allow `force_ip_resolve` + +## 7.4.1 - 2021-12-06 + +### Changed + +- Replaced implicit URI to string coercion [#2946](https://github.com/guzzle/guzzle/pull/2946) +- Allow `symfony/deprecation-contracts` version 3 [#2961](https://github.com/guzzle/guzzle/pull/2961) + +### Fixed + +- Only close curl handle if it's done [#2950](https://github.com/guzzle/guzzle/pull/2950) + +## 7.4.0 - 2021-10-18 + +### Added + +- Support PHP 8.1 [#2929](https://github.com/guzzle/guzzle/pull/2929), [#2939](https://github.com/guzzle/guzzle/pull/2939) +- Support `psr/log` version 2 and 3 [#2943](https://github.com/guzzle/guzzle/pull/2943) + +### Fixed + +- Make sure we always call `restore_error_handler()` [#2915](https://github.com/guzzle/guzzle/pull/2915) +- Fix progress parameter type compatibility between the cURL and stream handlers [#2936](https://github.com/guzzle/guzzle/pull/2936) +- Throw `InvalidArgumentException` when an incorrect `headers` array is provided [#2916](https://github.com/guzzle/guzzle/pull/2916), [#2942](https://github.com/guzzle/guzzle/pull/2942) + +### Changed + +- Be more strict with types [#2914](https://github.com/guzzle/guzzle/pull/2914), [#2917](https://github.com/guzzle/guzzle/pull/2917), [#2919](https://github.com/guzzle/guzzle/pull/2919), [#2945](https://github.com/guzzle/guzzle/pull/2945) + +## 7.3.0 - 2021-03-23 + +### Added + +- Support for DER and P12 certificates [#2413](https://github.com/guzzle/guzzle/pull/2413) +- Support the cURL (http://) scheme for StreamHandler proxies [#2850](https://github.com/guzzle/guzzle/pull/2850) +- Support for `guzzlehttp/psr7:^2.0` [#2878](https://github.com/guzzle/guzzle/pull/2878) + +### Fixed + +- Handle exceptions on invalid header consistently between PHP versions and handlers [#2872](https://github.com/guzzle/guzzle/pull/2872) + +## 7.2.0 - 2020-10-10 + +### Added + +- Support for PHP 8 [#2712](https://github.com/guzzle/guzzle/pull/2712), [#2715](https://github.com/guzzle/guzzle/pull/2715), [#2789](https://github.com/guzzle/guzzle/pull/2789) +- Support passing a body summarizer to the http errors middleware [#2795](https://github.com/guzzle/guzzle/pull/2795) + +### Fixed + +- Handle exceptions during response creation [#2591](https://github.com/guzzle/guzzle/pull/2591) +- Fix CURLOPT_ENCODING not to be overwritten [#2595](https://github.com/guzzle/guzzle/pull/2595) +- Make sure the Request always has a body object [#2804](https://github.com/guzzle/guzzle/pull/2804) + +### Changed + +- The `TooManyRedirectsException` has a response [#2660](https://github.com/guzzle/guzzle/pull/2660) +- Avoid "functions" from dependencies [#2712](https://github.com/guzzle/guzzle/pull/2712) + +### Deprecated + +- Using environment variable GUZZLE_CURL_SELECT_TIMEOUT [#2786](https://github.com/guzzle/guzzle/pull/2786) + +## 7.1.1 - 2020-09-30 + +### Fixed + +- Incorrect EOF detection for response body streams on Windows. + +### Changed + +- We dont connect curl `sink` on HEAD requests. +- Removed some PHP 5 workarounds + +## 7.1.0 - 2020-09-22 + +### Added + +- `GuzzleHttp\MessageFormatterInterface` + +### Fixed + +- Fixed issue that caused cookies with no value not to be stored. +- On redirects, we allow all safe methods like GET, HEAD and OPTIONS. +- Fixed logging on empty responses. +- Make sure MessageFormatter::format returns string + +### Deprecated + +- All functions in `GuzzleHttp` has been deprecated. Use static methods on `Utils` instead. +- `ClientInterface::getConfig()` +- `Client::getConfig()` +- `Client::__call()` +- `Utils::defaultCaBundle()` +- `CurlFactory::LOW_CURL_VERSION_NUMBER` + +## 7.0.1 - 2020-06-27 + +* Fix multiply defined functions fatal error [#2699](https://github.com/guzzle/guzzle/pull/2699) + +## 7.0.0 - 2020-06-27 + +No changes since 7.0.0-rc1. + +## 7.0.0-rc1 - 2020-06-15 + +### Changed + +* Use error level for logging errors in Middleware [#2629](https://github.com/guzzle/guzzle/pull/2629) +* Disabled IDN support by default and require ext-intl to use it [#2675](https://github.com/guzzle/guzzle/pull/2675) + +## 7.0.0-beta2 - 2020-05-25 + +### Added + +* Using `Utils` class instead of functions in the `GuzzleHttp` namespace. [#2546](https://github.com/guzzle/guzzle/pull/2546) +* `ClientInterface::MAJOR_VERSION` [#2583](https://github.com/guzzle/guzzle/pull/2583) + +### Changed + +* Avoid the `getenv` function when unsafe [#2531](https://github.com/guzzle/guzzle/pull/2531) +* Added real client methods [#2529](https://github.com/guzzle/guzzle/pull/2529) +* Avoid functions due to global install conflicts [#2546](https://github.com/guzzle/guzzle/pull/2546) +* Use Symfony intl-idn polyfill [#2550](https://github.com/guzzle/guzzle/pull/2550) +* Adding methods for HTTP verbs like `Client::get()`, `Client::head()`, `Client::patch()` etc [#2529](https://github.com/guzzle/guzzle/pull/2529) +* `ConnectException` extends `TransferException` [#2541](https://github.com/guzzle/guzzle/pull/2541) +* Updated the default User Agent to "GuzzleHttp/7" [#2654](https://github.com/guzzle/guzzle/pull/2654) + +### Fixed + +* Various intl icu issues [#2626](https://github.com/guzzle/guzzle/pull/2626) + +### Removed + +* Pool option `pool_size` [#2528](https://github.com/guzzle/guzzle/pull/2528) + +## 7.0.0-beta1 - 2019-12-30 + +The diff might look very big but 95% of Guzzle users will be able to upgrade without modification. +Please see [the upgrade document](UPGRADING.md) that describes all BC breaking changes. + +### Added + +* Implement PSR-18 and dropped PHP 5 support [#2421](https://github.com/guzzle/guzzle/pull/2421) [#2474](https://github.com/guzzle/guzzle/pull/2474) +* PHP 7 types [#2442](https://github.com/guzzle/guzzle/pull/2442) [#2449](https://github.com/guzzle/guzzle/pull/2449) [#2466](https://github.com/guzzle/guzzle/pull/2466) [#2497](https://github.com/guzzle/guzzle/pull/2497) [#2499](https://github.com/guzzle/guzzle/pull/2499) +* IDN support for redirects [2424](https://github.com/guzzle/guzzle/pull/2424) + +### Changed + +* Dont allow passing null as third argument to `BadResponseException::__construct()` [#2427](https://github.com/guzzle/guzzle/pull/2427) +* Use SAPI constant instead of method call [#2450](https://github.com/guzzle/guzzle/pull/2450) +* Use native function invocation [#2444](https://github.com/guzzle/guzzle/pull/2444) +* Better defaults for PHP installations with old ICU lib [2454](https://github.com/guzzle/guzzle/pull/2454) +* Added visibility to all constants [#2462](https://github.com/guzzle/guzzle/pull/2462) +* Dont allow passing `null` as URI to `Client::request()` and `Client::requestAsync()` [#2461](https://github.com/guzzle/guzzle/pull/2461) +* Widen the exception argument to throwable [#2495](https://github.com/guzzle/guzzle/pull/2495) + +### Fixed + +* Logging when Promise rejected with a string [#2311](https://github.com/guzzle/guzzle/pull/2311) + +### Removed + +* Class `SeekException` [#2162](https://github.com/guzzle/guzzle/pull/2162) +* `RequestException::getResponseBodySummary()` [#2425](https://github.com/guzzle/guzzle/pull/2425) +* `CookieJar::getCookieValue()` [#2433](https://github.com/guzzle/guzzle/pull/2433) +* `uri_template()` and `UriTemplate` [#2440](https://github.com/guzzle/guzzle/pull/2440) +* Request options `save_to` and `exceptions` [#2464](https://github.com/guzzle/guzzle/pull/2464) + +## 6.5.2 - 2019-12-23 + +* idn_to_ascii() fix for old PHP versions [#2489](https://github.com/guzzle/guzzle/pull/2489) + +## 6.5.1 - 2019-12-21 + +* Better defaults for PHP installations with old ICU lib [#2454](https://github.com/guzzle/guzzle/pull/2454) +* IDN support for redirects [#2424](https://github.com/guzzle/guzzle/pull/2424) + +## 6.5.0 - 2019-12-07 + +* Improvement: Added support for reset internal queue in MockHandler. [#2143](https://github.com/guzzle/guzzle/pull/2143) +* Improvement: Added support to pass arbitrary options to `curl_multi_init`. [#2287](https://github.com/guzzle/guzzle/pull/2287) +* Fix: Gracefully handle passing `null` to the `header` option. [#2132](https://github.com/guzzle/guzzle/pull/2132) +* Fix: `RetryMiddleware` did not do exponential delay between retires due unit mismatch. [#2132](https://github.com/guzzle/guzzle/pull/2132) +* Fix: Prevent undefined offset when using array for ssl_key options. [#2348](https://github.com/guzzle/guzzle/pull/2348) +* Deprecated `ClientInterface::VERSION` + +## 6.4.1 - 2019-10-23 + +* No `guzzle.phar` was created in 6.4.0 due expired API token. This release will fix that +* Added `parent::__construct()` to `FileCookieJar` and `SessionCookieJar` + +## 6.4.0 - 2019-10-23 + +* Improvement: Improved error messages when using curl < 7.21.2 [#2108](https://github.com/guzzle/guzzle/pull/2108) +* Fix: Test if response is readable before returning a summary in `RequestException::getResponseBodySummary()` [#2081](https://github.com/guzzle/guzzle/pull/2081) +* Fix: Add support for GUZZLE_CURL_SELECT_TIMEOUT environment variable [#2161](https://github.com/guzzle/guzzle/pull/2161) +* Improvement: Added `GuzzleHttp\Exception\InvalidArgumentException` [#2163](https://github.com/guzzle/guzzle/pull/2163) +* Improvement: Added `GuzzleHttp\_current_time()` to use `hrtime()` if that function exists. [#2242](https://github.com/guzzle/guzzle/pull/2242) +* Improvement: Added curl's `appconnect_time` in `TransferStats` [#2284](https://github.com/guzzle/guzzle/pull/2284) +* Improvement: Make GuzzleException extend Throwable wherever it's available [#2273](https://github.com/guzzle/guzzle/pull/2273) +* Fix: Prevent concurrent writes to file when saving `CookieJar` [#2335](https://github.com/guzzle/guzzle/pull/2335) +* Improvement: Update `MockHandler` so we can test transfer time [#2362](https://github.com/guzzle/guzzle/pull/2362) + +## 6.3.3 - 2018-04-22 + +* Fix: Default headers when decode_content is specified + + +## 6.3.2 - 2018-03-26 + +* Fix: Release process + + +## 6.3.1 - 2018-03-26 + +* Bug fix: Parsing 0 epoch expiry times in cookies [#2014](https://github.com/guzzle/guzzle/pull/2014) +* Improvement: Better ConnectException detection [#2012](https://github.com/guzzle/guzzle/pull/2012) +* Bug fix: Malformed domain that contains a "/" [#1999](https://github.com/guzzle/guzzle/pull/1999) +* Bug fix: Undefined offset when a cookie has no first key-value pair [#1998](https://github.com/guzzle/guzzle/pull/1998) +* Improvement: Support PHPUnit 6 [#1953](https://github.com/guzzle/guzzle/pull/1953) +* Bug fix: Support empty headers [#1915](https://github.com/guzzle/guzzle/pull/1915) +* Bug fix: Ignore case during header modifications [#1916](https://github.com/guzzle/guzzle/pull/1916) + ++ Minor code cleanups, documentation fixes and clarifications. + + +## 6.3.0 - 2017-06-22 + +* Feature: force IP resolution (ipv4 or ipv6) [#1608](https://github.com/guzzle/guzzle/pull/1608), [#1659](https://github.com/guzzle/guzzle/pull/1659) +* Improvement: Don't include summary in exception message when body is empty [#1621](https://github.com/guzzle/guzzle/pull/1621) +* Improvement: Handle `on_headers` option in MockHandler [#1580](https://github.com/guzzle/guzzle/pull/1580) +* Improvement: Added SUSE Linux CA path [#1609](https://github.com/guzzle/guzzle/issues/1609) +* Improvement: Use class reference for getting the name of the class instead of using hardcoded strings [#1641](https://github.com/guzzle/guzzle/pull/1641) +* Feature: Added `read_timeout` option [#1611](https://github.com/guzzle/guzzle/pull/1611) +* Bug fix: PHP 7.x fixes [#1685](https://github.com/guzzle/guzzle/pull/1685), [#1686](https://github.com/guzzle/guzzle/pull/1686), [#1811](https://github.com/guzzle/guzzle/pull/1811) +* Deprecation: BadResponseException instantiation without a response [#1642](https://github.com/guzzle/guzzle/pull/1642) +* Feature: Added NTLM auth [#1569](https://github.com/guzzle/guzzle/pull/1569) +* Feature: Track redirect HTTP status codes [#1711](https://github.com/guzzle/guzzle/pull/1711) +* Improvement: Check handler type during construction [#1745](https://github.com/guzzle/guzzle/pull/1745) +* Improvement: Always include the Content-Length if there's a body [#1721](https://github.com/guzzle/guzzle/pull/1721) +* Feature: Added convenience method to access a cookie by name [#1318](https://github.com/guzzle/guzzle/pull/1318) +* Bug fix: Fill `CURLOPT_CAPATH` and `CURLOPT_CAINFO` properly [#1684](https://github.com/guzzle/guzzle/pull/1684) +* Improvement: Use `\GuzzleHttp\Promise\rejection_for` function instead of object init [#1827](https://github.com/guzzle/guzzle/pull/1827) + + ++ Minor code cleanups, documentation fixes and clarifications. + +## 6.2.3 - 2017-02-28 + +* Fix deprecations with guzzle/psr7 version 1.4 + +## 6.2.2 - 2016-10-08 + +* Allow to pass nullable Response to delay callable +* Only add scheme when host is present +* Fix drain case where content-length is the literal string zero +* Obfuscate in-URL credentials in exceptions + +## 6.2.1 - 2016-07-18 + +* Address HTTP_PROXY security vulnerability, CVE-2016-5385: + https://httpoxy.org/ +* Fixing timeout bug with StreamHandler: + https://github.com/guzzle/guzzle/pull/1488 +* Only read up to `Content-Length` in PHP StreamHandler to avoid timeouts when + a server does not honor `Connection: close`. +* Ignore URI fragment when sending requests. + +## 6.2.0 - 2016-03-21 + +* Feature: added `GuzzleHttp\json_encode` and `GuzzleHttp\json_decode`. + https://github.com/guzzle/guzzle/pull/1389 +* Bug fix: Fix sleep calculation when waiting for delayed requests. + https://github.com/guzzle/guzzle/pull/1324 +* Feature: More flexible history containers. + https://github.com/guzzle/guzzle/pull/1373 +* Bug fix: defer sink stream opening in StreamHandler. + https://github.com/guzzle/guzzle/pull/1377 +* Bug fix: do not attempt to escape cookie values. + https://github.com/guzzle/guzzle/pull/1406 +* Feature: report original content encoding and length on decoded responses. + https://github.com/guzzle/guzzle/pull/1409 +* Bug fix: rewind seekable request bodies before dispatching to cURL. + https://github.com/guzzle/guzzle/pull/1422 +* Bug fix: provide an empty string to `http_build_query` for HHVM workaround. + https://github.com/guzzle/guzzle/pull/1367 + +## 6.1.1 - 2015-11-22 + +* Bug fix: Proxy::wrapSync() now correctly proxies to the appropriate handler + https://github.com/guzzle/guzzle/commit/911bcbc8b434adce64e223a6d1d14e9a8f63e4e4 +* Feature: HandlerStack is now more generic. + https://github.com/guzzle/guzzle/commit/f2102941331cda544745eedd97fc8fd46e1ee33e +* Bug fix: setting verify to false in the StreamHandler now disables peer + verification. https://github.com/guzzle/guzzle/issues/1256 +* Feature: Middleware now uses an exception factory, including more error + context. https://github.com/guzzle/guzzle/pull/1282 +* Feature: better support for disabled functions. + https://github.com/guzzle/guzzle/pull/1287 +* Bug fix: fixed regression where MockHandler was not using `sink`. + https://github.com/guzzle/guzzle/pull/1292 + +## 6.1.0 - 2015-09-08 + +* Feature: Added the `on_stats` request option to provide access to transfer + statistics for requests. https://github.com/guzzle/guzzle/pull/1202 +* Feature: Added the ability to persist session cookies in CookieJars. + https://github.com/guzzle/guzzle/pull/1195 +* Feature: Some compatibility updates for Google APP Engine + https://github.com/guzzle/guzzle/pull/1216 +* Feature: Added support for NO_PROXY to prevent the use of a proxy based on + a simple set of rules. https://github.com/guzzle/guzzle/pull/1197 +* Feature: Cookies can now contain square brackets. + https://github.com/guzzle/guzzle/pull/1237 +* Bug fix: Now correctly parsing `=` inside of quotes in Cookies. + https://github.com/guzzle/guzzle/pull/1232 +* Bug fix: Cusotm cURL options now correctly override curl options of the + same name. https://github.com/guzzle/guzzle/pull/1221 +* Bug fix: Content-Type header is now added when using an explicitly provided + multipart body. https://github.com/guzzle/guzzle/pull/1218 +* Bug fix: Now ignoring Set-Cookie headers that have no name. +* Bug fix: Reason phrase is no longer cast to an int in some cases in the + cURL handler. https://github.com/guzzle/guzzle/pull/1187 +* Bug fix: Remove the Authorization header when redirecting if the Host + header changes. https://github.com/guzzle/guzzle/pull/1207 +* Bug fix: Cookie path matching fixes + https://github.com/guzzle/guzzle/issues/1129 +* Bug fix: Fixing the cURL `body_as_string` setting + https://github.com/guzzle/guzzle/pull/1201 +* Bug fix: quotes are no longer stripped when parsing cookies. + https://github.com/guzzle/guzzle/issues/1172 +* Bug fix: `form_params` and `query` now always uses the `&` separator. + https://github.com/guzzle/guzzle/pull/1163 +* Bug fix: Adding a Content-Length to PHP stream wrapper requests if not set. + https://github.com/guzzle/guzzle/pull/1189 + +## 6.0.2 - 2015-07-04 + +* Fixed a memory leak in the curl handlers in which references to callbacks + were not being removed by `curl_reset`. +* Cookies are now extracted properly before redirects. +* Cookies now allow more character ranges. +* Decoded Content-Encoding responses are now modified to correctly reflect + their state if the encoding was automatically removed by a handler. This + means that the `Content-Encoding` header may be removed an the + `Content-Length` modified to reflect the message size after removing the + encoding. +* Added a more explicit error message when trying to use `form_params` and + `multipart` in the same request. +* Several fixes for HHVM support. +* Functions are now conditionally required using an additional level of + indirection to help with global Composer installations. + +## 6.0.1 - 2015-05-27 + +* Fixed a bug with serializing the `query` request option where the `&` + separator was missing. +* Added a better error message for when `body` is provided as an array. Please + use `form_params` or `multipart` instead. +* Various doc fixes. + +## 6.0.0 - 2015-05-26 + +* See the UPGRADING.md document for more information. +* Added `multipart` and `form_params` request options. +* Added `synchronous` request option. +* Added the `on_headers` request option. +* Fixed `expect` handling. +* No longer adding default middlewares in the client ctor. These need to be + present on the provided handler in order to work. +* Requests are no longer initiated when sending async requests with the + CurlMultiHandler. This prevents unexpected recursion from requests completing + while ticking the cURL loop. +* Removed the semantics of setting `default` to `true`. This is no longer + required now that the cURL loop is not ticked for async requests. +* Added request and response logging middleware. +* No longer allowing self signed certificates when using the StreamHandler. +* Ensuring that `sink` is valid if saving to a file. +* Request exceptions now include a "handler context" which provides handler + specific contextual information. +* Added `GuzzleHttp\RequestOptions` to allow request options to be applied + using constants. +* `$maxHandles` has been removed from CurlMultiHandler. +* `MultipartPostBody` is now part of the `guzzlehttp/psr7` package. + +## 5.3.0 - 2015-05-19 + +* Mock now supports `save_to` +* Marked `AbstractRequestEvent::getTransaction()` as public. +* Fixed a bug in which multiple headers using different casing would overwrite + previous headers in the associative array. +* Added `Utils::getDefaultHandler()` +* Marked `GuzzleHttp\Client::getDefaultUserAgent` as deprecated. +* URL scheme is now always lowercased. + +## 6.0.0-beta.1 + +* Requires PHP >= 5.5 +* Updated to use PSR-7 + * Requires immutable messages, which basically means an event based system + owned by a request instance is no longer possible. + * Utilizing the [Guzzle PSR-7 package](https://github.com/guzzle/psr7). + * Removed the dependency on `guzzlehttp/streams`. These stream abstractions + are available in the `guzzlehttp/psr7` package under the `GuzzleHttp\Psr7` + namespace. +* Added middleware and handler system + * Replaced the Guzzle event and subscriber system with a middleware system. + * No longer depends on RingPHP, but rather places the HTTP handlers directly + in Guzzle, operating on PSR-7 messages. + * Retry logic is now encapsulated in `GuzzleHttp\Middleware::retry`, which + means the `guzzlehttp/retry-subscriber` is now obsolete. + * Mocking responses is now handled using `GuzzleHttp\Handler\MockHandler`. +* Asynchronous responses + * No longer supports the `future` request option to send an async request. + Instead, use one of the `*Async` methods of a client (e.g., `requestAsync`, + `getAsync`, etc.). + * Utilizing `GuzzleHttp\Promise` instead of React's promise library to avoid + recursion required by chaining and forwarding react promises. See + https://github.com/guzzle/promises + * Added `requestAsync` and `sendAsync` to send request asynchronously. + * Added magic methods for `getAsync()`, `postAsync()`, etc. to send requests + asynchronously. +* Request options + * POST and form updates + * Added the `form_fields` and `form_files` request options. + * Removed the `GuzzleHttp\Post` namespace. + * The `body` request option no longer accepts an array for POST requests. + * The `exceptions` request option has been deprecated in favor of the + `http_errors` request options. + * The `save_to` request option has been deprecated in favor of `sink` request + option. +* Clients no longer accept an array of URI template string and variables for + URI variables. You will need to expand URI templates before passing them + into a client constructor or request method. +* Client methods `get()`, `post()`, `put()`, `patch()`, `options()`, etc. are + now magic methods that will send synchronous requests. +* Replaced `Utils.php` with plain functions in `functions.php`. +* Removed `GuzzleHttp\Collection`. +* Removed `GuzzleHttp\BatchResults`. Batched pool results are now returned as + an array. +* Removed `GuzzleHttp\Query`. Query string handling is now handled using an + associative array passed into the `query` request option. The query string + is serialized using PHP's `http_build_query`. If you need more control, you + can pass the query string in as a string. +* `GuzzleHttp\QueryParser` has been replaced with the + `GuzzleHttp\Psr7\parse_query`. + +## 5.2.0 - 2015-01-27 + +* Added `AppliesHeadersInterface` to make applying headers to a request based + on the body more generic and not specific to `PostBodyInterface`. +* Reduced the number of stack frames needed to send requests. +* Nested futures are now resolved in the client rather than the RequestFsm +* Finishing state transitions is now handled in the RequestFsm rather than the + RingBridge. +* Added a guard in the Pool class to not use recursion for request retries. + +## 5.1.0 - 2014-12-19 + +* Pool class no longer uses recursion when a request is intercepted. +* The size of a Pool can now be dynamically adjusted using a callback. + See https://github.com/guzzle/guzzle/pull/943. +* Setting a request option to `null` when creating a request with a client will + ensure that the option is not set. This allows you to overwrite default + request options on a per-request basis. + See https://github.com/guzzle/guzzle/pull/937. +* Added the ability to limit which protocols are allowed for redirects by + specifying a `protocols` array in the `allow_redirects` request option. +* Nested futures due to retries are now resolved when waiting for synchronous + responses. See https://github.com/guzzle/guzzle/pull/947. +* `"0"` is now an allowed URI path. See + https://github.com/guzzle/guzzle/pull/935. +* `Query` no longer typehints on the `$query` argument in the constructor, + allowing for strings and arrays. +* Exceptions thrown in the `end` event are now correctly wrapped with Guzzle + specific exceptions if necessary. + +## 5.0.3 - 2014-11-03 + +This change updates query strings so that they are treated as un-encoded values +by default where the value represents an un-encoded value to send over the +wire. A Query object then encodes the value before sending over the wire. This +means that even value query string values (e.g., ":") are url encoded. This +makes the Query class match PHP's http_build_query function. However, if you +want to send requests over the wire using valid query string characters that do +not need to be encoded, then you can provide a string to Url::setQuery() and +pass true as the second argument to specify that the query string is a raw +string that should not be parsed or encoded (unless a call to getQuery() is +subsequently made, forcing the query-string to be converted into a Query +object). + +## 5.0.2 - 2014-10-30 + +* Added a trailing `\r\n` to multipart/form-data payloads. See + https://github.com/guzzle/guzzle/pull/871 +* Added a `GuzzleHttp\Pool::send()` convenience method to match the docs. +* Status codes are now returned as integers. See + https://github.com/guzzle/guzzle/issues/881 +* No longer overwriting an existing `application/x-www-form-urlencoded` header + when sending POST requests, allowing for customized headers. See + https://github.com/guzzle/guzzle/issues/877 +* Improved path URL serialization. + + * No longer double percent-encoding characters in the path or query string if + they are already encoded. + * Now properly encoding the supplied path to a URL object, instead of only + encoding ' ' and '?'. + * Note: This has been changed in 5.0.3 to now encode query string values by + default unless the `rawString` argument is provided when setting the query + string on a URL: Now allowing many more characters to be present in the + query string without being percent encoded. See https://tools.ietf.org/html/rfc3986#appendix-A + +## 5.0.1 - 2014-10-16 + +Bugfix release. + +* Fixed an issue where connection errors still returned response object in + error and end events event though the response is unusable. This has been + corrected so that a response is not returned in the `getResponse` method of + these events if the response did not complete. https://github.com/guzzle/guzzle/issues/867 +* Fixed an issue where transfer statistics were not being populated in the + RingBridge. https://github.com/guzzle/guzzle/issues/866 + +## 5.0.0 - 2014-10-12 + +Adding support for non-blocking responses and some minor API cleanup. + +### New Features + +* Added support for non-blocking responses based on `guzzlehttp/guzzle-ring`. +* Added a public API for creating a default HTTP adapter. +* Updated the redirect plugin to be non-blocking so that redirects are sent + concurrently. Other plugins like this can now be updated to be non-blocking. +* Added a "progress" event so that you can get upload and download progress + events. +* Added `GuzzleHttp\Pool` which implements FutureInterface and transfers + requests concurrently using a capped pool size as efficiently as possible. +* Added `hasListeners()` to EmitterInterface. +* Removed `GuzzleHttp\ClientInterface::sendAll` and marked + `GuzzleHttp\Client::sendAll` as deprecated (it's still there, just not the + recommended way). + +### Breaking changes + +The breaking changes in this release are relatively minor. The biggest thing to +look out for is that request and response objects no longer implement fluent +interfaces. + +* Removed the fluent interfaces (i.e., `return $this`) from requests, + responses, `GuzzleHttp\Collection`, `GuzzleHttp\Url`, + `GuzzleHttp\Query`, `GuzzleHttp\Post\PostBody`, and + `GuzzleHttp\Cookie\SetCookie`. This blog post provides a good outline of + why I did this: https://ocramius.github.io/blog/fluent-interfaces-are-evil/. + This also makes the Guzzle message interfaces compatible with the current + PSR-7 message proposal. +* Removed "functions.php", so that Guzzle is truly PSR-4 compliant. Except + for the HTTP request functions from function.php, these functions are now + implemented in `GuzzleHttp\Utils` using camelCase. `GuzzleHttp\json_decode` + moved to `GuzzleHttp\Utils::jsonDecode`. `GuzzleHttp\get_path` moved to + `GuzzleHttp\Utils::getPath`. `GuzzleHttp\set_path` moved to + `GuzzleHttp\Utils::setPath`. `GuzzleHttp\batch` should now be + `GuzzleHttp\Pool::batch`, which returns an `objectStorage`. Using functions.php + caused problems for many users: they aren't PSR-4 compliant, require an + explicit include, and needed an if-guard to ensure that the functions are not + declared multiple times. +* Rewrote adapter layer. + * Removing all classes from `GuzzleHttp\Adapter`, these are now + implemented as callables that are stored in `GuzzleHttp\Ring\Client`. + * Removed the concept of "parallel adapters". Sending requests serially or + concurrently is now handled using a single adapter. + * Moved `GuzzleHttp\Adapter\Transaction` to `GuzzleHttp\Transaction`. The + Transaction object now exposes the request, response, and client as public + properties. The getters and setters have been removed. +* Removed the "headers" event. This event was only useful for changing the + body a response once the headers of the response were known. You can implement + a similar behavior in a number of ways. One example might be to use a + FnStream that has access to the transaction being sent. For example, when the + first byte is written, you could check if the response headers match your + expectations, and if so, change the actual stream body that is being + written to. +* Removed the `asArray` parameter from + `GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header + value as an array, then use the newly added `getHeaderAsArray()` method of + `MessageInterface`. This change makes the Guzzle interfaces compatible with + the PSR-7 interfaces. +* `GuzzleHttp\Message\MessageFactory` no longer allows subclasses to add + custom request options using double-dispatch (this was an implementation + detail). Instead, you should now provide an associative array to the + constructor which is a mapping of the request option name mapping to a + function that applies the option value to a request. +* Removed the concept of "throwImmediately" from exceptions and error events. + This control mechanism was used to stop a transfer of concurrent requests + from completing. This can now be handled by throwing the exception or by + cancelling a pool of requests or each outstanding future request individually. +* Updated to "GuzzleHttp\Streams" 3.0. + * `GuzzleHttp\Stream\StreamInterface::getContents()` no longer accepts a + `maxLen` parameter. This update makes the Guzzle streams project + compatible with the current PSR-7 proposal. + * `GuzzleHttp\Stream\Stream::__construct`, + `GuzzleHttp\Stream\Stream::factory`, and + `GuzzleHttp\Stream\Utils::create` no longer accept a size in the second + argument. They now accept an associative array of options, including the + "size" key and "metadata" key which can be used to provide custom metadata. + +## 4.2.2 - 2014-09-08 + +* Fixed a memory leak in the CurlAdapter when reusing cURL handles. +* No longer using `request_fulluri` in stream adapter proxies. +* Relative redirects are now based on the last response, not the first response. + +## 4.2.1 - 2014-08-19 + +* Ensuring that the StreamAdapter does not always add a Content-Type header +* Adding automated github releases with a phar and zip + +## 4.2.0 - 2014-08-17 + +* Now merging in default options using a case-insensitive comparison. + Closes https://github.com/guzzle/guzzle/issues/767 +* Added the ability to automatically decode `Content-Encoding` response bodies + using the `decode_content` request option. This is set to `true` by default + to decode the response body if it comes over the wire with a + `Content-Encoding`. Set this value to `false` to disable decoding the + response content, and pass a string to provide a request `Accept-Encoding` + header and turn on automatic response decoding. This feature now allows you + to pass an `Accept-Encoding` header in the headers of a request but still + disable automatic response decoding. + Closes https://github.com/guzzle/guzzle/issues/764 +* Added the ability to throw an exception immediately when transferring + requests in parallel. Closes https://github.com/guzzle/guzzle/issues/760 +* Updating guzzlehttp/streams dependency to ~2.1 +* No longer utilizing the now deprecated namespaced methods from the stream + package. + +## 4.1.8 - 2014-08-14 + +* Fixed an issue in the CurlFactory that caused setting the `stream=false` + request option to throw an exception. + See: https://github.com/guzzle/guzzle/issues/769 +* TransactionIterator now calls rewind on the inner iterator. + See: https://github.com/guzzle/guzzle/pull/765 +* You can now set the `Content-Type` header to `multipart/form-data` + when creating POST requests to force multipart bodies. + See https://github.com/guzzle/guzzle/issues/768 + +## 4.1.7 - 2014-08-07 + +* Fixed an error in the HistoryPlugin that caused the same request and response + to be logged multiple times when an HTTP protocol error occurs. +* Ensuring that cURL does not add a default Content-Type when no Content-Type + has been supplied by the user. This prevents the adapter layer from modifying + the request that is sent over the wire after any listeners may have already + put the request in a desired state (e.g., signed the request). +* Throwing an exception when you attempt to send requests that have the + "stream" set to true in parallel using the MultiAdapter. +* Only calling curl_multi_select when there are active cURL handles. This was + previously changed and caused performance problems on some systems due to PHP + always selecting until the maximum select timeout. +* Fixed a bug where multipart/form-data POST fields were not correctly + aggregated (e.g., values with "&"). + +## 4.1.6 - 2014-08-03 + +* Added helper methods to make it easier to represent messages as strings, + including getting the start line and getting headers as a string. + +## 4.1.5 - 2014-08-02 + +* Automatically retrying cURL "Connection died, retrying a fresh connect" + errors when possible. +* cURL implementation cleanup +* Allowing multiple event subscriber listeners to be registered per event by + passing an array of arrays of listener configuration. + +## 4.1.4 - 2014-07-22 + +* Fixed a bug that caused multi-part POST requests with more than one field to + serialize incorrectly. +* Paths can now be set to "0" +* `ResponseInterface::xml` now accepts a `libxml_options` option and added a + missing default argument that was required when parsing XML response bodies. +* A `save_to` stream is now created lazily, which means that files are not + created on disk unless a request succeeds. + +## 4.1.3 - 2014-07-15 + +* Various fixes to multipart/form-data POST uploads +* Wrapping function.php in an if-statement to ensure Guzzle can be used + globally and in a Composer install +* Fixed an issue with generating and merging in events to an event array +* POST headers are only applied before sending a request to allow you to change + the query aggregator used before uploading +* Added much more robust query string parsing +* Fixed various parsing and normalization issues with URLs +* Fixing an issue where multi-valued headers were not being utilized correctly + in the StreamAdapter + +## 4.1.2 - 2014-06-18 + +* Added support for sending payloads with GET requests + +## 4.1.1 - 2014-06-08 + +* Fixed an issue related to using custom message factory options in subclasses +* Fixed an issue with nested form fields in a multi-part POST +* Fixed an issue with using the `json` request option for POST requests +* Added `ToArrayInterface` to `GuzzleHttp\Cookie\CookieJar` + +## 4.1.0 - 2014-05-27 + +* Added a `json` request option to easily serialize JSON payloads. +* Added a `GuzzleHttp\json_decode()` wrapper to safely parse JSON. +* Added `setPort()` and `getPort()` to `GuzzleHttp\Message\RequestInterface`. +* Added the ability to provide an emitter to a client in the client constructor. +* Added the ability to persist a cookie session using $_SESSION. +* Added a trait that can be used to add event listeners to an iterator. +* Removed request method constants from RequestInterface. +* Fixed warning when invalid request start-lines are received. +* Updated MessageFactory to work with custom request option methods. +* Updated cacert bundle to latest build. + +4.0.2 (2014-04-16) +------------------ + +* Proxy requests using the StreamAdapter now properly use request_fulluri (#632) +* Added the ability to set scalars as POST fields (#628) + +## 4.0.1 - 2014-04-04 + +* The HTTP status code of a response is now set as the exception code of + RequestException objects. +* 303 redirects will now correctly switch from POST to GET requests. +* The default parallel adapter of a client now correctly uses the MultiAdapter. +* HasDataTrait now initializes the internal data array as an empty array so + that the toArray() method always returns an array. + +## 4.0.0 - 2014-03-29 + +* For information on changes and upgrading, see: + https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 +* Added `GuzzleHttp\batch()` as a convenience function for sending requests in + parallel without needing to write asynchronous code. +* Restructured how events are added to `GuzzleHttp\ClientInterface::sendAll()`. + You can now pass a callable or an array of associative arrays where each + associative array contains the "fn", "priority", and "once" keys. + +## 4.0.0.rc-2 - 2014-03-25 + +* Removed `getConfig()` and `setConfig()` from clients to avoid confusion + around whether things like base_url, message_factory, etc. should be able to + be retrieved or modified. +* Added `getDefaultOption()` and `setDefaultOption()` to ClientInterface +* functions.php functions were renamed using snake_case to match PHP idioms +* Added support for `HTTP_PROXY`, `HTTPS_PROXY`, and + `GUZZLE_CURL_SELECT_TIMEOUT` environment variables +* Added the ability to specify custom `sendAll()` event priorities +* Added the ability to specify custom stream context options to the stream + adapter. +* Added a functions.php function for `get_path()` and `set_path()` +* CurlAdapter and MultiAdapter now use a callable to generate curl resources +* MockAdapter now properly reads a body and emits a `headers` event +* Updated Url class to check if a scheme and host are set before adding ":" + and "//". This allows empty Url (e.g., "") to be serialized as "". +* Parsing invalid XML no longer emits warnings +* Curl classes now properly throw AdapterExceptions +* Various performance optimizations +* Streams are created with the faster `Stream\create()` function +* Marked deprecation_proxy() as internal +* Test server is now a collection of static methods on a class + +## 4.0.0-rc.1 - 2014-03-15 + +* See https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 + +## 3.8.1 - 2014-01-28 + +* Bug: Always using GET requests when redirecting from a 303 response +* Bug: CURLOPT_SSL_VERIFYHOST is now correctly set to false when setting `$certificateAuthority` to false in + `Guzzle\Http\ClientInterface::setSslVerification()` +* Bug: RedirectPlugin now uses strict RFC 3986 compliance when combining a base URL with a relative URL +* Bug: The body of a request can now be set to `"0"` +* Sending PHP stream requests no longer forces `HTTP/1.0` +* Adding more information to ExceptionCollection exceptions so that users have more context, including a stack trace of + each sub-exception +* Updated the `$ref` attribute in service descriptions to merge over any existing parameters of a schema (rather than + clobbering everything). +* Merging URLs will now use the query string object from the relative URL (thus allowing custom query aggregators) +* Query strings are now parsed in a way that they do no convert empty keys with no value to have a dangling `=`. + For example `foo&bar=baz` is now correctly parsed and recognized as `foo&bar=baz` rather than `foo=&bar=baz`. +* Now properly escaping the regular expression delimiter when matching Cookie domains. +* Network access is now disabled when loading XML documents + +## 3.8.0 - 2013-12-05 + +* Added the ability to define a POST name for a file +* JSON response parsing now properly walks additionalProperties +* cURL error code 18 is now retried automatically in the BackoffPlugin +* Fixed a cURL error when URLs contain fragments +* Fixed an issue in the BackoffPlugin retry event where it was trying to access all exceptions as if they were + CurlExceptions +* CURLOPT_PROGRESS function fix for PHP 5.5 (69fcc1e) +* Added the ability for Guzzle to work with older versions of cURL that do not support `CURLOPT_TIMEOUT_MS` +* Fixed a bug that was encountered when parsing empty header parameters +* UriTemplate now has a `setRegex()` method to match the docs +* The `debug` request parameter now checks if it is truthy rather than if it exists +* Setting the `debug` request parameter to true shows verbose cURL output instead of using the LogPlugin +* Added the ability to combine URLs using strict RFC 3986 compliance +* Command objects can now return the validation errors encountered by the command +* Various fixes to cache revalidation (#437 and 29797e5) +* Various fixes to the AsyncPlugin +* Cleaned up build scripts + +## 3.7.4 - 2013-10-02 + +* Bug fix: 0 is now an allowed value in a description parameter that has a default value (#430) +* Bug fix: SchemaFormatter now returns an integer when formatting to a Unix timestamp + (see https://github.com/aws/aws-sdk-php/issues/147) +* Bug fix: Cleaned up and fixed URL dot segment removal to properly resolve internal dots +* Minimum PHP version is now properly specified as 5.3.3 (up from 5.3.2) (#420) +* Updated the bundled cacert.pem (#419) +* OauthPlugin now supports adding authentication to headers or query string (#425) + +## 3.7.3 - 2013-09-08 + +* Added the ability to get the exception associated with a request/command when using `MultiTransferException` and + `CommandTransferException`. +* Setting `additionalParameters` of a response to false is now honored when parsing responses with a service description +* Schemas are only injected into response models when explicitly configured. +* No longer guessing Content-Type based on the path of a request. Content-Type is now only guessed based on the path of + an EntityBody. +* Bug fix: ChunkedIterator can now properly chunk a \Traversable as well as an \Iterator. +* Bug fix: FilterIterator now relies on `\Iterator` instead of `\Traversable`. +* Bug fix: Gracefully handling malformed responses in RequestMediator::writeResponseBody() +* Bug fix: Replaced call to canCache with canCacheRequest in the CallbackCanCacheStrategy of the CachePlugin +* Bug fix: Visiting XML attributes first before visiting XML children when serializing requests +* Bug fix: Properly parsing headers that contain commas contained in quotes +* Bug fix: mimetype guessing based on a filename is now case-insensitive + +## 3.7.2 - 2013-08-02 + +* Bug fix: Properly URL encoding paths when using the PHP-only version of the UriTemplate expander + See https://github.com/guzzle/guzzle/issues/371 +* Bug fix: Cookie domains are now matched correctly according to RFC 6265 + See https://github.com/guzzle/guzzle/issues/377 +* Bug fix: GET parameters are now used when calculating an OAuth signature +* Bug fix: Fixed an issue with cache revalidation where the If-None-Match header was being double quoted +* `Guzzle\Common\AbstractHasDispatcher::dispatch()` now returns the event that was dispatched +* `Guzzle\Http\QueryString::factory()` now guesses the most appropriate query aggregator to used based on the input. + See https://github.com/guzzle/guzzle/issues/379 +* Added a way to add custom domain objects to service description parsing using the `operation.parse_class` event. See + https://github.com/guzzle/guzzle/pull/380 +* cURL multi cleanup and optimizations + +## 3.7.1 - 2013-07-05 + +* Bug fix: Setting default options on a client now works +* Bug fix: Setting options on HEAD requests now works. See #352 +* Bug fix: Moving stream factory before send event to before building the stream. See #353 +* Bug fix: Cookies no longer match on IP addresses per RFC 6265 +* Bug fix: Correctly parsing header parameters that are in `<>` and quotes +* Added `cert` and `ssl_key` as request options +* `Host` header can now diverge from the host part of a URL if the header is set manually +* `Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor` was rewritten to change from using SimpleXML to XMLWriter +* OAuth parameters are only added via the plugin if they aren't already set +* Exceptions are now thrown when a URL cannot be parsed +* Returning `false` if `Guzzle\Http\EntityBody::getContentMd5()` fails +* Not setting a `Content-MD5` on a command if calculating the Content-MD5 fails via the CommandContentMd5Plugin + +## 3.7.0 - 2013-06-10 + +* See UPGRADING.md for more information on how to upgrade. +* Requests now support the ability to specify an array of $options when creating a request to more easily modify a + request. You can pass a 'request.options' configuration setting to a client to apply default request options to + every request created by a client (e.g. default query string variables, headers, curl options, etc.). +* Added a static facade class that allows you to use Guzzle with static methods and mount the class to `\Guzzle`. + See `Guzzle\Http\StaticClient::mount`. +* Added `command.request_options` to `Guzzle\Service\Command\AbstractCommand` to pass request options to requests + created by a command (e.g. custom headers, query string variables, timeout settings, etc.). +* Stream size in `Guzzle\Stream\PhpStreamRequestFactory` will now be set if Content-Length is returned in the + headers of a response +* Added `Guzzle\Common\Collection::setPath($path, $value)` to set a value into an array using a nested key + (e.g. `$collection->setPath('foo/baz/bar', 'test'); echo $collection['foo']['bar']['bar'];`) +* ServiceBuilders now support storing and retrieving arbitrary data +* CachePlugin can now purge all resources for a given URI +* CachePlugin can automatically purge matching cached items when a non-idempotent request is sent to a resource +* CachePlugin now uses the Vary header to determine if a resource is a cache hit +* `Guzzle\Http\Message\Response` now implements `\Serializable` +* Added `Guzzle\Cache\CacheAdapterFactory::fromCache()` to more easily create cache adapters +* `Guzzle\Service\ClientInterface::execute()` now accepts an array, single command, or Traversable +* Fixed a bug in `Guzzle\Http\Message\Header\Link::addLink()` +* Better handling of calculating the size of a stream in `Guzzle\Stream\Stream` using fstat() and caching the size +* `Guzzle\Common\Exception\ExceptionCollection` now creates a more readable exception message +* Fixing BC break: Added back the MonologLogAdapter implementation rather than extending from PsrLog so that older + Symfony users can still use the old version of Monolog. +* Fixing BC break: Added the implementation back in for `Guzzle\Http\Message\AbstractMessage::getTokenizedHeader()`. + Now triggering an E_USER_DEPRECATED warning when used. Use `$message->getHeader()->parseParams()`. +* Several performance improvements to `Guzzle\Common\Collection` +* Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +* Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +* Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +* Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +* Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +* Added `Guzzle\Stream\StreamInterface::isRepeatable` +* Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))`. +* Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`. +* Removed `Guzzle\Http\ClientInterface::expandTemplate()` +* Removed `Guzzle\Http\ClientInterface::setRequestFactory()` +* Removed `Guzzle\Http\ClientInterface::getCurlMulti()` +* Removed `Guzzle\Http\Message\RequestInterface::canCache` +* Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect` +* Removed `Guzzle\Http\Message\RequestInterface::isRedirect` +* Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. +* You can now enable E_USER_DEPRECATED warnings to see if you are using a deprecated method by setting + `Guzzle\Common\Version::$emitWarnings` to true. +* Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use + `$request->getResponseBody()->isRepeatable()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +* Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. + These will work through Guzzle 4.0 +* Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use [request.options][params]. +* Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +* Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers')`. +* Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. +* Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +* Marked `Guzzle\Common\Collection::inject()` as deprecated. +* Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');` +* CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +* Always setting X-cache headers on cached responses +* Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +* `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +* `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +* `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +* Added `CacheStorageInterface::purge($url)` +* `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +* Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +## 3.6.0 - 2013-05-29 + +* ServiceDescription now implements ToArrayInterface +* Added command.hidden_params to blacklist certain headers from being treated as additionalParameters +* Guzzle can now correctly parse incomplete URLs +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess +* Added the ability to cast Model objects to a string to view debug information. + +## 3.5.0 - 2013-05-13 + +* Bug: Fixed a regression so that request responses are parsed only once per oncomplete event rather than multiple times +* Bug: Better cleanup of one-time events across the board (when an event is meant to fire once, it will now remove + itself from the EventDispatcher) +* Bug: `Guzzle\Log\MessageFormatter` now properly writes "total_time" and "connect_time" values +* Bug: Cloning an EntityEnclosingRequest now clones the EntityBody too +* Bug: Fixed an undefined index error when parsing nested JSON responses with a sentAs parameter that reference a + non-existent key +* Bug: All __call() method arguments are now required (helps with mocking frameworks) +* Deprecating Response::getRequest() and now using a shallow clone of a request object to remove a circular reference + to help with refcount based garbage collection of resources created by sending a request +* Deprecating ZF1 cache and log adapters. These will be removed in the next major version. +* Deprecating `Response::getPreviousResponse()` (method signature still exists, but it's deprecated). Use the + HistoryPlugin for a history. +* Added a `responseBody` alias for the `response_body` location +* Refactored internals to no longer rely on Response::getRequest() +* HistoryPlugin can now be cast to a string +* HistoryPlugin now logs transactions rather than requests and responses to more accurately keep track of the requests + and responses that are sent over the wire +* Added `getEffectiveUrl()` and `getRedirectCount()` to Response objects + +## 3.4.3 - 2013-04-30 + +* Bug fix: Fixing bug introduced in 3.4.2 where redirect responses are duplicated on the final redirected response +* Added a check to re-extract the temp cacert bundle from the phar before sending each request + +## 3.4.2 - 2013-04-29 + +* Bug fix: Stream objects now work correctly with "a" and "a+" modes +* Bug fix: Removing `Transfer-Encoding: chunked` header when a Content-Length is present +* Bug fix: AsyncPlugin no longer forces HEAD requests +* Bug fix: DateTime timezones are now properly handled when using the service description schema formatter +* Bug fix: CachePlugin now properly handles stale-if-error directives when a request to the origin server fails +* Setting a response on a request will write to the custom request body from the response body if one is specified +* LogPlugin now writes to php://output when STDERR is undefined +* Added the ability to set multiple POST files for the same key in a single call +* application/x-www-form-urlencoded POSTs now use the utf-8 charset by default +* Added the ability to queue CurlExceptions to the MockPlugin +* Cleaned up how manual responses are queued on requests (removed "queued_response" and now using request.before_send) +* Configuration loading now allows remote files + +## 3.4.1 - 2013-04-16 + +* Large refactoring to how CurlMulti handles work. There is now a proxy that sits in front of a pool of CurlMulti + handles. This greatly simplifies the implementation, fixes a couple bugs, and provides a small performance boost. +* Exceptions are now properly grouped when sending requests in parallel +* Redirects are now properly aggregated when a multi transaction fails +* Redirects now set the response on the original object even in the event of a failure +* Bug fix: Model names are now properly set even when using $refs +* Added support for PHP 5.5's CurlFile to prevent warnings with the deprecated @ syntax +* Added support for oauth_callback in OAuth signatures +* Added support for oauth_verifier in OAuth signatures +* Added support to attempt to retrieve a command first literally, then ucfirst, the with inflection + +## 3.4.0 - 2013-04-11 + +* Bug fix: URLs are now resolved correctly based on https://tools.ietf.org/html/rfc3986#section-5.2. #289 +* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289 +* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263 +* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264. +* Bug fix: Added `number` type to service descriptions. +* Bug fix: empty parameters are removed from an OAuth signature +* Bug fix: Revalidating a cache entry prefers the Last-Modified over the Date header +* Bug fix: Fixed "array to string" error when validating a union of types in a service description +* Bug fix: Removed code that attempted to determine the size of a stream when data is written to the stream +* Bug fix: Not including an `oauth_token` if the value is null in the OauthPlugin. +* Bug fix: Now correctly aggregating successful requests and failed requests in CurlMulti when a redirect occurs. +* The new default CURLOPT_TIMEOUT setting has been increased to 150 seconds so that Guzzle works on poor connections. +* Added a feature to EntityEnclosingRequest::setBody() that will automatically set the Content-Type of the request if + the Content-Type can be determined based on the entity body or the path of the request. +* Added the ability to overwrite configuration settings in a client when grabbing a throwaway client from a builder. +* Added support for a PSR-3 LogAdapter. +* Added a `command.after_prepare` event +* Added `oauth_callback` parameter to the OauthPlugin +* Added the ability to create a custom stream class when using a stream factory +* Added a CachingEntityBody decorator +* Added support for `additionalParameters` in service descriptions to define how custom parameters are serialized. +* The bundled SSL certificate is now provided in the phar file and extracted when running Guzzle from a phar. +* You can now send any EntityEnclosingRequest with POST fields or POST files and cURL will handle creating bodies +* POST requests using a custom entity body are now treated exactly like PUT requests but with a custom cURL method. This + means that the redirect behavior of POST requests with custom bodies will not be the same as POST requests that use + POST fields or files (the latter is only used when emulating a form POST in the browser). +* Lots of cleanup to CurlHandle::factory and RequestFactory::createRequest + +## 3.3.1 - 2013-03-10 + +* Added the ability to create PHP streaming responses from HTTP requests +* Bug fix: Running any filters when parsing response headers with service descriptions +* Bug fix: OauthPlugin fixes to allow for multi-dimensional array signing, and sorting parameters before signing +* Bug fix: Removed the adding of default empty arrays and false Booleans to responses in order to be consistent across + response location visitors. +* Bug fix: Removed the possibility of creating configuration files with circular dependencies +* RequestFactory::create() now uses the key of a POST file when setting the POST file name +* Added xmlAllowEmpty to serialize an XML body even if no XML specific parameters are set + +## 3.3.0 - 2013-03-03 + +* A large number of performance optimizations have been made +* Bug fix: Added 'wb' as a valid write mode for streams +* Bug fix: `Guzzle\Http\Message\Response::json()` now allows scalar values to be returned +* Bug fix: Fixed bug in `Guzzle\Http\Message\Response` where wrapping quotes were stripped from `getEtag()` +* BC: Removed `Guzzle\Http\Utils` class +* BC: Setting a service description on a client will no longer modify the client's command factories. +* BC: Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using + the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' +* BC: `Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to + lowercase +* Operation parameter objects are now lazy loaded internally +* Added ErrorResponsePlugin that can throw errors for responses defined in service description operations' errorResponses +* Added support for instantiating responseType=class responseClass classes. Classes must implement + `Guzzle\Service\Command\ResponseClassInterface` +* Added support for additionalProperties for top-level parameters in responseType=model responseClasses. These + additional properties also support locations and can be used to parse JSON responses where the outermost part of the + JSON is an array +* Added support for nested renaming of JSON models (rename sentAs to name) +* CachePlugin + * Added support for stale-if-error so that the CachePlugin can now serve stale content from the cache on error + * Debug headers can now added to cached response in the CachePlugin + +## 3.2.0 - 2013-02-14 + +* CurlMulti is no longer reused globally. A new multi object is created per-client. This helps to isolate clients. +* URLs with no path no longer contain a "/" by default +* Guzzle\Http\QueryString does no longer manages the leading "?". This is now handled in Guzzle\Http\Url. +* BadResponseException no longer includes the full request and response message +* Adding setData() to Guzzle\Service\Description\ServiceDescriptionInterface +* Adding getResponseBody() to Guzzle\Http\Message\RequestInterface +* Various updates to classes to use ServiceDescriptionInterface type hints rather than ServiceDescription +* Header values can now be normalized into distinct values when multiple headers are combined with a comma separated list +* xmlEncoding can now be customized for the XML declaration of a XML service description operation +* Guzzle\Http\QueryString now uses Guzzle\Http\QueryAggregator\QueryAggregatorInterface objects to add custom value + aggregation and no longer uses callbacks +* The URL encoding implementation of Guzzle\Http\QueryString can now be customized +* Bug fix: Filters were not always invoked for array service description parameters +* Bug fix: Redirects now use a target response body rather than a temporary response body +* Bug fix: The default exponential backoff BackoffPlugin was not giving when the request threshold was exceeded +* Bug fix: Guzzle now takes the first found value when grabbing Cache-Control directives + +## 3.1.2 - 2013-01-27 + +* Refactored how operation responses are parsed. Visitors now include a before() method responsible for parsing the + response body. For example, the XmlVisitor now parses the XML response into an array in the before() method. +* Fixed an issue where cURL would not automatically decompress responses when the Accept-Encoding header was sent +* CURLOPT_SSL_VERIFYHOST is never set to 1 because it is deprecated (see 5e0ff2ef20f839e19d1eeb298f90ba3598784444) +* Fixed a bug where redirect responses were not chained correctly using getPreviousResponse() +* Setting default headers on a client after setting the user-agent will not erase the user-agent setting + +## 3.1.1 - 2013-01-20 + +* Adding wildcard support to Guzzle\Common\Collection::getPath() +* Adding alias support to ServiceBuilder configs +* Adding Guzzle\Service\Resource\CompositeResourceIteratorFactory and cleaning up factory interface + +## 3.1.0 - 2013-01-12 + +* BC: CurlException now extends from RequestException rather than BadResponseException +* BC: Renamed Guzzle\Plugin\Cache\CanCacheStrategyInterface::canCache() to canCacheRequest() and added CanCacheResponse() +* Added getData to ServiceDescriptionInterface +* Added context array to RequestInterface::setState() +* Bug: Removing hard dependency on the BackoffPlugin from Guzzle\Http +* Bug: Adding required content-type when JSON request visitor adds JSON to a command +* Bug: Fixing the serialization of a service description with custom data +* Made it easier to deal with exceptions thrown when transferring commands or requests in parallel by providing + an array of successful and failed responses +* Moved getPath from Guzzle\Service\Resource\Model to Guzzle\Common\Collection +* Added Guzzle\Http\IoEmittingEntityBody +* Moved command filtration from validators to location visitors +* Added `extends` attributes to service description parameters +* Added getModels to ServiceDescriptionInterface + +## 3.0.7 - 2012-12-19 + +* Fixing phar detection when forcing a cacert to system if null or true +* Allowing filename to be passed to `Guzzle\Http\Message\Request::setResponseBody()` +* Cleaning up `Guzzle\Common\Collection::inject` method +* Adding a response_body location to service descriptions + +## 3.0.6 - 2012-12-09 + +* CurlMulti performance improvements +* Adding setErrorResponses() to Operation +* composer.json tweaks + +## 3.0.5 - 2012-11-18 + +* Bug: Fixing an infinite recursion bug caused from revalidating with the CachePlugin +* Bug: Response body can now be a string containing "0" +* Bug: Using Guzzle inside of a phar uses system by default but now allows for a custom cacert +* Bug: QueryString::fromString now properly parses query string parameters that contain equal signs +* Added support for XML attributes in service description responses +* DefaultRequestSerializer now supports array URI parameter values for URI template expansion +* Added better mimetype guessing to requests and post files + +## 3.0.4 - 2012-11-11 + +* Bug: Fixed a bug when adding multiple cookies to a request to use the correct glue value +* Bug: Cookies can now be added that have a name, domain, or value set to "0" +* Bug: Using the system cacert bundle when using the Phar +* Added json and xml methods to Response to make it easier to parse JSON and XML response data into data structures +* Enhanced cookie jar de-duplication +* Added the ability to enable strict cookie jars that throw exceptions when invalid cookies are added +* Added setStream to StreamInterface to actually make it possible to implement custom rewind behavior for entity bodies +* Added the ability to create any sort of hash for a stream rather than just an MD5 hash + +## 3.0.3 - 2012-11-04 + +* Implementing redirects in PHP rather than cURL +* Added PECL URI template extension and using as default parser if available +* Bug: Fixed Content-Length parsing of Response factory +* Adding rewind() method to entity bodies and streams. Allows for custom rewinding of non-repeatable streams. +* Adding ToArrayInterface throughout library +* Fixing OauthPlugin to create unique nonce values per request + +## 3.0.2 - 2012-10-25 + +* Magic methods are enabled by default on clients +* Magic methods return the result of a command +* Service clients no longer require a base_url option in the factory +* Bug: Fixed an issue with URI templates where null template variables were being expanded + +## 3.0.1 - 2012-10-22 + +* Models can now be used like regular collection objects by calling filter, map, etc. +* Models no longer require a Parameter structure or initial data in the constructor +* Added a custom AppendIterator to get around a PHP bug with the `\AppendIterator` + +## 3.0.0 - 2012-10-15 + +* Rewrote service description format to be based on Swagger + * Now based on JSON schema + * Added nested input structures and nested response models + * Support for JSON and XML input and output models + * Renamed `commands` to `operations` + * Removed dot class notation + * Removed custom types +* Broke the project into smaller top-level namespaces to be more component friendly +* Removed support for XML configs and descriptions. Use arrays or JSON files. +* Removed the Validation component and Inspector +* Moved all cookie code to Guzzle\Plugin\Cookie +* Magic methods on a Guzzle\Service\Client now return the command un-executed. +* Calling getResult() or getResponse() on a command will lazily execute the command if needed. +* Now shipping with cURL's CA certs and using it by default +* Added previousResponse() method to response objects +* No longer sending Accept and Accept-Encoding headers on every request +* Only sending an Expect header by default when a payload is greater than 1MB +* Added/moved client options: + * curl.blacklist to curl.option.blacklist + * Added ssl.certificate_authority +* Added a Guzzle\Iterator component +* Moved plugins from Guzzle\Http\Plugin to Guzzle\Plugin +* Added a more robust backoff retry strategy (replaced the ExponentialBackoffPlugin) +* Added a more robust caching plugin +* Added setBody to response objects +* Updating LogPlugin to use a more flexible MessageFormatter +* Added a completely revamped build process +* Cleaning up Collection class and removing default values from the get method +* Fixed ZF2 cache adapters + +## 2.8.8 - 2012-10-15 + +* Bug: Fixed a cookie issue that caused dot prefixed domains to not match where popular browsers did + +## 2.8.7 - 2012-09-30 + +* Bug: Fixed config file aliases for JSON includes +* Bug: Fixed cookie bug on a request object by using CookieParser to parse cookies on requests +* Bug: Removing the path to a file when sending a Content-Disposition header on a POST upload +* Bug: Hardening request and response parsing to account for missing parts +* Bug: Fixed PEAR packaging +* Bug: Fixed Request::getInfo +* Bug: Fixed cases where CURLM_CALL_MULTI_PERFORM return codes were causing curl transactions to fail +* Adding the ability for the namespace Iterator factory to look in multiple directories +* Added more getters/setters/removers from service descriptions +* Added the ability to remove POST fields from OAuth signatures +* OAuth plugin now supports 2-legged OAuth + +## 2.8.6 - 2012-09-05 + +* Added the ability to modify and build service descriptions +* Added the use of visitors to apply parameters to locations in service descriptions using the dynamic command +* Added a `json` parameter location +* Now allowing dot notation for classes in the CacheAdapterFactory +* Using the union of two arrays rather than an array_merge when extending service builder services and service params +* Ensuring that a service is a string before doing strpos() checks on it when substituting services for references + in service builder config files. +* Services defined in two different config files that include one another will by default replace the previously + defined service, but you can now create services that extend themselves and merge their settings over the previous +* The JsonLoader now supports aliasing filenames with different filenames. This allows you to alias something like + '_default' with a default JSON configuration file. + +## 2.8.5 - 2012-08-29 + +* Bug: Suppressed empty arrays from URI templates +* Bug: Added the missing $options argument from ServiceDescription::factory to enable caching +* Added support for HTTP responses that do not contain a reason phrase in the start-line +* AbstractCommand commands are now invokable +* Added a way to get the data used when signing an Oauth request before a request is sent + +## 2.8.4 - 2012-08-15 + +* Bug: Custom delay time calculations are no longer ignored in the ExponentialBackoffPlugin +* Added the ability to transfer entity bodies as a string rather than streamed. This gets around curl error 65. Set `body_as_string` in a request's curl options to enable. +* Added a StreamInterface, EntityBodyInterface, and added ftell() to Guzzle\Common\Stream +* Added an AbstractEntityBodyDecorator and a ReadLimitEntityBody decorator to transfer only a subset of a decorated stream +* Stream and EntityBody objects will now return the file position to the previous position after a read required operation (e.g. getContentMd5()) +* Added additional response status codes +* Removed SSL information from the default User-Agent header +* DELETE requests can now send an entity body +* Added an EventDispatcher to the ExponentialBackoffPlugin and added an ExponentialBackoffLogger to log backoff retries +* Added the ability of the MockPlugin to consume mocked request bodies +* LogPlugin now exposes request and response objects in the extras array + +## 2.8.3 - 2012-07-30 + +* Bug: Fixed a case where empty POST requests were sent as GET requests +* Bug: Fixed a bug in ExponentialBackoffPlugin that caused fatal errors when retrying an EntityEnclosingRequest that does not have a body +* Bug: Setting the response body of a request to null after completing a request, not when setting the state of a request to new +* Added multiple inheritance to service description commands +* Added an ApiCommandInterface and added `getParamNames()` and `hasParam()` +* Removed the default 2mb size cutoff from the Md5ValidatorPlugin so that it now defaults to validating everything +* Changed CurlMulti::perform to pass a smaller timeout to CurlMulti::executeHandles + +## 2.8.2 - 2012-07-24 + +* Bug: Query string values set to 0 are no longer dropped from the query string +* Bug: A Collection object is no longer created each time a call is made to `Guzzle\Service\Command\AbstractCommand::getRequestHeaders()` +* Bug: `+` is now treated as an encoded space when parsing query strings +* QueryString and Collection performance improvements +* Allowing dot notation for class paths in filters attribute of a service descriptions + +## 2.8.1 - 2012-07-16 + +* Loosening Event Dispatcher dependency +* POST redirects can now be customized using CURLOPT_POSTREDIR + +## 2.8.0 - 2012-07-15 + +* BC: Guzzle\Http\Query + * Query strings with empty variables will always show an equal sign unless the variable is set to QueryString::BLANK (e.g. ?acl= vs ?acl) + * Changed isEncodingValues() and isEncodingFields() to isUrlEncoding() + * Changed setEncodeValues(bool) and setEncodeFields(bool) to useUrlEncoding(bool) + * Changed the aggregation functions of QueryString to be static methods + * Can now use fromString() with querystrings that have a leading ? +* cURL configuration values can be specified in service descriptions using `curl.` prefixed parameters +* Content-Length is set to 0 before emitting the request.before_send event when sending an empty request body +* Cookies are no longer URL decoded by default +* Bug: URI template variables set to null are no longer expanded + +## 2.7.2 - 2012-07-02 + +* BC: Moving things to get ready for subtree splits. Moving Inflection into Common. Moving Guzzle\Http\Parser to Guzzle\Parser. +* BC: Removing Guzzle\Common\Batch\Batch::count() and replacing it with isEmpty() +* CachePlugin now allows for a custom request parameter function to check if a request can be cached +* Bug fix: CachePlugin now only caches GET and HEAD requests by default +* Bug fix: Using header glue when transferring headers over the wire +* Allowing deeply nested arrays for composite variables in URI templates +* Batch divisors can now return iterators or arrays + +## 2.7.1 - 2012-06-26 + +* Minor patch to update version number in UA string +* Updating build process + +## 2.7.0 - 2012-06-25 + +* BC: Inflection classes moved to Guzzle\Inflection. No longer static methods. Can now inject custom inflectors into classes. +* BC: Removed magic setX methods from commands +* BC: Magic methods mapped to service description commands are now inflected in the command factory rather than the client __call() method +* Verbose cURL options are no longer enabled by default. Set curl.debug to true on a client to enable. +* Bug: Now allowing colons in a response start-line (e.g. HTTP/1.1 503 Service Unavailable: Back-end server is at capacity) +* Guzzle\Service\Resource\ResourceIteratorApplyBatched now internally uses the Guzzle\Common\Batch namespace +* Added Guzzle\Service\Plugin namespace and a PluginCollectionPlugin +* Added the ability to set POST fields and files in a service description +* Guzzle\Http\EntityBody::factory() now accepts objects with a __toString() method +* Adding a command.before_prepare event to clients +* Added BatchClosureTransfer and BatchClosureDivisor +* BatchTransferException now includes references to the batch divisor and transfer strategies +* Fixed some tests so that they pass more reliably +* Added Guzzle\Common\Log\ArrayLogAdapter + +## 2.6.6 - 2012-06-10 + +* BC: Removing Guzzle\Http\Plugin\BatchQueuePlugin +* BC: Removing Guzzle\Service\Command\CommandSet +* Adding generic batching system (replaces the batch queue plugin and command set) +* Updating ZF cache and log adapters and now using ZF's composer repository +* Bug: Setting the name of each ApiParam when creating through an ApiCommand +* Adding result_type, result_doc, deprecated, and doc_url to service descriptions +* Bug: Changed the default cookie header casing back to 'Cookie' + +## 2.6.5 - 2012-06-03 + +* BC: Renaming Guzzle\Http\Message\RequestInterface::getResourceUri() to getResource() +* BC: Removing unused AUTH_BASIC and AUTH_DIGEST constants from +* BC: Guzzle\Http\Cookie is now used to manage Set-Cookie data, not Cookie data +* BC: Renaming methods in the CookieJarInterface +* Moving almost all cookie logic out of the CookiePlugin and into the Cookie or CookieJar implementations +* Making the default glue for HTTP headers ';' instead of ',' +* Adding a removeValue to Guzzle\Http\Message\Header +* Adding getCookies() to request interface. +* Making it easier to add event subscribers to HasDispatcherInterface classes. Can now directly call addSubscriber() + +## 2.6.4 - 2012-05-30 + +* BC: Cleaning up how POST files are stored in EntityEnclosingRequest objects. Adding PostFile class. +* BC: Moving ApiCommand specific functionality from the Inspector and on to the ApiCommand +* Bug: Fixing magic method command calls on clients +* Bug: Email constraint only validates strings +* Bug: Aggregate POST fields when POST files are present in curl handle +* Bug: Fixing default User-Agent header +* Bug: Only appending or prepending parameters in commands if they are specified +* Bug: Not requiring response reason phrases or status codes to match a predefined list of codes +* Allowing the use of dot notation for class namespaces when using instance_of constraint +* Added any_match validation constraint +* Added an AsyncPlugin +* Passing request object to the calculateWait method of the ExponentialBackoffPlugin +* Allowing the result of a command object to be changed +* Parsing location and type sub values when instantiating a service description rather than over and over at runtime + +## 2.6.3 - 2012-05-23 + +* [BC] Guzzle\Common\FromConfigInterface no longer requires any config options. +* [BC] Refactoring how POST files are stored on an EntityEnclosingRequest. They are now separate from POST fields. +* You can now use an array of data when creating PUT request bodies in the request factory. +* Removing the requirement that HTTPS requests needed a Cache-Control: public directive to be cacheable. +* [Http] Adding support for Content-Type in multipart POST uploads per upload +* [Http] Added support for uploading multiple files using the same name (foo[0], foo[1]) +* Adding more POST data operations for easier manipulation of POST data. +* You can now set empty POST fields. +* The body of a request is only shown on EntityEnclosingRequest objects that do not use POST files. +* Split the Guzzle\Service\Inspector::validateConfig method into two methods. One to initialize when a command is created, and one to validate. +* CS updates + +## 2.6.2 - 2012-05-19 + +* [Http] Better handling of nested scope requests in CurlMulti. Requests are now always prepares in the send() method rather than the addRequest() method. + +## 2.6.1 - 2012-05-19 + +* [BC] Removing 'path' support in service descriptions. Use 'uri'. +* [BC] Guzzle\Service\Inspector::parseDocBlock is now protected. Adding getApiParamsForClass() with cache. +* [BC] Removing Guzzle\Common\NullObject. Use https://github.com/mtdowling/NullObject if you need it. +* [BC] Removing Guzzle\Common\XmlElement. +* All commands, both dynamic and concrete, have ApiCommand objects. +* Adding a fix for CurlMulti so that if all of the connections encounter some sort of curl error, then the loop exits. +* Adding checks to EntityEnclosingRequest so that empty POST files and fields are ignored. +* Making the method signature of Guzzle\Service\Builder\ServiceBuilder::factory more flexible. + +## 2.6.0 - 2012-05-15 + +* [BC] Moving Guzzle\Service\Builder to Guzzle\Service\Builder\ServiceBuilder +* [BC] Executing a Command returns the result of the command rather than the command +* [BC] Moving all HTTP parsing logic to Guzzle\Http\Parsers. Allows for faster C implementations if needed. +* [BC] Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. +* [BC] Moving ResourceIterator* to Guzzle\Service\Resource +* [BC] Completely refactored ResourceIterators to iterate over a cloned command object +* [BC] Moved Guzzle\Http\UriTemplate to Guzzle\Http\Parser\UriTemplate\UriTemplate +* [BC] Guzzle\Guzzle is now deprecated +* Moving Guzzle\Common\Guzzle::inject to Guzzle\Common\Collection::inject +* Adding Guzzle\Version class to give version information about Guzzle +* Adding Guzzle\Http\Utils class to provide getDefaultUserAgent() and getHttpDate() +* Adding Guzzle\Curl\CurlVersion to manage caching curl_version() data +* ServiceDescription and ServiceBuilder are now cacheable using similar configs +* Changing the format of XML and JSON service builder configs. Backwards compatible. +* Cleaned up Cookie parsing +* Trimming the default Guzzle User-Agent header +* Adding a setOnComplete() method to Commands that is called when a command completes +* Keeping track of requests that were mocked in the MockPlugin +* Fixed a caching bug in the CacheAdapterFactory +* Inspector objects can be injected into a Command object +* Refactoring a lot of code and tests to be case insensitive when dealing with headers +* Adding Guzzle\Http\Message\HeaderComparison for easy comparison of HTTP headers using a DSL +* Adding the ability to set global option overrides to service builder configs +* Adding the ability to include other service builder config files from within XML and JSON files +* Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. + +## 2.5.0 - 2012-05-08 + +* Major performance improvements +* [BC] Simplifying Guzzle\Common\Collection. Please check to see if you are using features that are now deprecated. +* [BC] Using a custom validation system that allows a flyweight implementation for much faster validation. No longer using Symfony2 Validation component. +* [BC] No longer supporting "{{ }}" for injecting into command or UriTemplates. Use "{}" +* Added the ability to passed parameters to all requests created by a client +* Added callback functionality to the ExponentialBackoffPlugin +* Using microtime in ExponentialBackoffPlugin to allow more granular backoff strategies. +* Rewinding request stream bodies when retrying requests +* Exception is thrown when JSON response body cannot be decoded +* Added configurable magic method calls to clients and commands. This is off by default. +* Fixed a defect that added a hash to every parsed URL part +* Fixed duplicate none generation for OauthPlugin. +* Emitting an event each time a client is generated by a ServiceBuilder +* Using an ApiParams object instead of a Collection for parameters of an ApiCommand +* cache.* request parameters should be renamed to params.cache.* +* Added the ability to set arbitrary curl options on requests (disable_wire, progress, etc.). See CurlHandle. +* Added the ability to disable type validation of service descriptions +* ServiceDescriptions and ServiceBuilders are now Serializable diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/LICENSE b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/LICENSE new file mode 100644 index 0000000..fd2375d --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/LICENSE @@ -0,0 +1,27 @@ +The MIT License (MIT) + +Copyright (c) 2011 Michael Dowling +Copyright (c) 2012 Jeremy Lindblom +Copyright (c) 2014 Graham Campbell +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Tobias Schultze +Copyright (c) 2016 Tobias Nyholm +Copyright (c) 2016 George Mponos + +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/plugins/login-oauth2/vendor/guzzlehttp/guzzle/README.md b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/README.md new file mode 100644 index 0000000..f287fa9 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/README.md @@ -0,0 +1,94 @@ +![Guzzle](.github/logo.png?raw=true) + +# Guzzle, PHP HTTP client + +[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases) +[![Build Status](https://img.shields.io/github/workflow/status/guzzle/guzzle/CI?label=ci%20build&style=flat-square)](https://github.com/guzzle/guzzle/actions?query=workflow%3ACI) +[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle) + +Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and +trivial to integrate with web services. + +- Simple interface for building query strings, POST requests, streaming large + uploads, streaming large downloads, using HTTP cookies, uploading JSON data, + etc... +- Can send both synchronous and asynchronous requests using the same interface. +- Uses PSR-7 interfaces for requests, responses, and streams. This allows you + to utilize other PSR-7 compatible libraries with Guzzle. +- Supports PSR-18 allowing interoperability between other PSR-18 HTTP Clients. +- Abstracts away the underlying HTTP transport, allowing you to write + environment and transport agnostic code; i.e., no hard dependency on cURL, + PHP streams, sockets, or non-blocking event loops. +- Middleware system allows you to augment and compose client behavior. + +```php +$client = new \GuzzleHttp\Client(); +$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle'); + +echo $response->getStatusCode(); // 200 +echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8' +echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}' + +// Send an asynchronous request. +$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); +$promise = $client->sendAsync($request)->then(function ($response) { + echo 'I completed! ' . $response->getBody(); +}); + +$promise->wait(); +``` + +## Help and docs + +We use GitHub issues only to discuss bugs and new features. For support please refer to: + +- [Documentation](https://docs.guzzlephp.org) +- [Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle) +- [#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on [PHP-HTTP Slack](https://slack.httplug.io/) +- [Gitter](https://gitter.im/guzzle/guzzle) + + +## Installing Guzzle + +The recommended way to install Guzzle is through +[Composer](https://getcomposer.org/). + +```bash +composer require guzzlehttp/guzzle +``` + + +## Version Guidance + +| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version | +|---------|----------------|---------------------|--------------|---------------------|---------------------|-------|--------------| +| 3.x | EOL | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >=5.3.3,<7.0 | +| 4.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >=5.4,<7.0 | +| 5.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >=5.4,<7.4 | +| 6.x | Security fixes | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >=5.5,<8.0 | +| 7.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v7][guzzle-7-repo] | [v7][guzzle-7-docs] | Yes | >=7.2.5,<8.2 | + +[guzzle-3-repo]: https://github.com/guzzle/guzzle3 +[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x +[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3 +[guzzle-6-repo]: https://github.com/guzzle/guzzle/tree/6.5 +[guzzle-7-repo]: https://github.com/guzzle/guzzle +[guzzle-3-docs]: https://guzzle3.readthedocs.io/ +[guzzle-5-docs]: https://docs.guzzlephp.org/en/5.3/ +[guzzle-6-docs]: https://docs.guzzlephp.org/en/6.5/ +[guzzle-7-docs]: https://docs.guzzlephp.org/en/latest/ + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/guzzle/security/policy) for more information. + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-guzzle?utm_source=packagist-guzzlehttp-guzzle&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/UPGRADING.md b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/UPGRADING.md new file mode 100644 index 0000000..45417a7 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/UPGRADING.md @@ -0,0 +1,1253 @@ +Guzzle Upgrade Guide +==================== + +6.0 to 7.0 +---------- + +In order to take advantage of the new features of PHP, Guzzle dropped the support +of PHP 5. The minimum supported PHP version is now PHP 7.2. Type hints and return +types for functions and methods have been added wherever possible. + +Please make sure: +- You are calling a function or a method with the correct type. +- If you extend a class of Guzzle; update all signatures on methods you override. + +#### Other backwards compatibility breaking changes + +- Class `GuzzleHttp\UriTemplate` is removed. +- Class `GuzzleHttp\Exception\SeekException` is removed. +- Classes `GuzzleHttp\Exception\BadResponseException`, `GuzzleHttp\Exception\ClientException`, + `GuzzleHttp\Exception\ServerException` can no longer be initialized with an empty + Response as argument. +- Class `GuzzleHttp\Exception\ConnectException` now extends `GuzzleHttp\Exception\TransferException` + instead of `GuzzleHttp\Exception\RequestException`. +- Function `GuzzleHttp\Exception\ConnectException::getResponse()` is removed. +- Function `GuzzleHttp\Exception\ConnectException::hasResponse()` is removed. +- Constant `GuzzleHttp\ClientInterface::VERSION` is removed. Added `GuzzleHttp\ClientInterface::MAJOR_VERSION` instead. +- Function `GuzzleHttp\Exception\RequestException::getResponseBodySummary` is removed. + Use `\GuzzleHttp\Psr7\get_message_body_summary` as an alternative. +- Function `GuzzleHttp\Cookie\CookieJar::getCookieValue` is removed. +- Request option `exception` is removed. Please use `http_errors`. +- Request option `save_to` is removed. Please use `sink`. +- Pool option `pool_size` is removed. Please use `concurrency`. +- We now look for environment variables in the `$_SERVER` super global, due to thread safety issues with `getenv`. We continue to fallback to `getenv` in CLI environments, for maximum compatibility. +- The `get`, `head`, `put`, `post`, `patch`, `delete`, `getAsync`, `headAsync`, `putAsync`, `postAsync`, `patchAsync`, and `deleteAsync` methods are now implemented as genuine methods on `GuzzleHttp\Client`, with strong typing. The original `__call` implementation remains unchanged for now, for maximum backwards compatibility, but won't be invoked under normal operation. +- The `log` middleware will log the errors with level `error` instead of `notice` +- Support for international domain names (IDN) is now disabled by default, and enabling it requires installing ext-intl, linked against a modern version of the C library (ICU 4.6 or higher). + +#### Native functions calls + +All internal native functions calls of Guzzle are now prefixed with a slash. This +change makes it impossible for method overloading by other libraries or applications. +Example: + +```php +// Before: +curl_version(); + +// After: +\curl_version(); +``` + +For the full diff you can check [here](https://github.com/guzzle/guzzle/compare/6.5.4..master). + +5.0 to 6.0 +---------- + +Guzzle now uses [PSR-7](https://www.php-fig.org/psr/psr-7/) for HTTP messages. +Due to the fact that these messages are immutable, this prompted a refactoring +of Guzzle to use a middleware based system rather than an event system. Any +HTTP message interaction (e.g., `GuzzleHttp\Message\Request`) need to be +updated to work with the new immutable PSR-7 request and response objects. Any +event listeners or subscribers need to be updated to become middleware +functions that wrap handlers (or are injected into a +`GuzzleHttp\HandlerStack`). + +- Removed `GuzzleHttp\BatchResults` +- Removed `GuzzleHttp\Collection` +- Removed `GuzzleHttp\HasDataTrait` +- Removed `GuzzleHttp\ToArrayInterface` +- The `guzzlehttp/streams` dependency has been removed. Stream functionality + is now present in the `GuzzleHttp\Psr7` namespace provided by the + `guzzlehttp/psr7` package. +- Guzzle no longer uses ReactPHP promises and now uses the + `guzzlehttp/promises` library. We use a custom promise library for three + significant reasons: + 1. React promises (at the time of writing this) are recursive. Promise + chaining and promise resolution will eventually blow the stack. Guzzle + promises are not recursive as they use a sort of trampolining technique. + Note: there has been movement in the React project to modify promises to + no longer utilize recursion. + 2. Guzzle needs to have the ability to synchronously block on a promise to + wait for a result. Guzzle promises allows this functionality (and does + not require the use of recursion). + 3. Because we need to be able to wait on a result, doing so using React + promises requires wrapping react promises with RingPHP futures. This + overhead is no longer needed, reducing stack sizes, reducing complexity, + and improving performance. +- `GuzzleHttp\Mimetypes` has been moved to a function in + `GuzzleHttp\Psr7\mimetype_from_extension` and + `GuzzleHttp\Psr7\mimetype_from_filename`. +- `GuzzleHttp\Query` and `GuzzleHttp\QueryParser` have been removed. Query + strings must now be passed into request objects as strings, or provided to + the `query` request option when creating requests with clients. The `query` + option uses PHP's `http_build_query` to convert an array to a string. If you + need a different serialization technique, you will need to pass the query + string in as a string. There are a couple helper functions that will make + working with query strings easier: `GuzzleHttp\Psr7\parse_query` and + `GuzzleHttp\Psr7\build_query`. +- Guzzle no longer has a dependency on RingPHP. Due to the use of a middleware + system based on PSR-7, using RingPHP and it's middleware system as well adds + more complexity than the benefits it provides. All HTTP handlers that were + present in RingPHP have been modified to work directly with PSR-7 messages + and placed in the `GuzzleHttp\Handler` namespace. This significantly reduces + complexity in Guzzle, removes a dependency, and improves performance. RingPHP + will be maintained for Guzzle 5 support, but will no longer be a part of + Guzzle 6. +- As Guzzle now uses a middleware based systems the event system and RingPHP + integration has been removed. Note: while the event system has been removed, + it is possible to add your own type of event system that is powered by the + middleware system. + - Removed the `Event` namespace. + - Removed the `Subscriber` namespace. + - Removed `Transaction` class + - Removed `RequestFsm` + - Removed `RingBridge` + - `GuzzleHttp\Subscriber\Cookie` is now provided by + `GuzzleHttp\Middleware::cookies` + - `GuzzleHttp\Subscriber\HttpError` is now provided by + `GuzzleHttp\Middleware::httpError` + - `GuzzleHttp\Subscriber\History` is now provided by + `GuzzleHttp\Middleware::history` + - `GuzzleHttp\Subscriber\Mock` is now provided by + `GuzzleHttp\Handler\MockHandler` + - `GuzzleHttp\Subscriber\Prepare` is now provided by + `GuzzleHttp\PrepareBodyMiddleware` + - `GuzzleHttp\Subscriber\Redirect` is now provided by + `GuzzleHttp\RedirectMiddleware` +- Guzzle now uses `Psr\Http\Message\UriInterface` (implements in + `GuzzleHttp\Psr7\Uri`) for URI support. `GuzzleHttp\Url` is now gone. +- Static functions in `GuzzleHttp\Utils` have been moved to namespaced + functions under the `GuzzleHttp` namespace. This requires either a Composer + based autoloader or you to include functions.php. +- `GuzzleHttp\ClientInterface::getDefaultOption` has been renamed to + `GuzzleHttp\ClientInterface::getConfig`. +- `GuzzleHttp\ClientInterface::setDefaultOption` has been removed. +- The `json` and `xml` methods of response objects has been removed. With the + migration to strictly adhering to PSR-7 as the interface for Guzzle messages, + adding methods to message interfaces would actually require Guzzle messages + to extend from PSR-7 messages rather then work with them directly. + +## Migrating to middleware + +The change to PSR-7 unfortunately required significant refactoring to Guzzle +due to the fact that PSR-7 messages are immutable. Guzzle 5 relied on an event +system from plugins. The event system relied on mutability of HTTP messages and +side effects in order to work. With immutable messages, you have to change your +workflow to become more about either returning a value (e.g., functional +middlewares) or setting a value on an object. Guzzle v6 has chosen the +functional middleware approach. + +Instead of using the event system to listen for things like the `before` event, +you now create a stack based middleware function that intercepts a request on +the way in and the promise of the response on the way out. This is a much +simpler and more predictable approach than the event system and works nicely +with PSR-7 middleware. Due to the use of promises, the middleware system is +also asynchronous. + +v5: + +```php +use GuzzleHttp\Event\BeforeEvent; +$client = new GuzzleHttp\Client(); +// Get the emitter and listen to the before event. +$client->getEmitter()->on('before', function (BeforeEvent $e) { + // Guzzle v5 events relied on mutation + $e->getRequest()->setHeader('X-Foo', 'Bar'); +}); +``` + +v6: + +In v6, you can modify the request before it is sent using the `mapRequest` +middleware. The idiomatic way in v6 to modify the request/response lifecycle is +to setup a handler middleware stack up front and inject the handler into a +client. + +```php +use GuzzleHttp\Middleware; +// Create a handler stack that has all of the default middlewares attached +$handler = GuzzleHttp\HandlerStack::create(); +// Push the handler onto the handler stack +$handler->push(Middleware::mapRequest(function (RequestInterface $request) { + // Notice that we have to return a request object + return $request->withHeader('X-Foo', 'Bar'); +})); +// Inject the handler into the client +$client = new GuzzleHttp\Client(['handler' => $handler]); +``` + +## POST Requests + +This version added the [`form_params`](http://guzzle.readthedocs.org/en/latest/request-options.html#form_params) +and `multipart` request options. `form_params` is an associative array of +strings or array of strings and is used to serialize an +`application/x-www-form-urlencoded` POST request. The +[`multipart`](http://guzzle.readthedocs.org/en/latest/request-options.html#multipart) +option is now used to send a multipart/form-data POST request. + +`GuzzleHttp\Post\PostFile` has been removed. Use the `multipart` option to add +POST files to a multipart/form-data request. + +The `body` option no longer accepts an array to send POST requests. Please use +`multipart` or `form_params` instead. + +The `base_url` option has been renamed to `base_uri`. + +4.x to 5.0 +---------- + +## Rewritten Adapter Layer + +Guzzle now uses [RingPHP](http://ringphp.readthedocs.org/en/latest) to send +HTTP requests. The `adapter` option in a `GuzzleHttp\Client` constructor +is still supported, but it has now been renamed to `handler`. Instead of +passing a `GuzzleHttp\Adapter\AdapterInterface`, you must now pass a PHP +`callable` that follows the RingPHP specification. + +## Removed Fluent Interfaces + +[Fluent interfaces were removed](https://ocramius.github.io/blog/fluent-interfaces-are-evil/) +from the following classes: + +- `GuzzleHttp\Collection` +- `GuzzleHttp\Url` +- `GuzzleHttp\Query` +- `GuzzleHttp\Post\PostBody` +- `GuzzleHttp\Cookie\SetCookie` + +## Removed functions.php + +Removed "functions.php", so that Guzzle is truly PSR-4 compliant. The following +functions can be used as replacements. + +- `GuzzleHttp\json_decode` -> `GuzzleHttp\Utils::jsonDecode` +- `GuzzleHttp\get_path` -> `GuzzleHttp\Utils::getPath` +- `GuzzleHttp\Utils::setPath` -> `GuzzleHttp\set_path` +- `GuzzleHttp\Pool::batch` -> `GuzzleHttp\batch`. This function is, however, + deprecated in favor of using `GuzzleHttp\Pool::batch()`. + +The "procedural" global client has been removed with no replacement (e.g., +`GuzzleHttp\get()`, `GuzzleHttp\post()`, etc.). Use a `GuzzleHttp\Client` +object as a replacement. + +## `throwImmediately` has been removed + +The concept of "throwImmediately" has been removed from exceptions and error +events. This control mechanism was used to stop a transfer of concurrent +requests from completing. This can now be handled by throwing the exception or +by cancelling a pool of requests or each outstanding future request +individually. + +## headers event has been removed + +Removed the "headers" event. This event was only useful for changing the +body a response once the headers of the response were known. You can implement +a similar behavior in a number of ways. One example might be to use a +FnStream that has access to the transaction being sent. For example, when the +first byte is written, you could check if the response headers match your +expectations, and if so, change the actual stream body that is being +written to. + +## Updates to HTTP Messages + +Removed the `asArray` parameter from +`GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header +value as an array, then use the newly added `getHeaderAsArray()` method of +`MessageInterface`. This change makes the Guzzle interfaces compatible with +the PSR-7 interfaces. + +3.x to 4.0 +---------- + +## Overarching changes: + +- Now requires PHP 5.4 or greater. +- No longer requires cURL to send requests. +- Guzzle no longer wraps every exception it throws. Only exceptions that are + recoverable are now wrapped by Guzzle. +- Various namespaces have been removed or renamed. +- No longer requiring the Symfony EventDispatcher. A custom event dispatcher + based on the Symfony EventDispatcher is + now utilized in `GuzzleHttp\Event\EmitterInterface` (resulting in significant + speed and functionality improvements). + +Changes per Guzzle 3.x namespace are described below. + +## Batch + +The `Guzzle\Batch` namespace has been removed. This is best left to +third-parties to implement on top of Guzzle's core HTTP library. + +## Cache + +The `Guzzle\Cache` namespace has been removed. (Todo: No suitable replacement +has been implemented yet, but hoping to utilize a PSR cache interface). + +## Common + +- Removed all of the wrapped exceptions. It's better to use the standard PHP + library for unrecoverable exceptions. +- `FromConfigInterface` has been removed. +- `Guzzle\Common\Version` has been removed. The VERSION constant can be found + at `GuzzleHttp\ClientInterface::VERSION`. + +### Collection + +- `getAll` has been removed. Use `toArray` to convert a collection to an array. +- `inject` has been removed. +- `keySearch` has been removed. +- `getPath` no longer supports wildcard expressions. Use something better like + JMESPath for this. +- `setPath` now supports appending to an existing array via the `[]` notation. + +### Events + +Guzzle no longer requires Symfony's EventDispatcher component. Guzzle now uses +`GuzzleHttp\Event\Emitter`. + +- `Symfony\Component\EventDispatcher\EventDispatcherInterface` is replaced by + `GuzzleHttp\Event\EmitterInterface`. +- `Symfony\Component\EventDispatcher\EventDispatcher` is replaced by + `GuzzleHttp\Event\Emitter`. +- `Symfony\Component\EventDispatcher\Event` is replaced by + `GuzzleHttp\Event\Event`, and Guzzle now has an EventInterface in + `GuzzleHttp\Event\EventInterface`. +- `AbstractHasDispatcher` has moved to a trait, `HasEmitterTrait`, and + `HasDispatcherInterface` has moved to `HasEmitterInterface`. Retrieving the + event emitter of a request, client, etc. now uses the `getEmitter` method + rather than the `getDispatcher` method. + +#### Emitter + +- Use the `once()` method to add a listener that automatically removes itself + the first time it is invoked. +- Use the `listeners()` method to retrieve a list of event listeners rather than + the `getListeners()` method. +- Use `emit()` instead of `dispatch()` to emit an event from an emitter. +- Use `attach()` instead of `addSubscriber()` and `detach()` instead of + `removeSubscriber()`. + +```php +$mock = new Mock(); +// 3.x +$request->getEventDispatcher()->addSubscriber($mock); +$request->getEventDispatcher()->removeSubscriber($mock); +// 4.x +$request->getEmitter()->attach($mock); +$request->getEmitter()->detach($mock); +``` + +Use the `on()` method to add a listener rather than the `addListener()` method. + +```php +// 3.x +$request->getEventDispatcher()->addListener('foo', function (Event $event) { /* ... */ } ); +// 4.x +$request->getEmitter()->on('foo', function (Event $event, $name) { /* ... */ } ); +``` + +## Http + +### General changes + +- The cacert.pem certificate has been moved to `src/cacert.pem`. +- Added the concept of adapters that are used to transfer requests over the + wire. +- Simplified the event system. +- Sending requests in parallel is still possible, but batching is no longer a + concept of the HTTP layer. Instead, you must use the `complete` and `error` + events to asynchronously manage parallel request transfers. +- `Guzzle\Http\Url` has moved to `GuzzleHttp\Url`. +- `Guzzle\Http\QueryString` has moved to `GuzzleHttp\Query`. +- QueryAggregators have been rewritten so that they are simply callable + functions. +- `GuzzleHttp\StaticClient` has been removed. Use the functions provided in + `functions.php` for an easy to use static client instance. +- Exceptions in `GuzzleHttp\Exception` have been updated to all extend from + `GuzzleHttp\Exception\TransferException`. + +### Client + +Calling methods like `get()`, `post()`, `head()`, etc. no longer create and +return a request, but rather creates a request, sends the request, and returns +the response. + +```php +// 3.0 +$request = $client->get('/'); +$response = $request->send(); + +// 4.0 +$response = $client->get('/'); + +// or, to mirror the previous behavior +$request = $client->createRequest('GET', '/'); +$response = $client->send($request); +``` + +`GuzzleHttp\ClientInterface` has changed. + +- The `send` method no longer accepts more than one request. Use `sendAll` to + send multiple requests in parallel. +- `setUserAgent()` has been removed. Use a default request option instead. You + could, for example, do something like: + `$client->setConfig('defaults/headers/User-Agent', 'Foo/Bar ' . $client::getDefaultUserAgent())`. +- `setSslVerification()` has been removed. Use default request options instead, + like `$client->setConfig('defaults/verify', true)`. + +`GuzzleHttp\Client` has changed. + +- The constructor now accepts only an associative array. You can include a + `base_url` string or array to use a URI template as the base URL of a client. + You can also specify a `defaults` key that is an associative array of default + request options. You can pass an `adapter` to use a custom adapter, + `batch_adapter` to use a custom adapter for sending requests in parallel, or + a `message_factory` to change the factory used to create HTTP requests and + responses. +- The client no longer emits a `client.create_request` event. +- Creating requests with a client no longer automatically utilize a URI + template. You must pass an array into a creational method (e.g., + `createRequest`, `get`, `put`, etc.) in order to expand a URI template. + +### Messages + +Messages no longer have references to their counterparts (i.e., a request no +longer has a reference to it's response, and a response no loger has a +reference to its request). This association is now managed through a +`GuzzleHttp\Adapter\TransactionInterface` object. You can get references to +these transaction objects using request events that are emitted over the +lifecycle of a request. + +#### Requests with a body + +- `GuzzleHttp\Message\EntityEnclosingRequest` and + `GuzzleHttp\Message\EntityEnclosingRequestInterface` have been removed. The + separation between requests that contain a body and requests that do not + contain a body has been removed, and now `GuzzleHttp\Message\RequestInterface` + handles both use cases. +- Any method that previously accepts a `GuzzleHttp\Response` object now accept a + `GuzzleHttp\Message\ResponseInterface`. +- `GuzzleHttp\Message\RequestFactoryInterface` has been renamed to + `GuzzleHttp\Message\MessageFactoryInterface`. This interface is used to create + both requests and responses and is implemented in + `GuzzleHttp\Message\MessageFactory`. +- POST field and file methods have been removed from the request object. You + must now use the methods made available to `GuzzleHttp\Post\PostBodyInterface` + to control the format of a POST body. Requests that are created using a + standard `GuzzleHttp\Message\MessageFactoryInterface` will automatically use + a `GuzzleHttp\Post\PostBody` body if the body was passed as an array or if + the method is POST and no body is provided. + +```php +$request = $client->createRequest('POST', '/'); +$request->getBody()->setField('foo', 'bar'); +$request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r'))); +``` + +#### Headers + +- `GuzzleHttp\Message\Header` has been removed. Header values are now simply + represented by an array of values or as a string. Header values are returned + as a string by default when retrieving a header value from a message. You can + pass an optional argument of `true` to retrieve a header value as an array + of strings instead of a single concatenated string. +- `GuzzleHttp\PostFile` and `GuzzleHttp\PostFileInterface` have been moved to + `GuzzleHttp\Post`. This interface has been simplified and now allows the + addition of arbitrary headers. +- Custom headers like `GuzzleHttp\Message\Header\Link` have been removed. Most + of the custom headers are now handled separately in specific + subscribers/plugins, and `GuzzleHttp\Message\HeaderValues::parseParams()` has + been updated to properly handle headers that contain parameters (like the + `Link` header). + +#### Responses + +- `GuzzleHttp\Message\Response::getInfo()` and + `GuzzleHttp\Message\Response::setInfo()` have been removed. Use the event + system to retrieve this type of information. +- `GuzzleHttp\Message\Response::getRawHeaders()` has been removed. +- `GuzzleHttp\Message\Response::getMessage()` has been removed. +- `GuzzleHttp\Message\Response::calculateAge()` and other cache specific + methods have moved to the CacheSubscriber. +- Header specific helper functions like `getContentMd5()` have been removed. + Just use `getHeader('Content-MD5')` instead. +- `GuzzleHttp\Message\Response::setRequest()` and + `GuzzleHttp\Message\Response::getRequest()` have been removed. Use the event + system to work with request and response objects as a transaction. +- `GuzzleHttp\Message\Response::getRedirectCount()` has been removed. Use the + Redirect subscriber instead. +- `GuzzleHttp\Message\Response::isSuccessful()` and other related methods have + been removed. Use `getStatusCode()` instead. + +#### Streaming responses + +Streaming requests can now be created by a client directly, returning a +`GuzzleHttp\Message\ResponseInterface` object that contains a body stream +referencing an open PHP HTTP stream. + +```php +// 3.0 +use Guzzle\Stream\PhpStreamRequestFactory; +$request = $client->get('/'); +$factory = new PhpStreamRequestFactory(); +$stream = $factory->fromRequest($request); +$data = $stream->read(1024); + +// 4.0 +$response = $client->get('/', ['stream' => true]); +// Read some data off of the stream in the response body +$data = $response->getBody()->read(1024); +``` + +#### Redirects + +The `configureRedirects()` method has been removed in favor of a +`allow_redirects` request option. + +```php +// Standard redirects with a default of a max of 5 redirects +$request = $client->createRequest('GET', '/', ['allow_redirects' => true]); + +// Strict redirects with a custom number of redirects +$request = $client->createRequest('GET', '/', [ + 'allow_redirects' => ['max' => 5, 'strict' => true] +]); +``` + +#### EntityBody + +EntityBody interfaces and classes have been removed or moved to +`GuzzleHttp\Stream`. All classes and interfaces that once required +`GuzzleHttp\EntityBodyInterface` now require +`GuzzleHttp\Stream\StreamInterface`. Creating a new body for a request no +longer uses `GuzzleHttp\EntityBody::factory` but now uses +`GuzzleHttp\Stream\Stream::factory` or even better: +`GuzzleHttp\Stream\create()`. + +- `Guzzle\Http\EntityBodyInterface` is now `GuzzleHttp\Stream\StreamInterface` +- `Guzzle\Http\EntityBody` is now `GuzzleHttp\Stream\Stream` +- `Guzzle\Http\CachingEntityBody` is now `GuzzleHttp\Stream\CachingStream` +- `Guzzle\Http\ReadLimitEntityBody` is now `GuzzleHttp\Stream\LimitStream` +- `Guzzle\Http\IoEmittyinEntityBody` has been removed. + +#### Request lifecycle events + +Requests previously submitted a large number of requests. The number of events +emitted over the lifecycle of a request has been significantly reduced to make +it easier to understand how to extend the behavior of a request. All events +emitted during the lifecycle of a request now emit a custom +`GuzzleHttp\Event\EventInterface` object that contains context providing +methods and a way in which to modify the transaction at that specific point in +time (e.g., intercept the request and set a response on the transaction). + +- `request.before_send` has been renamed to `before` and now emits a + `GuzzleHttp\Event\BeforeEvent` +- `request.complete` has been renamed to `complete` and now emits a + `GuzzleHttp\Event\CompleteEvent`. +- `request.sent` has been removed. Use `complete`. +- `request.success` has been removed. Use `complete`. +- `error` is now an event that emits a `GuzzleHttp\Event\ErrorEvent`. +- `request.exception` has been removed. Use `error`. +- `request.receive.status_line` has been removed. +- `curl.callback.progress` has been removed. Use a custom `StreamInterface` to + maintain a status update. +- `curl.callback.write` has been removed. Use a custom `StreamInterface` to + intercept writes. +- `curl.callback.read` has been removed. Use a custom `StreamInterface` to + intercept reads. + +`headers` is a new event that is emitted after the response headers of a +request have been received before the body of the response is downloaded. This +event emits a `GuzzleHttp\Event\HeadersEvent`. + +You can intercept a request and inject a response using the `intercept()` event +of a `GuzzleHttp\Event\BeforeEvent`, `GuzzleHttp\Event\CompleteEvent`, and +`GuzzleHttp\Event\ErrorEvent` event. + +See: http://docs.guzzlephp.org/en/latest/events.html + +## Inflection + +The `Guzzle\Inflection` namespace has been removed. This is not a core concern +of Guzzle. + +## Iterator + +The `Guzzle\Iterator` namespace has been removed. + +- `Guzzle\Iterator\AppendIterator`, `Guzzle\Iterator\ChunkedIterator`, and + `Guzzle\Iterator\MethodProxyIterator` are nice, but not a core requirement of + Guzzle itself. +- `Guzzle\Iterator\FilterIterator` is no longer needed because an equivalent + class is shipped with PHP 5.4. +- `Guzzle\Iterator\MapIterator` is not really needed when using PHP 5.5 because + it's easier to just wrap an iterator in a generator that maps values. + +For a replacement of these iterators, see https://github.com/nikic/iter + +## Log + +The LogPlugin has moved to https://github.com/guzzle/log-subscriber. The +`Guzzle\Log` namespace has been removed. Guzzle now relies on +`Psr\Log\LoggerInterface` for all logging. The MessageFormatter class has been +moved to `GuzzleHttp\Subscriber\Log\Formatter`. + +## Parser + +The `Guzzle\Parser` namespace has been removed. This was previously used to +make it possible to plug in custom parsers for cookies, messages, URI +templates, and URLs; however, this level of complexity is not needed in Guzzle +so it has been removed. + +- Cookie: Cookie parsing logic has been moved to + `GuzzleHttp\Cookie\SetCookie::fromString`. +- Message: Message parsing logic for both requests and responses has been moved + to `GuzzleHttp\Message\MessageFactory::fromMessage`. Message parsing is only + used in debugging or deserializing messages, so it doesn't make sense for + Guzzle as a library to add this level of complexity to parsing messages. +- UriTemplate: URI template parsing has been moved to + `GuzzleHttp\UriTemplate`. The Guzzle library will automatically use the PECL + URI template library if it is installed. +- Url: URL parsing is now performed in `GuzzleHttp\Url::fromString` (previously + it was `Guzzle\Http\Url::factory()`). If custom URL parsing is necessary, + then developers are free to subclass `GuzzleHttp\Url`. + +## Plugin + +The `Guzzle\Plugin` namespace has been renamed to `GuzzleHttp\Subscriber`. +Several plugins are shipping with the core Guzzle library under this namespace. + +- `GuzzleHttp\Subscriber\Cookie`: Replaces the old CookiePlugin. Cookie jar + code has moved to `GuzzleHttp\Cookie`. +- `GuzzleHttp\Subscriber\History`: Replaces the old HistoryPlugin. +- `GuzzleHttp\Subscriber\HttpError`: Throws errors when a bad HTTP response is + received. +- `GuzzleHttp\Subscriber\Mock`: Replaces the old MockPlugin. +- `GuzzleHttp\Subscriber\Prepare`: Prepares the body of a request just before + sending. This subscriber is attached to all requests by default. +- `GuzzleHttp\Subscriber\Redirect`: Replaces the RedirectPlugin. + +The following plugins have been removed (third-parties are free to re-implement +these if needed): + +- `GuzzleHttp\Plugin\Async` has been removed. +- `GuzzleHttp\Plugin\CurlAuth` has been removed. +- `GuzzleHttp\Plugin\ErrorResponse\ErrorResponsePlugin` has been removed. This + functionality should instead be implemented with event listeners that occur + after normal response parsing occurs in the guzzle/command package. + +The following plugins are not part of the core Guzzle package, but are provided +in separate repositories: + +- `Guzzle\Http\Plugin\BackoffPlugin` has been rewritten to be much simpler + to build custom retry policies using simple functions rather than various + chained classes. See: https://github.com/guzzle/retry-subscriber +- `Guzzle\Http\Plugin\Cache\CachePlugin` has moved to + https://github.com/guzzle/cache-subscriber +- `Guzzle\Http\Plugin\Log\LogPlugin` has moved to + https://github.com/guzzle/log-subscriber +- `Guzzle\Http\Plugin\Md5\Md5Plugin` has moved to + https://github.com/guzzle/message-integrity-subscriber +- `Guzzle\Http\Plugin\Mock\MockPlugin` has moved to + `GuzzleHttp\Subscriber\MockSubscriber`. +- `Guzzle\Http\Plugin\Oauth\OauthPlugin` has moved to + https://github.com/guzzle/oauth-subscriber + +## Service + +The service description layer of Guzzle has moved into two separate packages: + +- http://github.com/guzzle/command Provides a high level abstraction over web + services by representing web service operations using commands. +- http://github.com/guzzle/guzzle-services Provides an implementation of + guzzle/command that provides request serialization and response parsing using + Guzzle service descriptions. + +## Stream + +Stream have moved to a separate package available at +https://github.com/guzzle/streams. + +`Guzzle\Stream\StreamInterface` has been given a large update to cleanly take +on the responsibilities of `Guzzle\Http\EntityBody` and +`Guzzle\Http\EntityBodyInterface` now that they have been removed. The number +of methods implemented by the `StreamInterface` has been drastically reduced to +allow developers to more easily extend and decorate stream behavior. + +## Removed methods from StreamInterface + +- `getStream` and `setStream` have been removed to better encapsulate streams. +- `getMetadata` and `setMetadata` have been removed in favor of + `GuzzleHttp\Stream\MetadataStreamInterface`. +- `getWrapper`, `getWrapperData`, `getStreamType`, and `getUri` have all been + removed. This data is accessible when + using streams that implement `GuzzleHttp\Stream\MetadataStreamInterface`. +- `rewind` has been removed. Use `seek(0)` for a similar behavior. + +## Renamed methods + +- `detachStream` has been renamed to `detach`. +- `feof` has been renamed to `eof`. +- `ftell` has been renamed to `tell`. +- `readLine` has moved from an instance method to a static class method of + `GuzzleHttp\Stream\Stream`. + +## Metadata streams + +`GuzzleHttp\Stream\MetadataStreamInterface` has been added to denote streams +that contain additional metadata accessible via `getMetadata()`. +`GuzzleHttp\Stream\StreamInterface::getMetadata` and +`GuzzleHttp\Stream\StreamInterface::setMetadata` have been removed. + +## StreamRequestFactory + +The entire concept of the StreamRequestFactory has been removed. The way this +was used in Guzzle 3 broke the actual interface of sending streaming requests +(instead of getting back a Response, you got a StreamInterface). Streaming +PHP requests are now implemented through the `GuzzleHttp\Adapter\StreamAdapter`. + +3.6 to 3.7 +---------- + +### Deprecations + +- You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.: + +```php +\Guzzle\Common\Version::$emitWarnings = true; +``` + +The following APIs and options have been marked as deprecated: + +- Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use `$request->getResponseBody()->isRepeatable()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +- Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +- Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +- Marked `Guzzle\Common\Collection::inject()` as deprecated. +- Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use + `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` or + `$client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` + +3.7 introduces `request.options` as a parameter for a client configuration and as an optional argument to all creational +request methods. When paired with a client's configuration settings, these options allow you to specify default settings +for various aspects of a request. Because these options make other previous configuration options redundant, several +configuration options and methods of a client and AbstractCommand have been deprecated. + +- Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use `$client->getDefaultOption('headers')`. +- Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->setDefaultOption('headers/{header_name}', 'value')`. +- Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use `$client->setDefaultOption('params/{param_name}', 'value')` +- Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0 + + $command = $client->getCommand('foo', array( + 'command.headers' => array('Test' => '123'), + 'command.response_body' => '/path/to/file' + )); + + // Should be changed to: + + $command = $client->getCommand('foo', array( + 'command.request_options' => array( + 'headers' => array('Test' => '123'), + 'save_as' => '/path/to/file' + ) + )); + +### Interface changes + +Additions and changes (you will need to update any implementations or subclasses you may have created): + +- Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +- Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +- Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +- Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +- Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +- Added `Guzzle\Stream\StreamInterface::isRepeatable` +- Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. + +The following methods were removed from interfaces. All of these methods are still available in the concrete classes +that implement them, but you should update your code to use alternative methods: + +- Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + `$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))` or + `$client->setDefaultOption('headers/{header_name}', 'value')`. or + `$client->setDefaultOption('headers', array('header_name' => 'value'))`. +- Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use `$client->getConfig()->getPath('request.options/headers')`. +- Removed `Guzzle\Http\ClientInterface::expandTemplate()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::setRequestFactory()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::getCurlMulti()`. This is a very specific implementation detail. +- Removed `Guzzle\Http\Message\RequestInterface::canCache`. Use the CachePlugin. +- Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`. Use the HistoryPlugin. +- Removed `Guzzle\Http\Message\RequestInterface::isRedirect`. Use the HistoryPlugin. + +### Cache plugin breaking changes + +- CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +- Always setting X-cache headers on cached responses +- Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +- `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +- `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +- `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +- Added `CacheStorageInterface::purge($url)` +- `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +- Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +3.5 to 3.6 +---------- + +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). + For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader(). + Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request. +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Moved getLinks() from Response to just be used on a Link header object. + +If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the +HeaderInterface (e.g. toArray(), getAll(), etc.). + +### Interface changes + +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() + +### Removed deprecated functions + +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). + +### Deprecations + +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. + +### Other changes + +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess + +3.3 to 3.4 +---------- + +Base URLs of a client now follow the rules of https://tools.ietf.org/html/rfc3986#section-5.2.2 when merging URLs. + +3.2 to 3.3 +---------- + +### Response::getEtag() quote stripping removed + +`Guzzle\Http\Message\Response::getEtag()` no longer strips quotes around the ETag response header + +### Removed `Guzzle\Http\Utils` + +The `Guzzle\Http\Utils` class was removed. This class was only used for testing. + +### Stream wrapper and type + +`Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getStreamType()` are no longer converted to lowercase. + +### curl.emit_io became emit_io + +Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the +'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' + +3.1 to 3.2 +---------- + +### CurlMulti is no longer reused globally + +Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added +to a single client can pollute requests dispatched from other clients. + +If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the +ServiceBuilder's `service_builder.create_client` event to inject a custom CurlMulti object into each client as it is +created. + +```php +$multi = new Guzzle\Http\Curl\CurlMulti(); +$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json'); +$builder->addListener('service_builder.create_client', function ($event) use ($multi) { + $event['client']->setCurlMulti($multi); +} +}); +``` + +### No default path + +URLs no longer have a default path value of '/' if no path was specified. + +Before: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com/ +``` + +After: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com +``` + +### Less verbose BadResponseException + +The exception message for `Guzzle\Http\Exception\BadResponseException` no longer contains the full HTTP request and +response information. You can, however, get access to the request and response object by calling `getRequest()` or +`getResponse()` on the exception object. + +### Query parameter aggregation + +Multi-valued query parameters are no longer aggregated using a callback function. `Guzzle\Http\Query` now has a +setAggregator() method that accepts a `Guzzle\Http\QueryAggregator\QueryAggregatorInterface` object. This object is +responsible for handling the aggregation of multi-valued query string variables into a flattened hash. + +2.8 to 3.x +---------- + +### Guzzle\Service\Inspector + +Change `\Guzzle\Service\Inspector::fromConfig` to `\Guzzle\Common\Collection::fromConfig` + +**Before** + +```php +use Guzzle\Service\Inspector; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Inspector::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +**After** + +```php +use Guzzle\Common\Collection; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Collection::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +### Convert XML Service Descriptions to JSON + +**Before** + +```xml + + + + + + Get a list of groups + + + Uses a search query to get a list of groups + + + + Create a group + + + + + Delete a group by ID + + + + + + + Update a group + + + + + + +``` + +**After** + +```json +{ + "name": "Zendesk REST API v2", + "apiVersion": "2012-12-31", + "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users", + "operations": { + "list_groups": { + "httpMethod":"GET", + "uri": "groups.json", + "summary": "Get a list of groups" + }, + "search_groups":{ + "httpMethod":"GET", + "uri": "search.json?query=\"{query} type:group\"", + "summary": "Uses a search query to get a list of groups", + "parameters":{ + "query":{ + "location": "uri", + "description":"Zendesk Search Query", + "type": "string", + "required": true + } + } + }, + "create_group": { + "httpMethod":"POST", + "uri": "groups.json", + "summary": "Create a group", + "parameters":{ + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + }, + "delete_group": { + "httpMethod":"DELETE", + "uri": "groups/{id}.json", + "summary": "Delete a group", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to delete by ID", + "type": "integer", + "required": true + } + } + }, + "get_group": { + "httpMethod":"GET", + "uri": "groups/{id}.json", + "summary": "Get a ticket", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to get by ID", + "type": "integer", + "required": true + } + } + }, + "update_group": { + "httpMethod":"PUT", + "uri": "groups/{id}.json", + "summary": "Update a group", + "parameters":{ + "id": { + "location": "uri", + "description":"Group to update by ID", + "type": "integer", + "required": true + }, + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + } +} +``` + +### Guzzle\Service\Description\ServiceDescription + +Commands are now called Operations + +**Before** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getCommands(); // @returns ApiCommandInterface[] +$sd->hasCommand($name); +$sd->getCommand($name); // @returns ApiCommandInterface|null +$sd->addCommand($command); // @param ApiCommandInterface $command +``` + +**After** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getOperations(); // @returns OperationInterface[] +$sd->hasOperation($name); +$sd->getOperation($name); // @returns OperationInterface|null +$sd->addOperation($operation); // @param OperationInterface $operation +``` + +### Guzzle\Common\Inflection\Inflector + +Namespace is now `Guzzle\Inflection\Inflector` + +### Guzzle\Http\Plugin + +Namespace is now `Guzzle\Plugin`. Many other changes occur within this namespace and are detailed in their own sections below. + +### Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log + +Now `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` respectively. + +**Before** + +```php +use Guzzle\Common\Log\ClosureLogAdapter; +use Guzzle\Http\Plugin\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $verbosity is an integer indicating desired message verbosity level +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE); +``` + +**After** + +```php +use Guzzle\Log\ClosureLogAdapter; +use Guzzle\Log\MessageFormatter; +use Guzzle\Plugin\Log\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $format is a string indicating desired message format -- @see MessageFormatter +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT); +``` + +### Guzzle\Http\Plugin\CurlAuthPlugin + +Now `Guzzle\Plugin\CurlAuth\CurlAuthPlugin`. + +### Guzzle\Http\Plugin\ExponentialBackoffPlugin + +Now `Guzzle\Plugin\Backoff\BackoffPlugin`, and other changes. + +**Before** + +```php +use Guzzle\Http\Plugin\ExponentialBackoffPlugin; + +$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge( + ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429) + )); + +$client->addSubscriber($backoffPlugin); +``` + +**After** + +```php +use Guzzle\Plugin\Backoff\BackoffPlugin; +use Guzzle\Plugin\Backoff\HttpBackoffStrategy; + +// Use convenient factory method instead -- see implementation for ideas of what +// you can do with chaining backoff strategies +$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge( + HttpBackoffStrategy::getDefaultFailureCodes(), array(429) + )); +$client->addSubscriber($backoffPlugin); +``` + +### Known Issues + +#### [BUG] Accept-Encoding header behavior changed unintentionally. + +(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e) + +In version 2.8 setting the `Accept-Encoding` header would set the CURLOPT_ENCODING option, which permitted cURL to +properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen. +See issue #217 for a workaround, or use a version containing the fix. diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/composer.json b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/composer.json new file mode 100644 index 0000000..f369ce6 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/composer.json @@ -0,0 +1,105 @@ +{ + "name": "guzzlehttp/guzzle", + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "framework", + "http", + "rest", + "web service", + "curl", + "client", + "HTTP client", + "PSR-7", + "PSR-18" + ], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "ext-json": "*", + "guzzlehttp/promises": "^1.5", + "guzzlehttp/psr7": "^1.9 || ^2.4", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2 || ^3.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "ext-curl": "*", + "bamarni/composer-bin-plugin": "^1.8.1", + "php-http/client-integration-tests": "^3.0", + "phpunit/phpunit": "^8.5.29 || ^9.5.23", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "7.5-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\": "tests/" + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/BodySummarizer.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/BodySummarizer.php new file mode 100644 index 0000000..6eca94e --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/BodySummarizer.php @@ -0,0 +1,28 @@ +truncateAt = $truncateAt; + } + + /** + * Returns a summarized message body. + */ + public function summarize(MessageInterface $message): ?string + { + return $this->truncateAt === null + ? \GuzzleHttp\Psr7\Message::bodySummary($message) + : \GuzzleHttp\Psr7\Message::bodySummary($message, $this->truncateAt); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php new file mode 100644 index 0000000..3e02e03 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/BodySummarizerInterface.php @@ -0,0 +1,13 @@ + 'http://www.foo.com/1.0/', + * 'timeout' => 0, + * 'allow_redirects' => false, + * 'proxy' => '192.168.16.1:10' + * ]); + * + * Client configuration settings include the following options: + * + * - handler: (callable) Function that transfers HTTP requests over the + * wire. The function is called with a Psr7\Http\Message\RequestInterface + * and array of transfer options, and must return a + * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a + * Psr7\Http\Message\ResponseInterface on success. + * If no handler is provided, a default handler will be created + * that enables all of the request options below by attaching all of the + * default middleware to the handler. + * - base_uri: (string|UriInterface) Base URI of the client that is merged + * into relative URIs. Can be a string or instance of UriInterface. + * - **: any request option + * + * @param array $config Client configuration settings. + * + * @see \GuzzleHttp\RequestOptions for a list of available request options. + */ + public function __construct(array $config = []) + { + if (!isset($config['handler'])) { + $config['handler'] = HandlerStack::create(); + } elseif (!\is_callable($config['handler'])) { + throw new InvalidArgumentException('handler must be a callable'); + } + + // Convert the base_uri to a UriInterface + if (isset($config['base_uri'])) { + $config['base_uri'] = Psr7\Utils::uriFor($config['base_uri']); + } + + $this->configureDefaults($config); + } + + /** + * @param string $method + * @param array $args + * + * @return PromiseInterface|ResponseInterface + * + * @deprecated Client::__call will be removed in guzzlehttp/guzzle:8.0. + */ + public function __call($method, $args) + { + if (\count($args) < 1) { + throw new InvalidArgumentException('Magic request methods require a URI and optional options array'); + } + + $uri = $args[0]; + $opts = $args[1] ?? []; + + return \substr($method, -5) === 'Async' + ? $this->requestAsync(\substr($method, 0, -5), $uri, $opts) + : $this->request($method, $uri, $opts); + } + + /** + * Asynchronously send an HTTP request. + * + * @param array $options Request options to apply to the given + * request and to the transfer. See \GuzzleHttp\RequestOptions. + */ + public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface + { + // Merge the base URI into the request URI if needed. + $options = $this->prepareDefaults($options); + + return $this->transfer( + $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')), + $options + ); + } + + /** + * Send an HTTP request. + * + * @param array $options Request options to apply to the given + * request and to the transfer. See \GuzzleHttp\RequestOptions. + * + * @throws GuzzleException + */ + public function send(RequestInterface $request, array $options = []): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + return $this->sendAsync($request, $options)->wait(); + } + + /** + * The HttpClient PSR (PSR-18) specify this method. + * + * @inheritDoc + */ + public function sendRequest(RequestInterface $request): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + $options[RequestOptions::ALLOW_REDIRECTS] = false; + $options[RequestOptions::HTTP_ERRORS] = false; + + return $this->sendAsync($request, $options)->wait(); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. + */ + public function requestAsync(string $method, $uri = '', array $options = []): PromiseInterface + { + $options = $this->prepareDefaults($options); + // Remove request modifying parameter because it can be done up-front. + $headers = $options['headers'] ?? []; + $body = $options['body'] ?? null; + $version = $options['version'] ?? '1.1'; + // Merge the URI into the base URI. + $uri = $this->buildUri(Psr7\Utils::uriFor($uri), $options); + if (\is_array($body)) { + throw $this->invalidBody(); + } + $request = new Psr7\Request($method, $uri, $headers, $body, $version); + // Remove the option so that they are not doubly-applied. + unset($options['headers'], $options['body'], $options['version']); + + return $this->transfer($request, $options); + } + + /** + * Create and send an HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string $method HTTP method. + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. + * + * @throws GuzzleException + */ + public function request(string $method, $uri = '', array $options = []): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + return $this->requestAsync($method, $uri, $options)->wait(); + } + + /** + * Get a client configuration option. + * + * These options include default request options of the client, a "handler" + * (if utilized by the concrete client), and a "base_uri" if utilized by + * the concrete client. + * + * @param string|null $option The config option to retrieve. + * + * @return mixed + * + * @deprecated Client::getConfig will be removed in guzzlehttp/guzzle:8.0. + */ + public function getConfig(?string $option = null) + { + return $option === null + ? $this->config + : ($this->config[$option] ?? null); + } + + private function buildUri(UriInterface $uri, array $config): UriInterface + { + if (isset($config['base_uri'])) { + $uri = Psr7\UriResolver::resolve(Psr7\Utils::uriFor($config['base_uri']), $uri); + } + + if (isset($config['idn_conversion']) && ($config['idn_conversion'] !== false)) { + $idnOptions = ($config['idn_conversion'] === true) ? \IDNA_DEFAULT : $config['idn_conversion']; + $uri = Utils::idnUriConvert($uri, $idnOptions); + } + + return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri; + } + + /** + * Configures the default options for a client. + */ + private function configureDefaults(array $config): void + { + $defaults = [ + 'allow_redirects' => RedirectMiddleware::$defaultSettings, + 'http_errors' => true, + 'decode_content' => true, + 'verify' => true, + 'cookies' => false, + 'idn_conversion' => false, + ]; + + // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set. + + // We can only trust the HTTP_PROXY environment variable in a CLI + // process due to the fact that PHP has no reliable mechanism to + // get environment variables that start with "HTTP_". + if (\PHP_SAPI === 'cli' && ($proxy = Utils::getenv('HTTP_PROXY'))) { + $defaults['proxy']['http'] = $proxy; + } + + if ($proxy = Utils::getenv('HTTPS_PROXY')) { + $defaults['proxy']['https'] = $proxy; + } + + if ($noProxy = Utils::getenv('NO_PROXY')) { + $cleanedNoProxy = \str_replace(' ', '', $noProxy); + $defaults['proxy']['no'] = \explode(',', $cleanedNoProxy); + } + + $this->config = $config + $defaults; + + if (!empty($config['cookies']) && $config['cookies'] === true) { + $this->config['cookies'] = new CookieJar(); + } + + // Add the default user-agent header. + if (!isset($this->config['headers'])) { + $this->config['headers'] = ['User-Agent' => Utils::defaultUserAgent()]; + } else { + // Add the User-Agent header if one was not already set. + foreach (\array_keys($this->config['headers']) as $name) { + if (\strtolower($name) === 'user-agent') { + return; + } + } + $this->config['headers']['User-Agent'] = Utils::defaultUserAgent(); + } + } + + /** + * Merges default options into the array. + * + * @param array $options Options to modify by reference + */ + private function prepareDefaults(array $options): array + { + $defaults = $this->config; + + if (!empty($defaults['headers'])) { + // Default headers are only added if they are not present. + $defaults['_conditional'] = $defaults['headers']; + unset($defaults['headers']); + } + + // Special handling for headers is required as they are added as + // conditional headers and as headers passed to a request ctor. + if (\array_key_exists('headers', $options)) { + // Allows default headers to be unset. + if ($options['headers'] === null) { + $defaults['_conditional'] = []; + unset($options['headers']); + } elseif (!\is_array($options['headers'])) { + throw new InvalidArgumentException('headers must be an array'); + } + } + + // Shallow merge defaults underneath options. + $result = $options + $defaults; + + // Remove null values. + foreach ($result as $k => $v) { + if ($v === null) { + unset($result[$k]); + } + } + + return $result; + } + + /** + * Transfers the given request and applies request options. + * + * The URI of the request is not modified and the request options are used + * as-is without merging in default options. + * + * @param array $options See \GuzzleHttp\RequestOptions. + */ + private function transfer(RequestInterface $request, array $options): PromiseInterface + { + $request = $this->applyOptions($request, $options); + /** @var HandlerStack $handler */ + $handler = $options['handler']; + + try { + return P\Create::promiseFor($handler($request, $options)); + } catch (\Exception $e) { + return P\Create::rejectionFor($e); + } + } + + /** + * Applies the array of request options to a request. + */ + private function applyOptions(RequestInterface $request, array &$options): RequestInterface + { + $modify = [ + 'set_headers' => [], + ]; + + if (isset($options['headers'])) { + if (array_keys($options['headers']) === range(0, count($options['headers']) - 1)) { + throw new InvalidArgumentException('The headers array must have header name as keys.'); + } + $modify['set_headers'] = $options['headers']; + unset($options['headers']); + } + + if (isset($options['form_params'])) { + if (isset($options['multipart'])) { + throw new InvalidArgumentException('You cannot use ' + . 'form_params and multipart at the same time. Use the ' + . 'form_params option if you want to send application/' + . 'x-www-form-urlencoded requests, and the multipart ' + . 'option to send multipart/form-data requests.'); + } + $options['body'] = \http_build_query($options['form_params'], '', '&'); + unset($options['form_params']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded'; + } + + if (isset($options['multipart'])) { + $options['body'] = new Psr7\MultipartStream($options['multipart']); + unset($options['multipart']); + } + + if (isset($options['json'])) { + $options['body'] = Utils::jsonEncode($options['json']); + unset($options['json']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/json'; + } + + if (!empty($options['decode_content']) + && $options['decode_content'] !== true + ) { + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding'], $options['_conditional']); + $modify['set_headers']['Accept-Encoding'] = $options['decode_content']; + } + + if (isset($options['body'])) { + if (\is_array($options['body'])) { + throw $this->invalidBody(); + } + $modify['body'] = Psr7\Utils::streamFor($options['body']); + unset($options['body']); + } + + if (!empty($options['auth']) && \is_array($options['auth'])) { + $value = $options['auth']; + $type = isset($value[2]) ? \strtolower($value[2]) : 'basic'; + switch ($type) { + case 'basic': + // Ensure that we don't have the header in different case and set the new value. + $modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization'], $modify['set_headers']); + $modify['set_headers']['Authorization'] = 'Basic ' + . \base64_encode("$value[0]:$value[1]"); + break; + case 'digest': + // @todo: Do not rely on curl + $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_DIGEST; + $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + case 'ntlm': + $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM; + $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + } + } + + if (isset($options['query'])) { + $value = $options['query']; + if (\is_array($value)) { + $value = \http_build_query($value, '', '&', \PHP_QUERY_RFC3986); + } + if (!\is_string($value)) { + throw new InvalidArgumentException('query must be a string or array'); + } + $modify['query'] = $value; + unset($options['query']); + } + + // Ensure that sink is not an invalid value. + if (isset($options['sink'])) { + // TODO: Add more sink validation? + if (\is_bool($options['sink'])) { + throw new InvalidArgumentException('sink must not be a boolean'); + } + } + + $request = Psr7\Utils::modifyRequest($request, $modify); + if ($request->getBody() instanceof Psr7\MultipartStream) { + // Use a multipart/form-data POST if a Content-Type is not set. + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary=' + . $request->getBody()->getBoundary(); + } + + // Merge in conditional headers if they are not present. + if (isset($options['_conditional'])) { + // Build up the changes so it's in a single clone of the message. + $modify = []; + foreach ($options['_conditional'] as $k => $v) { + if (!$request->hasHeader($k)) { + $modify['set_headers'][$k] = $v; + } + } + $request = Psr7\Utils::modifyRequest($request, $modify); + // Don't pass this internal value along to middleware/handlers. + unset($options['_conditional']); + } + + return $request; + } + + /** + * Return an InvalidArgumentException with pre-set message. + */ + private function invalidBody(): InvalidArgumentException + { + return new InvalidArgumentException('Passing in the "body" request ' + . 'option as an array to send a request is not supported. ' + . 'Please use the "form_params" request option to send a ' + . 'application/x-www-form-urlencoded request, or the "multipart" ' + . 'request option to send a multipart/form-data request.'); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/ClientInterface.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/ClientInterface.php new file mode 100644 index 0000000..6aaee61 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/ClientInterface.php @@ -0,0 +1,84 @@ +request('GET', $uri, $options); + } + + /** + * Create and send an HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function head($uri, array $options = []): ResponseInterface + { + return $this->request('HEAD', $uri, $options); + } + + /** + * Create and send an HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function put($uri, array $options = []): ResponseInterface + { + return $this->request('PUT', $uri, $options); + } + + /** + * Create and send an HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function post($uri, array $options = []): ResponseInterface + { + return $this->request('POST', $uri, $options); + } + + /** + * Create and send an HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function patch($uri, array $options = []): ResponseInterface + { + return $this->request('PATCH', $uri, $options); + } + + /** + * Create and send an HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function delete($uri, array $options = []): ResponseInterface + { + return $this->request('DELETE', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface; + + /** + * Create and send an asynchronous HTTP GET request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function getAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('GET', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function headAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('HEAD', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function putAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('PUT', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function postAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('POST', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function patchAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('PATCH', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function deleteAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('DELETE', $uri, $options); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php new file mode 100644 index 0000000..9985a98 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php @@ -0,0 +1,317 @@ +strictMode = $strictMode; + + foreach ($cookieArray as $cookie) { + if (!($cookie instanceof SetCookie)) { + $cookie = new SetCookie($cookie); + } + $this->setCookie($cookie); + } + } + + /** + * Create a new Cookie jar from an associative array and domain. + * + * @param array $cookies Cookies to create the jar from + * @param string $domain Domain to set the cookies to + */ + public static function fromArray(array $cookies, string $domain): self + { + $cookieJar = new self(); + foreach ($cookies as $name => $value) { + $cookieJar->setCookie(new SetCookie([ + 'Domain' => $domain, + 'Name' => $name, + 'Value' => $value, + 'Discard' => true + ])); + } + + return $cookieJar; + } + + /** + * Evaluate if this cookie should be persisted to storage + * that survives between requests. + * + * @param SetCookie $cookie Being evaluated. + * @param bool $allowSessionCookies If we should persist session cookies + */ + public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool + { + if ($cookie->getExpires() || $allowSessionCookies) { + if (!$cookie->getDiscard()) { + return true; + } + } + + return false; + } + + /** + * Finds and returns the cookie based on the name + * + * @param string $name cookie name to search for + * + * @return SetCookie|null cookie that was found or null if not found + */ + public function getCookieByName(string $name): ?SetCookie + { + foreach ($this->cookies as $cookie) { + if ($cookie->getName() !== null && \strcasecmp($cookie->getName(), $name) === 0) { + return $cookie; + } + } + + return null; + } + + /** + * @inheritDoc + */ + public function toArray(): array + { + return \array_map(static function (SetCookie $cookie): array { + return $cookie->toArray(); + }, $this->getIterator()->getArrayCopy()); + } + + /** + * @inheritDoc + */ + public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void + { + if (!$domain) { + $this->cookies = []; + return; + } elseif (!$path) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($domain): bool { + return !$cookie->matchesDomain($domain); + } + ); + } elseif (!$name) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain): bool { + return !($cookie->matchesPath($path) && + $cookie->matchesDomain($domain)); + } + ); + } else { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain, $name) { + return !($cookie->getName() == $name && + $cookie->matchesPath($path) && + $cookie->matchesDomain($domain)); + } + ); + } + } + + /** + * @inheritDoc + */ + public function clearSessionCookies(): void + { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie): bool { + return !$cookie->getDiscard() && $cookie->getExpires(); + } + ); + } + + /** + * @inheritDoc + */ + public function setCookie(SetCookie $cookie): bool + { + // If the name string is empty (but not 0), ignore the set-cookie + // string entirely. + $name = $cookie->getName(); + if (!$name && $name !== '0') { + return false; + } + + // Only allow cookies with set and valid domain, name, value + $result = $cookie->validate(); + if ($result !== true) { + if ($this->strictMode) { + throw new \RuntimeException('Invalid cookie: ' . $result); + } + $this->removeCookieIfEmpty($cookie); + return false; + } + + // Resolve conflicts with previously set cookies + foreach ($this->cookies as $i => $c) { + // Two cookies are identical, when their path, and domain are + // identical. + if ($c->getPath() != $cookie->getPath() || + $c->getDomain() != $cookie->getDomain() || + $c->getName() != $cookie->getName() + ) { + continue; + } + + // The previously set cookie is a discard cookie and this one is + // not so allow the new cookie to be set + if (!$cookie->getDiscard() && $c->getDiscard()) { + unset($this->cookies[$i]); + continue; + } + + // If the new cookie's expiration is further into the future, then + // replace the old cookie + if ($cookie->getExpires() > $c->getExpires()) { + unset($this->cookies[$i]); + continue; + } + + // If the value has changed, we better change it + if ($cookie->getValue() !== $c->getValue()) { + unset($this->cookies[$i]); + continue; + } + + // The cookie exists, so no need to continue + return false; + } + + $this->cookies[] = $cookie; + + return true; + } + + public function count(): int + { + return \count($this->cookies); + } + + /** + * @return \ArrayIterator + */ + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator(\array_values($this->cookies)); + } + + public function extractCookies(RequestInterface $request, ResponseInterface $response): void + { + if ($cookieHeader = $response->getHeader('Set-Cookie')) { + foreach ($cookieHeader as $cookie) { + $sc = SetCookie::fromString($cookie); + if (!$sc->getDomain()) { + $sc->setDomain($request->getUri()->getHost()); + } + if (0 !== \strpos($sc->getPath(), '/')) { + $sc->setPath($this->getCookiePathFromRequest($request)); + } + if (!$sc->matchesDomain($request->getUri()->getHost())) { + continue; + } + // Note: At this point `$sc->getDomain()` being a public suffix should + // be rejected, but we don't want to pull in the full PSL dependency. + $this->setCookie($sc); + } + } + } + + /** + * Computes cookie path following RFC 6265 section 5.1.4 + * + * @link https://tools.ietf.org/html/rfc6265#section-5.1.4 + */ + private function getCookiePathFromRequest(RequestInterface $request): string + { + $uriPath = $request->getUri()->getPath(); + if ('' === $uriPath) { + return '/'; + } + if (0 !== \strpos($uriPath, '/')) { + return '/'; + } + if ('/' === $uriPath) { + return '/'; + } + $lastSlashPos = \strrpos($uriPath, '/'); + if (0 === $lastSlashPos || false === $lastSlashPos) { + return '/'; + } + + return \substr($uriPath, 0, $lastSlashPos); + } + + public function withCookieHeader(RequestInterface $request): RequestInterface + { + $values = []; + $uri = $request->getUri(); + $scheme = $uri->getScheme(); + $host = $uri->getHost(); + $path = $uri->getPath() ?: '/'; + + foreach ($this->cookies as $cookie) { + if ($cookie->matchesPath($path) && + $cookie->matchesDomain($host) && + !$cookie->isExpired() && + (!$cookie->getSecure() || $scheme === 'https') + ) { + $values[] = $cookie->getName() . '=' + . $cookie->getValue(); + } + } + + return $values + ? $request->withHeader('Cookie', \implode('; ', $values)) + : $request; + } + + /** + * If a cookie already exists and the server asks to set it again with a + * null value, the cookie must be deleted. + */ + private function removeCookieIfEmpty(SetCookie $cookie): void + { + $cookieValue = $cookie->getValue(); + if ($cookieValue === null || $cookieValue === '') { + $this->clear( + $cookie->getDomain(), + $cookie->getPath(), + $cookie->getName() + ); + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php new file mode 100644 index 0000000..7df374b --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php @@ -0,0 +1,79 @@ + + */ +interface CookieJarInterface extends \Countable, \IteratorAggregate +{ + /** + * Create a request with added cookie headers. + * + * If no matching cookies are found in the cookie jar, then no Cookie + * header is added to the request and the same request is returned. + * + * @param RequestInterface $request Request object to modify. + * + * @return RequestInterface returns the modified request. + */ + public function withCookieHeader(RequestInterface $request): RequestInterface; + + /** + * Extract cookies from an HTTP response and store them in the CookieJar. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface $response Response that was received + */ + public function extractCookies(RequestInterface $request, ResponseInterface $response): void; + + /** + * Sets a cookie in the cookie jar. + * + * @param SetCookie $cookie Cookie to set. + * + * @return bool Returns true on success or false on failure + */ + public function setCookie(SetCookie $cookie): bool; + + /** + * Remove cookies currently held in the cookie jar. + * + * Invoking this method without arguments will empty the whole cookie jar. + * If given a $domain argument only cookies belonging to that domain will + * be removed. If given a $domain and $path argument, cookies belonging to + * the specified path within that domain are removed. If given all three + * arguments, then the cookie with the specified name, path and domain is + * removed. + * + * @param string|null $domain Clears cookies matching a domain + * @param string|null $path Clears cookies matching a domain and path + * @param string|null $name Clears cookies matching a domain, path, and name + */ + public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void; + + /** + * Discard all sessions cookies. + * + * Removes cookies that don't have an expire field or a have a discard + * field set to true. To be called when the user agent shuts down according + * to RFC 2965. + */ + public function clearSessionCookies(): void; + + /** + * Converts the cookie jar to an array. + */ + public function toArray(): array; +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php new file mode 100644 index 0000000..290236d --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php @@ -0,0 +1,101 @@ +filename = $cookieFile; + $this->storeSessionCookies = $storeSessionCookies; + + if (\file_exists($cookieFile)) { + $this->load($cookieFile); + } + } + + /** + * Saves the file when shutting down + */ + public function __destruct() + { + $this->save($this->filename); + } + + /** + * Saves the cookies to a file. + * + * @param string $filename File to save + * + * @throws \RuntimeException if the file cannot be found or created + */ + public function save(string $filename): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $jsonStr = Utils::jsonEncode($json); + if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) { + throw new \RuntimeException("Unable to save file {$filename}"); + } + } + + /** + * Load cookies from a JSON formatted file. + * + * Old cookies are kept unless overwritten by newly loaded ones. + * + * @param string $filename Cookie file to load. + * + * @throws \RuntimeException if the file cannot be loaded. + */ + public function load(string $filename): void + { + $json = \file_get_contents($filename); + if (false === $json) { + throw new \RuntimeException("Unable to load file {$filename}"); + } + if ($json === '') { + return; + } + + $data = Utils::jsonDecode($json, true); + if (\is_array($data)) { + foreach ($data as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (\is_scalar($data) && !empty($data)) { + throw new \RuntimeException("Invalid cookie file: {$filename}"); + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php new file mode 100644 index 0000000..5d51ca9 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php @@ -0,0 +1,77 @@ +sessionKey = $sessionKey; + $this->storeSessionCookies = $storeSessionCookies; + $this->load(); + } + + /** + * Saves cookies to session when shutting down + */ + public function __destruct() + { + $this->save(); + } + + /** + * Save cookies to the client session + */ + public function save(): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $_SESSION[$this->sessionKey] = \json_encode($json); + } + + /** + * Load the contents of the client session into the data array + */ + protected function load(): void + { + if (!isset($_SESSION[$this->sessionKey])) { + return; + } + $data = \json_decode($_SESSION[$this->sessionKey], true); + if (\is_array($data)) { + foreach ($data as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (\strlen($data)) { + throw new \RuntimeException("Invalid cookie data"); + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php new file mode 100644 index 0000000..a613c77 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php @@ -0,0 +1,446 @@ + null, + 'Value' => null, + 'Domain' => null, + 'Path' => '/', + 'Max-Age' => null, + 'Expires' => null, + 'Secure' => false, + 'Discard' => false, + 'HttpOnly' => false + ]; + + /** + * @var array Cookie data + */ + private $data; + + /** + * Create a new SetCookie object from a string. + * + * @param string $cookie Set-Cookie header string + */ + public static function fromString(string $cookie): self + { + // Create the default return array + $data = self::$defaults; + // Explode the cookie string using a series of semicolons + $pieces = \array_filter(\array_map('trim', \explode(';', $cookie))); + // The name of the cookie (first kvp) must exist and include an equal sign. + if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) { + return new self($data); + } + + // Add the cookie pieces into the parsed data array + foreach ($pieces as $part) { + $cookieParts = \explode('=', $part, 2); + $key = \trim($cookieParts[0]); + $value = isset($cookieParts[1]) + ? \trim($cookieParts[1], " \n\r\t\0\x0B") + : true; + + // Only check for non-cookies when cookies have been found + if (!isset($data['Name'])) { + $data['Name'] = $key; + $data['Value'] = $value; + } else { + foreach (\array_keys(self::$defaults) as $search) { + if (!\strcasecmp($search, $key)) { + $data[$search] = $value; + continue 2; + } + } + $data[$key] = $value; + } + } + + return new self($data); + } + + /** + * @param array $data Array of cookie data provided by a Cookie parser + */ + public function __construct(array $data = []) + { + /** @var array|null $replaced will be null in case of replace error */ + $replaced = \array_replace(self::$defaults, $data); + if ($replaced === null) { + throw new \InvalidArgumentException('Unable to replace the default values for the Cookie.'); + } + + $this->data = $replaced; + // Extract the Expires value and turn it into a UNIX timestamp if needed + if (!$this->getExpires() && $this->getMaxAge()) { + // Calculate the Expires date + $this->setExpires(\time() + $this->getMaxAge()); + } elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) { + $this->setExpires($expires); + } + } + + public function __toString() + { + $str = $this->data['Name'] . '=' . ($this->data['Value'] ?? '') . '; '; + foreach ($this->data as $k => $v) { + if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) { + if ($k === 'Expires') { + $str .= 'Expires=' . \gmdate('D, d M Y H:i:s \G\M\T', $v) . '; '; + } else { + $str .= ($v === true ? $k : "{$k}={$v}") . '; '; + } + } + } + + return \rtrim($str, '; '); + } + + public function toArray(): array + { + return $this->data; + } + + /** + * Get the cookie name. + * + * @return string + */ + public function getName() + { + return $this->data['Name']; + } + + /** + * Set the cookie name. + * + * @param string $name Cookie name + */ + public function setName($name): void + { + if (!is_string($name)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Name'] = (string) $name; + } + + /** + * Get the cookie value. + * + * @return string|null + */ + public function getValue() + { + return $this->data['Value']; + } + + /** + * Set the cookie value. + * + * @param string $value Cookie value + */ + public function setValue($value): void + { + if (!is_string($value)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Value'] = (string) $value; + } + + /** + * Get the domain. + * + * @return string|null + */ + public function getDomain() + { + return $this->data['Domain']; + } + + /** + * Set the domain of the cookie. + * + * @param string|null $domain + */ + public function setDomain($domain): void + { + if (!is_string($domain) && null !== $domain) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Domain'] = null === $domain ? null : (string) $domain; + } + + /** + * Get the path. + * + * @return string + */ + public function getPath() + { + return $this->data['Path']; + } + + /** + * Set the path of the cookie. + * + * @param string $path Path of the cookie + */ + public function setPath($path): void + { + if (!is_string($path)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Path'] = (string) $path; + } + + /** + * Maximum lifetime of the cookie in seconds. + * + * @return int|null + */ + public function getMaxAge() + { + return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age']; + } + + /** + * Set the max-age of the cookie. + * + * @param int|null $maxAge Max age of the cookie in seconds + */ + public function setMaxAge($maxAge): void + { + if (!is_int($maxAge) && null !== $maxAge) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge; + } + + /** + * The UNIX timestamp when the cookie Expires. + * + * @return string|int|null + */ + public function getExpires() + { + return $this->data['Expires']; + } + + /** + * Set the unix timestamp for which the cookie will expire. + * + * @param int|string|null $timestamp Unix timestamp or any English textual datetime description. + */ + public function setExpires($timestamp): void + { + if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Expires'] = null === $timestamp ? null : (\is_numeric($timestamp) ? (int) $timestamp : \strtotime((string) $timestamp)); + } + + /** + * Get whether or not this is a secure cookie. + * + * @return bool + */ + public function getSecure() + { + return $this->data['Secure']; + } + + /** + * Set whether or not the cookie is secure. + * + * @param bool $secure Set to true or false if secure + */ + public function setSecure($secure): void + { + if (!is_bool($secure)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Secure'] = (bool) $secure; + } + + /** + * Get whether or not this is a session cookie. + * + * @return bool|null + */ + public function getDiscard() + { + return $this->data['Discard']; + } + + /** + * Set whether or not this is a session cookie. + * + * @param bool $discard Set to true or false if this is a session cookie + */ + public function setDiscard($discard): void + { + if (!is_bool($discard)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Discard'] = (bool) $discard; + } + + /** + * Get whether or not this is an HTTP only cookie. + * + * @return bool + */ + public function getHttpOnly() + { + return $this->data['HttpOnly']; + } + + /** + * Set whether or not this is an HTTP only cookie. + * + * @param bool $httpOnly Set to true or false if this is HTTP only + */ + public function setHttpOnly($httpOnly): void + { + if (!is_bool($httpOnly)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['HttpOnly'] = (bool) $httpOnly; + } + + /** + * Check if the cookie matches a path value. + * + * A request-path path-matches a given cookie-path if at least one of + * the following conditions holds: + * + * - The cookie-path and the request-path are identical. + * - The cookie-path is a prefix of the request-path, and the last + * character of the cookie-path is %x2F ("/"). + * - The cookie-path is a prefix of the request-path, and the first + * character of the request-path that is not included in the cookie- + * path is a %x2F ("/") character. + * + * @param string $requestPath Path to check against + */ + public function matchesPath(string $requestPath): bool + { + $cookiePath = $this->getPath(); + + // Match on exact matches or when path is the default empty "/" + if ($cookiePath === '/' || $cookiePath == $requestPath) { + return true; + } + + // Ensure that the cookie-path is a prefix of the request path. + if (0 !== \strpos($requestPath, $cookiePath)) { + return false; + } + + // Match if the last character of the cookie-path is "/" + if (\substr($cookiePath, -1, 1) === '/') { + return true; + } + + // Match if the first character not included in cookie path is "/" + return \substr($requestPath, \strlen($cookiePath), 1) === '/'; + } + + /** + * Check if the cookie matches a domain value. + * + * @param string $domain Domain to check against + */ + public function matchesDomain(string $domain): bool + { + $cookieDomain = $this->getDomain(); + if (null === $cookieDomain) { + return true; + } + + // Remove the leading '.' as per spec in RFC 6265. + // https://tools.ietf.org/html/rfc6265#section-5.2.3 + $cookieDomain = \ltrim(\strtolower($cookieDomain), '.'); + + $domain = \strtolower($domain); + + // Domain not set or exact match. + if ('' === $cookieDomain || $domain === $cookieDomain) { + return true; + } + + // Matching the subdomain according to RFC 6265. + // https://tools.ietf.org/html/rfc6265#section-5.1.3 + if (\filter_var($domain, \FILTER_VALIDATE_IP)) { + return false; + } + + return (bool) \preg_match('/\.' . \preg_quote($cookieDomain, '/') . '$/', $domain); + } + + /** + * Check if the cookie is expired. + */ + public function isExpired(): bool + { + return $this->getExpires() !== null && \time() > $this->getExpires(); + } + + /** + * Check if the cookie is valid according to RFC 6265. + * + * @return bool|string Returns true if valid or an error message if invalid + */ + public function validate() + { + $name = $this->getName(); + if ($name === '') { + return 'The cookie name must not be empty'; + } + + // Check if any of the invalid characters are present in the cookie name + if (\preg_match( + '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', + $name + )) { + return 'Cookie name must not contain invalid characters: ASCII ' + . 'Control characters (0-31;127), space, tab and the ' + . 'following characters: ()<>@,;:\"/?={}'; + } + + // Value must not be null. 0 and empty string are valid. Empty strings + // are technically against RFC 6265, but known to happen in the wild. + $value = $this->getValue(); + if ($value === null) { + return 'The cookie value must not be empty'; + } + + // Domains must not be empty, but can be 0. "0" is not a valid internet + // domain, but may be used as server name in a private network. + $domain = $this->getDomain(); + if ($domain === null || $domain === '') { + return 'The cookie domain must not be empty'; + } + + return true; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php new file mode 100644 index 0000000..a80956c --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/BadResponseException.php @@ -0,0 +1,39 @@ +request = $request; + $this->handlerContext = $handlerContext; + } + + /** + * Get the request that caused the exception + */ + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Get contextual information about the error from the underlying handler. + * + * The contents of this array will vary depending on which handler you are + * using. It may also be just an empty array. Relying on this data will + * couple you to a specific handler, but can give more debug information + * when needed. + */ + public function getHandlerContext(): array + { + return $this->handlerContext; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php new file mode 100644 index 0000000..fa3ed69 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/GuzzleException.php @@ -0,0 +1,9 @@ +getStatusCode() : 0; + parent::__construct($message, $code, $previous); + $this->request = $request; + $this->response = $response; + $this->handlerContext = $handlerContext; + } + + /** + * Wrap non-RequestExceptions with a RequestException + */ + public static function wrapException(RequestInterface $request, \Throwable $e): RequestException + { + return $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e); + } + + /** + * Factory method to create a new exception with a normalized error message + * + * @param RequestInterface $request Request sent + * @param ResponseInterface $response Response received + * @param \Throwable|null $previous Previous exception + * @param array $handlerContext Optional handler context + * @param BodySummarizerInterface|null $bodySummarizer Optional body summarizer + */ + public static function create( + RequestInterface $request, + ResponseInterface $response = null, + \Throwable $previous = null, + array $handlerContext = [], + BodySummarizerInterface $bodySummarizer = null + ): self { + if (!$response) { + return new self( + 'Error completing request', + $request, + null, + $previous, + $handlerContext + ); + } + + $level = (int) \floor($response->getStatusCode() / 100); + if ($level === 4) { + $label = 'Client error'; + $className = ClientException::class; + } elseif ($level === 5) { + $label = 'Server error'; + $className = ServerException::class; + } else { + $label = 'Unsuccessful request'; + $className = __CLASS__; + } + + $uri = $request->getUri(); + $uri = static::obfuscateUri($uri); + + // Client Error: `GET /` resulted in a `404 Not Found` response: + // ... (truncated) + $message = \sprintf( + '%s: `%s %s` resulted in a `%s %s` response', + $label, + $request->getMethod(), + $uri->__toString(), + $response->getStatusCode(), + $response->getReasonPhrase() + ); + + $summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response); + + if ($summary !== null) { + $message .= ":\n{$summary}\n"; + } + + return new $className($message, $request, $response, $previous, $handlerContext); + } + + /** + * Obfuscates URI if there is a username and a password present + */ + private static function obfuscateUri(UriInterface $uri): UriInterface + { + $userInfo = $uri->getUserInfo(); + + if (false !== ($pos = \strpos($userInfo, ':'))) { + return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***'); + } + + return $uri; + } + + /** + * Get the request that caused the exception + */ + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Get the associated response + */ + public function getResponse(): ?ResponseInterface + { + return $this->response; + } + + /** + * Check if a response was received + */ + public function hasResponse(): bool + { + return $this->response !== null; + } + + /** + * Get contextual information about the error from the underlying handler. + * + * The contents of this array will vary depending on which handler you are + * using. It may also be just an empty array. Relying on this data will + * couple you to a specific handler, but can give more debug information + * when needed. + */ + public function getHandlerContext(): array + { + return $this->handlerContext; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php new file mode 100644 index 0000000..8055e06 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Exception/ServerException.php @@ -0,0 +1,10 @@ +maxHandles = $maxHandles; + } + + public function create(RequestInterface $request, array $options): EasyHandle + { + if (isset($options['curl']['body_as_string'])) { + $options['_body_as_string'] = $options['curl']['body_as_string']; + unset($options['curl']['body_as_string']); + } + + $easy = new EasyHandle; + $easy->request = $request; + $easy->options = $options; + $conf = $this->getDefaultConf($easy); + $this->applyMethod($easy, $conf); + $this->applyHandlerOptions($easy, $conf); + $this->applyHeaders($easy, $conf); + unset($conf['_headers']); + + // Add handler options from the request configuration options + if (isset($options['curl'])) { + $conf = \array_replace($conf, $options['curl']); + } + + $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy); + $easy->handle = $this->handles ? \array_pop($this->handles) : \curl_init(); + curl_setopt_array($easy->handle, $conf); + + return $easy; + } + + public function release(EasyHandle $easy): void + { + $resource = $easy->handle; + unset($easy->handle); + + if (\count($this->handles) >= $this->maxHandles) { + \curl_close($resource); + } else { + // Remove all callback functions as they can hold onto references + // and are not cleaned up by curl_reset. Using curl_setopt_array + // does not work for some reason, so removing each one + // individually. + \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null); + \curl_setopt($resource, \CURLOPT_READFUNCTION, null); + \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null); + \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null); + \curl_reset($resource); + $this->handles[] = $resource; + } + } + + /** + * Completes a cURL transaction, either returning a response promise or a + * rejected promise. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + * @param CurlFactoryInterface $factory Dictates how the handle is released + */ + public static function finish(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface + { + if (isset($easy->options['on_stats'])) { + self::invokeStats($easy); + } + + if (!$easy->response || $easy->errno) { + return self::finishError($handler, $easy, $factory); + } + + // Return the response if it is present and there is no error. + $factory->release($easy); + + // Rewind the body of the response if possible. + $body = $easy->response->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + + return new FulfilledPromise($easy->response); + } + + private static function invokeStats(EasyHandle $easy): void + { + $curlStats = \curl_getinfo($easy->handle); + $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME); + $stats = new TransferStats( + $easy->request, + $easy->response, + $curlStats['total_time'], + $easy->errno, + $curlStats + ); + ($easy->options['on_stats'])($stats); + } + + /** + * @param callable(RequestInterface, array): PromiseInterface $handler + */ + private static function finishError(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface + { + // Get error information and release the handle to the factory. + $ctx = [ + 'errno' => $easy->errno, + 'error' => \curl_error($easy->handle), + 'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME), + ] + \curl_getinfo($easy->handle); + $ctx[self::CURL_VERSION_STR] = \curl_version()['version']; + $factory->release($easy); + + // Retry when nothing is present or when curl failed to rewind. + if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) { + return self::retryFailedRewind($handler, $easy, $ctx); + } + + return self::createRejection($easy, $ctx); + } + + private static function createRejection(EasyHandle $easy, array $ctx): PromiseInterface + { + static $connectionErrors = [ + \CURLE_OPERATION_TIMEOUTED => true, + \CURLE_COULDNT_RESOLVE_HOST => true, + \CURLE_COULDNT_CONNECT => true, + \CURLE_SSL_CONNECT_ERROR => true, + \CURLE_GOT_NOTHING => true, + ]; + + if ($easy->createResponseException) { + return P\Create::rejectionFor( + new RequestException( + 'An error was encountered while creating the response', + $easy->request, + $easy->response, + $easy->createResponseException, + $ctx + ) + ); + } + + // If an exception was encountered during the onHeaders event, then + // return a rejected promise that wraps that exception. + if ($easy->onHeadersException) { + return P\Create::rejectionFor( + new RequestException( + 'An error was encountered during the on_headers event', + $easy->request, + $easy->response, + $easy->onHeadersException, + $ctx + ) + ); + } + + $message = \sprintf( + 'cURL error %s: %s (%s)', + $ctx['errno'], + $ctx['error'], + 'see https://curl.haxx.se/libcurl/c/libcurl-errors.html' + ); + $uriString = (string) $easy->request->getUri(); + if ($uriString !== '' && false === \strpos($ctx['error'], $uriString)) { + $message .= \sprintf(' for %s', $uriString); + } + + // Create a connection exception if it was a specific error code. + $error = isset($connectionErrors[$easy->errno]) + ? new ConnectException($message, $easy->request, null, $ctx) + : new RequestException($message, $easy->request, $easy->response, null, $ctx); + + return P\Create::rejectionFor($error); + } + + /** + * @return array + */ + private function getDefaultConf(EasyHandle $easy): array + { + $conf = [ + '_headers' => $easy->request->getHeaders(), + \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), + \CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), + \CURLOPT_RETURNTRANSFER => false, + \CURLOPT_HEADER => false, + \CURLOPT_CONNECTTIMEOUT => 150, + ]; + + if (\defined('CURLOPT_PROTOCOLS')) { + $conf[\CURLOPT_PROTOCOLS] = \CURLPROTO_HTTP | \CURLPROTO_HTTPS; + } + + $version = $easy->request->getProtocolVersion(); + if ($version == 1.1) { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1; + } elseif ($version == 2.0) { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0; + } else { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0; + } + + return $conf; + } + + private function applyMethod(EasyHandle $easy, array &$conf): void + { + $body = $easy->request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size > 0) { + $this->applyBody($easy->request, $easy->options, $conf); + return; + } + + $method = $easy->request->getMethod(); + if ($method === 'PUT' || $method === 'POST') { + // See https://tools.ietf.org/html/rfc7230#section-3.3.2 + if (!$easy->request->hasHeader('Content-Length')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0'; + } + } elseif ($method === 'HEAD') { + $conf[\CURLOPT_NOBODY] = true; + unset( + $conf[\CURLOPT_WRITEFUNCTION], + $conf[\CURLOPT_READFUNCTION], + $conf[\CURLOPT_FILE], + $conf[\CURLOPT_INFILE] + ); + } + } + + private function applyBody(RequestInterface $request, array $options, array &$conf): void + { + $size = $request->hasHeader('Content-Length') + ? (int) $request->getHeaderLine('Content-Length') + : null; + + // Send the body as a string if the size is less than 1MB OR if the + // [curl][body_as_string] request value is set. + if (($size !== null && $size < 1000000) || !empty($options['_body_as_string'])) { + $conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody(); + // Don't duplicate the Content-Length header + $this->removeHeader('Content-Length', $conf); + $this->removeHeader('Transfer-Encoding', $conf); + } else { + $conf[\CURLOPT_UPLOAD] = true; + if ($size !== null) { + $conf[\CURLOPT_INFILESIZE] = $size; + $this->removeHeader('Content-Length', $conf); + } + $body = $request->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + $conf[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body) { + return $body->read($length); + }; + } + + // If the Expect header is not present, prevent curl from adding it + if (!$request->hasHeader('Expect')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Expect:'; + } + + // cURL sometimes adds a content-type by default. Prevent this. + if (!$request->hasHeader('Content-Type')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:'; + } + } + + private function applyHeaders(EasyHandle $easy, array &$conf): void + { + foreach ($conf['_headers'] as $name => $values) { + foreach ($values as $value) { + $value = (string) $value; + if ($value === '') { + // cURL requires a special format for empty headers. + // See https://github.com/guzzle/guzzle/issues/1882 for more details. + $conf[\CURLOPT_HTTPHEADER][] = "$name;"; + } else { + $conf[\CURLOPT_HTTPHEADER][] = "$name: $value"; + } + } + } + + // Remove the Accept header if one was not set + if (!$easy->request->hasHeader('Accept')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Accept:'; + } + } + + /** + * Remove a header from the options array. + * + * @param string $name Case-insensitive header to remove + * @param array $options Array of options to modify + */ + private function removeHeader(string $name, array &$options): void + { + foreach (\array_keys($options['_headers']) as $key) { + if (!\strcasecmp($key, $name)) { + unset($options['_headers'][$key]); + return; + } + } + } + + private function applyHandlerOptions(EasyHandle $easy, array &$conf): void + { + $options = $easy->options; + if (isset($options['verify'])) { + if ($options['verify'] === false) { + unset($conf[\CURLOPT_CAINFO]); + $conf[\CURLOPT_SSL_VERIFYHOST] = 0; + $conf[\CURLOPT_SSL_VERIFYPEER] = false; + } else { + $conf[\CURLOPT_SSL_VERIFYHOST] = 2; + $conf[\CURLOPT_SSL_VERIFYPEER] = true; + if (\is_string($options['verify'])) { + // Throw an error if the file/folder/link path is not valid or doesn't exist. + if (!\file_exists($options['verify'])) { + throw new \InvalidArgumentException("SSL CA bundle not found: {$options['verify']}"); + } + // If it's a directory or a link to a directory use CURLOPT_CAPATH. + // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO. + if ( + \is_dir($options['verify']) || + ( + \is_link($options['verify']) === true && + ($verifyLink = \readlink($options['verify'])) !== false && + \is_dir($verifyLink) + ) + ) { + $conf[\CURLOPT_CAPATH] = $options['verify']; + } else { + $conf[\CURLOPT_CAINFO] = $options['verify']; + } + } + } + } + + if (!isset($options['curl'][\CURLOPT_ENCODING]) && !empty($options['decode_content'])) { + $accept = $easy->request->getHeaderLine('Accept-Encoding'); + if ($accept) { + $conf[\CURLOPT_ENCODING] = $accept; + } else { + // The empty string enables all available decoders and implicitly + // sets a matching 'Accept-Encoding' header. + $conf[\CURLOPT_ENCODING] = ''; + // But as the user did not specify any acceptable encodings we need + // to overwrite this implicit header with an empty one. + $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:'; + } + } + + if (!isset($options['sink'])) { + // Use a default temp stream if no sink was set. + $options['sink'] = \GuzzleHttp\Psr7\Utils::tryFopen('php://temp', 'w+'); + } + $sink = $options['sink']; + if (!\is_string($sink)) { + $sink = \GuzzleHttp\Psr7\Utils::streamFor($sink); + } elseif (!\is_dir(\dirname($sink))) { + // Ensure that the directory exists before failing in curl. + throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink), $sink)); + } else { + $sink = new LazyOpenStream($sink, 'w+'); + } + $easy->sink = $sink; + $conf[\CURLOPT_WRITEFUNCTION] = static function ($ch, $write) use ($sink): int { + return $sink->write($write); + }; + + $timeoutRequiresNoSignal = false; + if (isset($options['timeout'])) { + $timeoutRequiresNoSignal |= $options['timeout'] < 1; + $conf[\CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000; + } + + // CURL default value is CURL_IPRESOLVE_WHATEVER + if (isset($options['force_ip_resolve'])) { + if ('v4' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4; + } elseif ('v6' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6; + } + } + + if (isset($options['connect_timeout'])) { + $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1; + $conf[\CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000; + } + + if ($timeoutRequiresNoSignal && \strtoupper(\substr(\PHP_OS, 0, 3)) !== 'WIN') { + $conf[\CURLOPT_NOSIGNAL] = true; + } + + if (isset($options['proxy'])) { + if (!\is_array($options['proxy'])) { + $conf[\CURLOPT_PROXY] = $options['proxy']; + } else { + $scheme = $easy->request->getUri()->getScheme(); + if (isset($options['proxy'][$scheme])) { + $host = $easy->request->getUri()->getHost(); + if (!isset($options['proxy']['no']) || !Utils::isHostInNoProxy($host, $options['proxy']['no'])) { + $conf[\CURLOPT_PROXY] = $options['proxy'][$scheme]; + } + } + } + } + + if (isset($options['cert'])) { + $cert = $options['cert']; + if (\is_array($cert)) { + $conf[\CURLOPT_SSLCERTPASSWD] = $cert[1]; + $cert = $cert[0]; + } + if (!\file_exists($cert)) { + throw new \InvalidArgumentException("SSL certificate not found: {$cert}"); + } + # OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files. + # see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html + $ext = pathinfo($cert, \PATHINFO_EXTENSION); + if (preg_match('#^(der|p12)$#i', $ext)) { + $conf[\CURLOPT_SSLCERTTYPE] = strtoupper($ext); + } + $conf[\CURLOPT_SSLCERT] = $cert; + } + + if (isset($options['ssl_key'])) { + if (\is_array($options['ssl_key'])) { + if (\count($options['ssl_key']) === 2) { + [$sslKey, $conf[\CURLOPT_SSLKEYPASSWD]] = $options['ssl_key']; + } else { + [$sslKey] = $options['ssl_key']; + } + } + + $sslKey = $sslKey ?? $options['ssl_key']; + + if (!\file_exists($sslKey)) { + throw new \InvalidArgumentException("SSL private key not found: {$sslKey}"); + } + $conf[\CURLOPT_SSLKEY] = $sslKey; + } + + if (isset($options['progress'])) { + $progress = $options['progress']; + if (!\is_callable($progress)) { + throw new \InvalidArgumentException('progress client option must be callable'); + } + $conf[\CURLOPT_NOPROGRESS] = false; + $conf[\CURLOPT_PROGRESSFUNCTION] = static function ($resource, int $downloadSize, int $downloaded, int $uploadSize, int $uploaded) use ($progress) { + $progress($downloadSize, $downloaded, $uploadSize, $uploaded); + }; + } + + if (!empty($options['debug'])) { + $conf[\CURLOPT_STDERR] = Utils::debugResource($options['debug']); + $conf[\CURLOPT_VERBOSE] = true; + } + } + + /** + * This function ensures that a response was set on a transaction. If one + * was not set, then the request is retried if possible. This error + * typically means you are sending a payload, curl encountered a + * "Connection died, retrying a fresh connect" error, tried to rewind the + * stream, and then encountered a "necessary data rewind wasn't possible" + * error, causing the request to be sent through curl_multi_info_read() + * without an error status. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + */ + private static function retryFailedRewind(callable $handler, EasyHandle $easy, array $ctx): PromiseInterface + { + try { + // Only rewind if the body has been read from. + $body = $easy->request->getBody(); + if ($body->tell() > 0) { + $body->rewind(); + } + } catch (\RuntimeException $e) { + $ctx['error'] = 'The connection unexpectedly failed without ' + . 'providing an error. The request would have been retried, ' + . 'but attempting to rewind the request body failed. ' + . 'Exception: ' . $e; + return self::createRejection($easy, $ctx); + } + + // Retry no more than 3 times before giving up. + if (!isset($easy->options['_curl_retries'])) { + $easy->options['_curl_retries'] = 1; + } elseif ($easy->options['_curl_retries'] == 2) { + $ctx['error'] = 'The cURL request was retried 3 times ' + . 'and did not succeed. The most likely reason for the failure ' + . 'is that cURL was unable to rewind the body of the request ' + . 'and subsequent retries resulted in the same error. Turn on ' + . 'the debug option to see what went wrong. See ' + . 'https://bugs.php.net/bug.php?id=47204 for more information.'; + return self::createRejection($easy, $ctx); + } else { + $easy->options['_curl_retries']++; + } + + return $handler($easy->request, $easy->options); + } + + private function createHeaderFn(EasyHandle $easy): callable + { + if (isset($easy->options['on_headers'])) { + $onHeaders = $easy->options['on_headers']; + + if (!\is_callable($onHeaders)) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + } else { + $onHeaders = null; + } + + return static function ($ch, $h) use ( + $onHeaders, + $easy, + &$startingResponse + ) { + $value = \trim($h); + if ($value === '') { + $startingResponse = true; + try { + $easy->createResponse(); + } catch (\Exception $e) { + $easy->createResponseException = $e; + return -1; + } + if ($onHeaders !== null) { + try { + $onHeaders($easy->response); + } catch (\Exception $e) { + // Associate the exception with the handle and trigger + // a curl header write error by returning 0. + $easy->onHeadersException = $e; + return -1; + } + } + } elseif ($startingResponse) { + $startingResponse = false; + $easy->headers = [$value]; + } else { + $easy->headers[] = $value; + } + return \strlen($h); + }; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php new file mode 100644 index 0000000..fe57ed5 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php @@ -0,0 +1,25 @@ +factory = $options['handle_factory'] + ?? new CurlFactory(3); + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (isset($options['delay'])) { + \usleep($options['delay'] * 1000); + } + + $easy = $this->factory->create($request, $options); + \curl_exec($easy->handle); + $easy->errno = \curl_errno($easy->handle); + + return CurlFactory::finish($this, $easy, $this->factory); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php new file mode 100644 index 0000000..4356d02 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php @@ -0,0 +1,262 @@ + An array of delay times, indexed by handle id in `addRequest`. + * + * @see CurlMultiHandler::addRequest + */ + private $delays = []; + + /** + * @var array An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt() + */ + private $options = []; + + /** + * This handler accepts the following options: + * + * - handle_factory: An optional factory used to create curl handles + * - select_timeout: Optional timeout (in seconds) to block before timing + * out while selecting curl handles. Defaults to 1 second. + * - options: An associative array of CURLMOPT_* options and + * corresponding values for curl_multi_setopt() + */ + public function __construct(array $options = []) + { + $this->factory = $options['handle_factory'] ?? new CurlFactory(50); + + if (isset($options['select_timeout'])) { + $this->selectTimeout = $options['select_timeout']; + } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { + @trigger_error('Since guzzlehttp/guzzle 7.2.0: Using environment variable GUZZLE_CURL_SELECT_TIMEOUT is deprecated. Use option "select_timeout" instead.', \E_USER_DEPRECATED); + $this->selectTimeout = (int) $selectTimeout; + } else { + $this->selectTimeout = 1; + } + + $this->options = $options['options'] ?? []; + } + + /** + * @param string $name + * + * @return resource|\CurlMultiHandle + * + * @throws \BadMethodCallException when another field as `_mh` will be gotten + * @throws \RuntimeException when curl can not initialize a multi handle + */ + public function __get($name) + { + if ($name !== '_mh') { + throw new \BadMethodCallException("Can not get other property as '_mh'."); + } + + $multiHandle = \curl_multi_init(); + + if (false === $multiHandle) { + throw new \RuntimeException('Can not initialize curl multi handle.'); + } + + $this->_mh = $multiHandle; + + foreach ($this->options as $option => $value) { + // A warning is raised in case of a wrong option. + curl_multi_setopt($this->_mh, $option, $value); + } + + return $this->_mh; + } + + public function __destruct() + { + if (isset($this->_mh)) { + \curl_multi_close($this->_mh); + unset($this->_mh); + } + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $easy = $this->factory->create($request, $options); + $id = (int) $easy->handle; + + $promise = new Promise( + [$this, 'execute'], + function () use ($id) { + return $this->cancel($id); + } + ); + + $this->addRequest(['easy' => $easy, 'deferred' => $promise]); + + return $promise; + } + + /** + * Ticks the curl event loop. + */ + public function tick(): void + { + // Add any delayed handles if needed. + if ($this->delays) { + $currentTime = Utils::currentTime(); + foreach ($this->delays as $id => $delay) { + if ($currentTime >= $delay) { + unset($this->delays[$id]); + \curl_multi_add_handle( + $this->_mh, + $this->handles[$id]['easy']->handle + ); + } + } + } + + // Step through the task queue which may add additional requests. + P\Utils::queue()->run(); + + if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) { + // Perform a usleep if a select returns -1. + // See: https://bugs.php.net/bug.php?id=61141 + \usleep(250); + } + + while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM); + + $this->processMessages(); + } + + /** + * Runs until all outstanding connections have completed. + */ + public function execute(): void + { + $queue = P\Utils::queue(); + + while ($this->handles || !$queue->isEmpty()) { + // If there are no transfers, then sleep for the next delay + if (!$this->active && $this->delays) { + \usleep($this->timeToNext()); + } + $this->tick(); + } + } + + private function addRequest(array $entry): void + { + $easy = $entry['easy']; + $id = (int) $easy->handle; + $this->handles[$id] = $entry; + if (empty($easy->options['delay'])) { + \curl_multi_add_handle($this->_mh, $easy->handle); + } else { + $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000); + } + } + + /** + * Cancels a handle from sending and removes references to it. + * + * @param int $id Handle ID to cancel and remove. + * + * @return bool True on success, false on failure. + */ + private function cancel($id): bool + { + if (!is_int($id)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an integer to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + // Cannot cancel if it has been processed. + if (!isset($this->handles[$id])) { + return false; + } + + $handle = $this->handles[$id]['easy']->handle; + unset($this->delays[$id], $this->handles[$id]); + \curl_multi_remove_handle($this->_mh, $handle); + \curl_close($handle); + + return true; + } + + private function processMessages(): void + { + while ($done = \curl_multi_info_read($this->_mh)) { + if ($done['msg'] !== \CURLMSG_DONE) { + // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216 + continue; + } + $id = (int) $done['handle']; + \curl_multi_remove_handle($this->_mh, $done['handle']); + + if (!isset($this->handles[$id])) { + // Probably was cancelled. + continue; + } + + $entry = $this->handles[$id]; + unset($this->handles[$id], $this->delays[$id]); + $entry['easy']->errno = $done['result']; + $entry['deferred']->resolve( + CurlFactory::finish($this, $entry['easy'], $this->factory) + ); + } + } + + private function timeToNext(): int + { + $currentTime = Utils::currentTime(); + $nextTime = \PHP_INT_MAX; + foreach ($this->delays as $time) { + if ($time < $nextTime) { + $nextTime = $time; + } + } + + return ((int) \max(0, $nextTime - $currentTime)) * 1000000; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php new file mode 100644 index 0000000..224344d --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/EasyHandle.php @@ -0,0 +1,112 @@ +headers); + + $normalizedKeys = Utils::normalizeHeaderKeys($headers); + + if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding'])) { + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + unset($headers[$normalizedKeys['content-encoding']]); + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; + + $bodyLength = (int) $this->sink->getSize(); + if ($bodyLength) { + $headers[$normalizedKeys['content-length']] = $bodyLength; + } else { + unset($headers[$normalizedKeys['content-length']]); + } + } + } + + // Attach a response to the easy handle with the parsed headers. + $this->response = new Response( + $status, + $headers, + $this->sink, + $ver, + $reason + ); + } + + /** + * @param string $name + * + * @return void + * + * @throws \BadMethodCallException + */ + public function __get($name) + { + $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: ' . $name; + throw new \BadMethodCallException($msg); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php new file mode 100644 index 0000000..a098884 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php @@ -0,0 +1,42 @@ +|null $queue The parameters to be passed to the append function, as an indexed array. + * @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled. + * @param callable|null $onRejected Callback to invoke when the return value is rejected. + */ + public function __construct(array $queue = null, callable $onFulfilled = null, callable $onRejected = null) + { + $this->onFulfilled = $onFulfilled; + $this->onRejected = $onRejected; + + if ($queue) { + // array_values included for BC + $this->append(...array_values($queue)); + } + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (!$this->queue) { + throw new \OutOfBoundsException('Mock queue is empty'); + } + + if (isset($options['delay']) && \is_numeric($options['delay'])) { + \usleep((int) $options['delay'] * 1000); + } + + $this->lastRequest = $request; + $this->lastOptions = $options; + $response = \array_shift($this->queue); + + if (isset($options['on_headers'])) { + if (!\is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + try { + $options['on_headers']($response); + } catch (\Exception $e) { + $msg = 'An error was encountered during the on_headers event'; + $response = new RequestException($msg, $request, $response, $e); + } + } + + if (\is_callable($response)) { + $response = $response($request, $options); + } + + $response = $response instanceof \Throwable + ? P\Create::rejectionFor($response) + : P\Create::promiseFor($response); + + return $response->then( + function (?ResponseInterface $value) use ($request, $options) { + $this->invokeStats($request, $options, $value); + if ($this->onFulfilled) { + ($this->onFulfilled)($value); + } + + if ($value !== null && isset($options['sink'])) { + $contents = (string) $value->getBody(); + $sink = $options['sink']; + + if (\is_resource($sink)) { + \fwrite($sink, $contents); + } elseif (\is_string($sink)) { + \file_put_contents($sink, $contents); + } elseif ($sink instanceof StreamInterface) { + $sink->write($contents); + } + } + + return $value; + }, + function ($reason) use ($request, $options) { + $this->invokeStats($request, $options, null, $reason); + if ($this->onRejected) { + ($this->onRejected)($reason); + } + return P\Create::rejectionFor($reason); + } + ); + } + + /** + * Adds one or more variadic requests, exceptions, callables, or promises + * to the queue. + * + * @param mixed ...$values + */ + public function append(...$values): void + { + foreach ($values as $value) { + if ($value instanceof ResponseInterface + || $value instanceof \Throwable + || $value instanceof PromiseInterface + || \is_callable($value) + ) { + $this->queue[] = $value; + } else { + throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found ' . Utils::describeType($value)); + } + } + } + + /** + * Get the last received request. + */ + public function getLastRequest(): ?RequestInterface + { + return $this->lastRequest; + } + + /** + * Get the last received request options. + */ + public function getLastOptions(): array + { + return $this->lastOptions; + } + + /** + * Returns the number of remaining items in the queue. + */ + public function count(): int + { + return \count($this->queue); + } + + public function reset(): void + { + $this->queue = []; + } + + /** + * @param mixed $reason Promise or reason. + */ + private function invokeStats( + RequestInterface $request, + array $options, + ResponseInterface $response = null, + $reason = null + ): void { + if (isset($options['on_stats'])) { + $transferTime = $options['transfer_time'] ?? 0; + $stats = new TransferStats($request, $response, $transferTime, $reason); + ($options['on_stats'])($stats); + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php new file mode 100644 index 0000000..f045b52 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php @@ -0,0 +1,51 @@ +withoutHeader('Expect'); + + // Append a content-length header if body size is zero to match + // cURL's behavior. + if (0 === $request->getBody()->getSize()) { + $request = $request->withHeader('Content-Length', '0'); + } + + return $this->createResponse( + $request, + $options, + $this->createStream($request, $options), + $startTime + ); + } catch (\InvalidArgumentException $e) { + throw $e; + } catch (\Exception $e) { + // Determine if the error was a networking error. + $message = $e->getMessage(); + // This list can probably get more comprehensive. + if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed + || false !== \strpos($message, 'Connection refused') + || false !== \strpos($message, "couldn't connect to host") // error on HHVM + || false !== \strpos($message, "connection attempt failed") + ) { + $e = new ConnectException($e->getMessage(), $request, $e); + } else { + $e = RequestException::wrapException($request, $e); + } + $this->invokeStats($options, $request, $startTime, null, $e); + + return P\Create::rejectionFor($e); + } + } + + private function invokeStats( + array $options, + RequestInterface $request, + ?float $startTime, + ResponseInterface $response = null, + \Throwable $error = null + ): void { + if (isset($options['on_stats'])) { + $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []); + ($options['on_stats'])($stats); + } + } + + /** + * @param resource $stream + */ + private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime): PromiseInterface + { + $hdrs = $this->lastHeaders; + $this->lastHeaders = []; + + try { + [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered while creating the response', $request, null, $e) + ); + } + + [$stream, $headers] = $this->checkDecode($options, $headers, $stream); + $stream = Psr7\Utils::streamFor($stream); + $sink = $stream; + + if (\strcasecmp('HEAD', $request->getMethod())) { + $sink = $this->createSink($stream, $options); + } + + try { + $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered while creating the response', $request, null, $e) + ); + } + + if (isset($options['on_headers'])) { + try { + $options['on_headers']($response); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered during the on_headers event', $request, $response, $e) + ); + } + } + + // Do not drain when the request is a HEAD request because they have + // no body. + if ($sink !== $stream) { + $this->drain($stream, $sink, $response->getHeaderLine('Content-Length')); + } + + $this->invokeStats($options, $request, $startTime, $response, null); + + return new FulfilledPromise($response); + } + + private function createSink(StreamInterface $stream, array $options): StreamInterface + { + if (!empty($options['stream'])) { + return $stream; + } + + $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+'); + + return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink); + } + + /** + * @param resource $stream + */ + private function checkDecode(array $options, array $headers, $stream): array + { + // Automatically decode responses when instructed. + if (!empty($options['decode_content'])) { + $normalizedKeys = Utils::normalizeHeaderKeys($headers); + if (isset($normalizedKeys['content-encoding'])) { + $encoding = $headers[$normalizedKeys['content-encoding']]; + if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { + $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream)); + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + + // Remove content-encoding header + unset($headers[$normalizedKeys['content-encoding']]); + + // Fix content-length header + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; + $length = (int) $stream->getSize(); + if ($length === 0) { + unset($headers[$normalizedKeys['content-length']]); + } else { + $headers[$normalizedKeys['content-length']] = [$length]; + } + } + } + } + } + + return [$stream, $headers]; + } + + /** + * Drains the source stream into the "sink" client option. + * + * @param string $contentLength Header specifying the amount of + * data to read. + * + * @throws \RuntimeException when the sink option is invalid. + */ + private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength): StreamInterface + { + // If a content-length header is provided, then stop reading once + // that number of bytes has been read. This can prevent infinitely + // reading from a stream when dealing with servers that do not honor + // Connection: Close headers. + Psr7\Utils::copyToStream( + $source, + $sink, + (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 + ); + + $sink->seek(0); + $source->close(); + + return $sink; + } + + /** + * Create a resource and check to ensure it was created successfully + * + * @param callable $callback Callable that returns stream resource + * + * @return resource + * + * @throws \RuntimeException on error + */ + private function createResource(callable $callback) + { + $errors = []; + \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool { + $errors[] = [ + 'message' => $msg, + 'file' => $file, + 'line' => $line + ]; + return true; + }); + + try { + $resource = $callback(); + } finally { + \restore_error_handler(); + } + + if (!$resource) { + $message = 'Error creating resource: '; + foreach ($errors as $err) { + foreach ($err as $key => $value) { + $message .= "[$key] $value" . \PHP_EOL; + } + } + throw new \RuntimeException(\trim($message)); + } + + return $resource; + } + + /** + * @return resource + */ + private function createStream(RequestInterface $request, array $options) + { + static $methods; + if (!$methods) { + $methods = \array_flip(\get_class_methods(__CLASS__)); + } + + if (!\in_array($request->getUri()->getScheme(), ['http', 'https'])) { + throw new RequestException(\sprintf("The scheme '%s' is not supported.", $request->getUri()->getScheme()), $request); + } + + // HTTP/1.1 streams using the PHP stream wrapper require a + // Connection: close header + if ($request->getProtocolVersion() == '1.1' + && !$request->hasHeader('Connection') + ) { + $request = $request->withHeader('Connection', 'close'); + } + + // Ensure SSL is verified by default + if (!isset($options['verify'])) { + $options['verify'] = true; + } + + $params = []; + $context = $this->getDefaultContext($request); + + if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + + if (!empty($options)) { + foreach ($options as $key => $value) { + $method = "add_{$key}"; + if (isset($methods[$method])) { + $this->{$method}($request, $context, $value, $params); + } + } + } + + if (isset($options['stream_context'])) { + if (!\is_array($options['stream_context'])) { + throw new \InvalidArgumentException('stream_context must be an array'); + } + $context = \array_replace_recursive($context, $options['stream_context']); + } + + // Microsoft NTLM authentication only supported with curl handler + if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) { + throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); + } + + $uri = $this->resolveHost($request, $options); + + $contextResource = $this->createResource( + static function () use ($context, $params) { + return \stream_context_create($context, $params); + } + ); + + return $this->createResource( + function () use ($uri, &$http_response_header, $contextResource, $context, $options, $request) { + $resource = @\fopen((string) $uri, 'r', false, $contextResource); + $this->lastHeaders = $http_response_header ?? []; + + if (false === $resource) { + throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context); + } + + if (isset($options['read_timeout'])) { + $readTimeout = $options['read_timeout']; + $sec = (int) $readTimeout; + $usec = ($readTimeout - $sec) * 100000; + \stream_set_timeout($resource, $sec, $usec); + } + + return $resource; + } + ); + } + + private function resolveHost(RequestInterface $request, array $options): UriInterface + { + $uri = $request->getUri(); + + if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) { + if ('v4' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_A); + if (false === $records || !isset($records[0]['ip'])) { + throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); + } + return $uri->withHost($records[0]['ip']); + } + if ('v6' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_AAAA); + if (false === $records || !isset($records[0]['ipv6'])) { + throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); + } + return $uri->withHost('[' . $records[0]['ipv6'] . ']'); + } + } + + return $uri; + } + + private function getDefaultContext(RequestInterface $request): array + { + $headers = ''; + foreach ($request->getHeaders() as $name => $value) { + foreach ($value as $val) { + $headers .= "$name: $val\r\n"; + } + } + + $context = [ + 'http' => [ + 'method' => $request->getMethod(), + 'header' => $headers, + 'protocol_version' => $request->getProtocolVersion(), + 'ignore_errors' => true, + 'follow_location' => 0, + ], + 'ssl' => [ + 'peer_name' => $request->getUri()->getHost(), + ], + ]; + + $body = (string) $request->getBody(); + + if (!empty($body)) { + $context['http']['content'] = $body; + // Prevent the HTTP handler from adding a Content-Type header. + if (!$request->hasHeader('Content-Type')) { + $context['http']['header'] .= "Content-Type:\r\n"; + } + } + + $context['http']['header'] = \rtrim($context['http']['header']); + + return $context; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void + { + $uri = null; + + if (!\is_array($value)) { + $uri = $value; + } else { + $scheme = $request->getUri()->getScheme(); + if (isset($value[$scheme])) { + if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) { + $uri = $value[$scheme]; + } + } + } + + if (!$uri) { + return; + } + + $parsed = $this->parse_proxy($uri); + $options['http']['proxy'] = $parsed['proxy']; + + if ($parsed['auth']) { + if (!isset($options['http']['header'])) { + $options['http']['header'] = []; + } + $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}"; + } + } + + /** + * Parses the given proxy URL to make it compatible with the format PHP's stream context expects. + */ + private function parse_proxy(string $url): array + { + $parsed = \parse_url($url); + + if ($parsed !== false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') { + if (isset($parsed['host']) && isset($parsed['port'])) { + $auth = null; + if (isset($parsed['user']) && isset($parsed['pass'])) { + $auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}"); + } + + return [ + 'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}", + 'auth' => $auth ? "Basic {$auth}" : null, + ]; + } + } + + // Return proxy as-is. + return [ + 'proxy' => $url, + 'auth' => null, + ]; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value > 0) { + $options['http']['timeout'] = $value; + } + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value === false) { + $options['ssl']['verify_peer'] = false; + $options['ssl']['verify_peer_name'] = false; + + return; + } + + if (\is_string($value)) { + $options['ssl']['cafile'] = $value; + if (!\file_exists($value)) { + throw new \RuntimeException("SSL CA bundle not found: $value"); + } + } elseif ($value !== true) { + throw new \InvalidArgumentException('Invalid verify request option'); + } + + $options['ssl']['verify_peer'] = true; + $options['ssl']['verify_peer_name'] = true; + $options['ssl']['allow_self_signed'] = false; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void + { + if (\is_array($value)) { + $options['ssl']['passphrase'] = $value[1]; + $value = $value[0]; + } + + if (!\file_exists($value)) { + throw new \RuntimeException("SSL certificate not found: {$value}"); + } + + $options['ssl']['local_cert'] = $value; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void + { + self::addNotification( + $params, + static function ($code, $a, $b, $c, $transferred, $total) use ($value) { + if ($code == \STREAM_NOTIFY_PROGRESS) { + // The upload progress cannot be determined. Use 0 for cURL compatibility: + // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html + $value($total, $transferred, 0, 0); + } + } + ); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value === false) { + return; + } + + static $map = [ + \STREAM_NOTIFY_CONNECT => 'CONNECT', + \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', + \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', + \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', + \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', + \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', + \STREAM_NOTIFY_PROGRESS => 'PROGRESS', + \STREAM_NOTIFY_FAILURE => 'FAILURE', + \STREAM_NOTIFY_COMPLETED => 'COMPLETED', + \STREAM_NOTIFY_RESOLVE => 'RESOLVE', + ]; + static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; + + $value = Utils::debugResource($value); + $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment(''); + self::addNotification( + $params, + static function (int $code, ...$passed) use ($ident, $value, $map, $args): void { + \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); + foreach (\array_filter($passed) as $i => $v) { + \fwrite($value, $args[$i] . ': "' . $v . '" '); + } + \fwrite($value, "\n"); + } + ); + } + + private static function addNotification(array &$params, callable $notify): void + { + // Wrap the existing function if needed. + if (!isset($params['notification'])) { + $params['notification'] = $notify; + } else { + $params['notification'] = self::callArray([ + $params['notification'], + $notify + ]); + } + } + + private static function callArray(array $functions): callable + { + return static function (...$args) use ($functions) { + foreach ($functions as $fn) { + $fn(...$args); + } + }; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/HandlerStack.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/HandlerStack.php new file mode 100644 index 0000000..e0a1d11 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/HandlerStack.php @@ -0,0 +1,275 @@ +push(Middleware::httpErrors(), 'http_errors'); + $stack->push(Middleware::redirect(), 'allow_redirects'); + $stack->push(Middleware::cookies(), 'cookies'); + $stack->push(Middleware::prepareBody(), 'prepare_body'); + + return $stack; + } + + /** + * @param (callable(RequestInterface, array): PromiseInterface)|null $handler Underlying HTTP handler. + */ + public function __construct(callable $handler = null) + { + $this->handler = $handler; + } + + /** + * Invokes the handler stack as a composed handler + * + * @return ResponseInterface|PromiseInterface + */ + public function __invoke(RequestInterface $request, array $options) + { + $handler = $this->resolve(); + + return $handler($request, $options); + } + + /** + * Dumps a string representation of the stack. + * + * @return string + */ + public function __toString() + { + $depth = 0; + $stack = []; + + if ($this->handler !== null) { + $stack[] = "0) Handler: " . $this->debugCallable($this->handler); + } + + $result = ''; + foreach (\array_reverse($this->stack) as $tuple) { + $depth++; + $str = "{$depth}) Name: '{$tuple[1]}', "; + $str .= "Function: " . $this->debugCallable($tuple[0]); + $result = "> {$str}\n{$result}"; + $stack[] = $str; + } + + foreach (\array_keys($stack) as $k) { + $result .= "< {$stack[$k]}\n"; + } + + return $result; + } + + /** + * Set the HTTP handler that actually returns a promise. + * + * @param callable(RequestInterface, array): PromiseInterface $handler Accepts a request and array of options and + * returns a Promise. + */ + public function setHandler(callable $handler): void + { + $this->handler = $handler; + $this->cached = null; + } + + /** + * Returns true if the builder has a handler. + */ + public function hasHandler(): bool + { + return $this->handler !== null ; + } + + /** + * Unshift a middleware to the bottom of the stack. + * + * @param callable(callable): callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function unshift(callable $middleware, ?string $name = null): void + { + \array_unshift($this->stack, [$middleware, $name]); + $this->cached = null; + } + + /** + * Push a middleware to the top of the stack. + * + * @param callable(callable): callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function push(callable $middleware, string $name = ''): void + { + $this->stack[] = [$middleware, $name]; + $this->cached = null; + } + + /** + * Add a middleware before another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable): callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function before(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, true); + } + + /** + * Add a middleware after another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable): callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function after(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, false); + } + + /** + * Remove a middleware by instance or name from the stack. + * + * @param callable|string $remove Middleware to remove by instance or name. + */ + public function remove($remove): void + { + if (!is_string($remove) && !is_callable($remove)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a callable or string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->cached = null; + $idx = \is_callable($remove) ? 0 : 1; + $this->stack = \array_values(\array_filter( + $this->stack, + static function ($tuple) use ($idx, $remove) { + return $tuple[$idx] !== $remove; + } + )); + } + + /** + * Compose the middleware and handler into a single callable function. + * + * @return callable(RequestInterface, array): PromiseInterface + */ + public function resolve(): callable + { + if ($this->cached === null) { + if (($prev = $this->handler) === null) { + throw new \LogicException('No handler has been specified'); + } + + foreach (\array_reverse($this->stack) as $fn) { + /** @var callable(RequestInterface, array): PromiseInterface $prev */ + $prev = $fn[0]($prev); + } + + $this->cached = $prev; + } + + return $this->cached; + } + + private function findByName(string $name): int + { + foreach ($this->stack as $k => $v) { + if ($v[1] === $name) { + return $k; + } + } + + throw new \InvalidArgumentException("Middleware not found: $name"); + } + + /** + * Splices a function into the middleware list at a specific position. + */ + private function splice(string $findName, string $withName, callable $middleware, bool $before): void + { + $this->cached = null; + $idx = $this->findByName($findName); + $tuple = [$middleware, $withName]; + + if ($before) { + if ($idx === 0) { + \array_unshift($this->stack, $tuple); + } else { + $replacement = [$tuple, $this->stack[$idx]]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } elseif ($idx === \count($this->stack) - 1) { + $this->stack[] = $tuple; + } else { + $replacement = [$this->stack[$idx], $tuple]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } + + /** + * Provides a debug string for a given callable. + * + * @param callable|string $fn Function to write as a string. + */ + private function debugCallable($fn): string + { + if (\is_string($fn)) { + return "callable({$fn})"; + } + + if (\is_array($fn)) { + return \is_string($fn[0]) + ? "callable({$fn[0]}::{$fn[1]})" + : "callable(['" . \get_class($fn[0]) . "', '{$fn[1]}'])"; + } + + /** @var object $fn */ + return 'callable(' . \spl_object_hash($fn) . ')'; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/MessageFormatter.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/MessageFormatter.php new file mode 100644 index 0000000..da49954 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/MessageFormatter.php @@ -0,0 +1,198 @@ +>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}"; + public const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}'; + + /** + * @var string Template used to format log messages + */ + private $template; + + /** + * @param string $template Log message template + */ + public function __construct(?string $template = self::CLF) + { + $this->template = $template ?: self::CLF; + } + + /** + * Returns a formatted message string. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface|null $response Response that was received + * @param \Throwable|null $error Exception that was received + */ + public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): string + { + $cache = []; + + /** @var string */ + return \preg_replace_callback( + '/{\s*([A-Za-z_\-\.0-9]+)\s*}/', + function (array $matches) use ($request, $response, $error, &$cache) { + if (isset($cache[$matches[1]])) { + return $cache[$matches[1]]; + } + + $result = ''; + switch ($matches[1]) { + case 'request': + $result = Psr7\Message::toString($request); + break; + case 'response': + $result = $response ? Psr7\Message::toString($response) : ''; + break; + case 'req_headers': + $result = \trim($request->getMethod() + . ' ' . $request->getRequestTarget()) + . ' HTTP/' . $request->getProtocolVersion() . "\r\n" + . $this->headers($request); + break; + case 'res_headers': + $result = $response ? + \sprintf( + 'HTTP/%s %d %s', + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() + ) . "\r\n" . $this->headers($response) + : 'NULL'; + break; + case 'req_body': + $result = $request->getBody()->__toString(); + break; + case 'res_body': + if (!$response instanceof ResponseInterface) { + $result = 'NULL'; + break; + } + + $body = $response->getBody(); + + if (!$body->isSeekable()) { + $result = 'RESPONSE_NOT_LOGGEABLE'; + break; + } + + $result = $response->getBody()->__toString(); + break; + case 'ts': + case 'date_iso_8601': + $result = \gmdate('c'); + break; + case 'date_common_log': + $result = \date('d/M/Y:H:i:s O'); + break; + case 'method': + $result = $request->getMethod(); + break; + case 'version': + $result = $request->getProtocolVersion(); + break; + case 'uri': + case 'url': + $result = $request->getUri()->__toString(); + break; + case 'target': + $result = $request->getRequestTarget(); + break; + case 'req_version': + $result = $request->getProtocolVersion(); + break; + case 'res_version': + $result = $response + ? $response->getProtocolVersion() + : 'NULL'; + break; + case 'host': + $result = $request->getHeaderLine('Host'); + break; + case 'hostname': + $result = \gethostname(); + break; + case 'code': + $result = $response ? $response->getStatusCode() : 'NULL'; + break; + case 'phrase': + $result = $response ? $response->getReasonPhrase() : 'NULL'; + break; + case 'error': + $result = $error ? $error->getMessage() : 'NULL'; + break; + default: + // handle prefixed dynamic headers + if (\strpos($matches[1], 'req_header_') === 0) { + $result = $request->getHeaderLine(\substr($matches[1], 11)); + } elseif (\strpos($matches[1], 'res_header_') === 0) { + $result = $response + ? $response->getHeaderLine(\substr($matches[1], 11)) + : 'NULL'; + } + } + + $cache[$matches[1]] = $result; + return $result; + }, + $this->template + ); + } + + /** + * Get headers from message as string + */ + private function headers(MessageInterface $message): string + { + $result = ''; + foreach ($message->getHeaders() as $name => $values) { + $result .= $name . ': ' . \implode(', ', $values) . "\r\n"; + } + + return \trim($result); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php new file mode 100644 index 0000000..a39ac24 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/MessageFormatterInterface.php @@ -0,0 +1,18 @@ +withCookieHeader($request); + return $handler($request, $options) + ->then( + static function (ResponseInterface $response) use ($cookieJar, $request): ResponseInterface { + $cookieJar->extractCookies($request, $response); + return $response; + } + ); + }; + }; + } + + /** + * Middleware that throws exceptions for 4xx or 5xx responses when the + * "http_errors" request option is set to true. + * + * @param BodySummarizerInterface|null $bodySummarizer The body summarizer to use in exception messages. + * + * @return callable(callable): callable Returns a function that accepts the next handler. + */ + public static function httpErrors(BodySummarizerInterface $bodySummarizer = null): callable + { + return static function (callable $handler) use ($bodySummarizer): callable { + return static function ($request, array $options) use ($handler, $bodySummarizer) { + if (empty($options['http_errors'])) { + return $handler($request, $options); + } + return $handler($request, $options)->then( + static function (ResponseInterface $response) use ($request, $bodySummarizer) { + $code = $response->getStatusCode(); + if ($code < 400) { + return $response; + } + throw RequestException::create($request, $response, null, [], $bodySummarizer); + } + ); + }; + }; + } + + /** + * Middleware that pushes history data to an ArrayAccess container. + * + * @param array|\ArrayAccess $container Container to hold the history (by reference). + * + * @return callable(callable): callable Returns a function that accepts the next handler. + * + * @throws \InvalidArgumentException if container is not an array or ArrayAccess. + */ + public static function history(&$container): callable + { + if (!\is_array($container) && !$container instanceof \ArrayAccess) { + throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess'); + } + + return static function (callable $handler) use (&$container): callable { + return static function (RequestInterface $request, array $options) use ($handler, &$container) { + return $handler($request, $options)->then( + static function ($value) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => $value, + 'error' => null, + 'options' => $options + ]; + return $value; + }, + static function ($reason) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => null, + 'error' => $reason, + 'options' => $options + ]; + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * Middleware that invokes a callback before and after sending a request. + * + * The provided listener cannot modify or alter the response. It simply + * "taps" into the chain to be notified before returning the promise. The + * before listener accepts a request and options array, and the after + * listener accepts a request, options array, and response promise. + * + * @param callable $before Function to invoke before forwarding the request. + * @param callable $after Function invoked after forwarding. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function tap(callable $before = null, callable $after = null): callable + { + return static function (callable $handler) use ($before, $after): callable { + return static function (RequestInterface $request, array $options) use ($handler, $before, $after) { + if ($before) { + $before($request, $options); + } + $response = $handler($request, $options); + if ($after) { + $after($request, $options, $response); + } + return $response; + }; + }; + } + + /** + * Middleware that handles request redirects. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function redirect(): callable + { + return static function (callable $handler): RedirectMiddleware { + return new RedirectMiddleware($handler); + }; + } + + /** + * Middleware that retries requests based on the boolean result of + * invoking the provided "decider" function. + * + * If no delay function is provided, a simple implementation of exponential + * backoff will be utilized. + * + * @param callable $decider Function that accepts the number of retries, + * a request, [response], and [exception] and + * returns true if the request is to be retried. + * @param callable $delay Function that accepts the number of retries and + * returns the number of milliseconds to delay. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function retry(callable $decider, callable $delay = null): callable + { + return static function (callable $handler) use ($decider, $delay): RetryMiddleware { + return new RetryMiddleware($decider, $handler, $delay); + }; + } + + /** + * Middleware that logs requests, responses, and errors using a message + * formatter. + * + * @phpstan-param \Psr\Log\LogLevel::* $logLevel Level at which to log requests. + * + * @param LoggerInterface $logger Logs messages. + * @param MessageFormatterInterface|MessageFormatter $formatter Formatter used to create message strings. + * @param string $logLevel Level at which to log requests. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function log(LoggerInterface $logger, $formatter, string $logLevel = 'info'): callable + { + // To be compatible with Guzzle 7.1.x we need to allow users to pass a MessageFormatter + if (!$formatter instanceof MessageFormatter && !$formatter instanceof MessageFormatterInterface) { + throw new \LogicException(sprintf('Argument 2 to %s::log() must be of type %s', self::class, MessageFormatterInterface::class)); + } + + return static function (callable $handler) use ($logger, $formatter, $logLevel): callable { + return static function (RequestInterface $request, array $options = []) use ($handler, $logger, $formatter, $logLevel) { + return $handler($request, $options)->then( + static function ($response) use ($logger, $request, $formatter, $logLevel): ResponseInterface { + $message = $formatter->format($request, $response); + $logger->log($logLevel, $message); + return $response; + }, + static function ($reason) use ($logger, $request, $formatter): PromiseInterface { + $response = $reason instanceof RequestException ? $reason->getResponse() : null; + $message = $formatter->format($request, $response, P\Create::exceptionFor($reason)); + $logger->error($message); + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * This middleware adds a default content-type if possible, a default + * content-length or transfer-encoding header, and the expect header. + */ + public static function prepareBody(): callable + { + return static function (callable $handler): PrepareBodyMiddleware { + return new PrepareBodyMiddleware($handler); + }; + } + + /** + * Middleware that applies a map function to the request before passing to + * the next handler. + * + * @param callable $fn Function that accepts a RequestInterface and returns + * a RequestInterface. + */ + public static function mapRequest(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function (RequestInterface $request, array $options) use ($handler, $fn) { + return $handler($fn($request), $options); + }; + }; + } + + /** + * Middleware that applies a map function to the resolved promise's + * response. + * + * @param callable $fn Function that accepts a ResponseInterface and + * returns a ResponseInterface. + */ + public static function mapResponse(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function (RequestInterface $request, array $options) use ($handler, $fn) { + return $handler($request, $options)->then($fn); + }; + }; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Pool.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Pool.php new file mode 100644 index 0000000..6277c61 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Pool.php @@ -0,0 +1,125 @@ + $rfn) { + if ($rfn instanceof RequestInterface) { + yield $key => $client->sendAsync($rfn, $opts); + } elseif (\is_callable($rfn)) { + yield $key => $rfn($opts); + } else { + throw new \InvalidArgumentException('Each value yielded by the iterator must be a Psr7\Http\Message\RequestInterface or a callable that returns a promise that fulfills with a Psr7\Message\Http\ResponseInterface object.'); + } + } + }; + + $this->each = new EachPromise($requests(), $config); + } + + /** + * Get promise + */ + public function promise(): PromiseInterface + { + return $this->each->promise(); + } + + /** + * Sends multiple requests concurrently and returns an array of responses + * and exceptions that uses the same ordering as the provided requests. + * + * IMPORTANT: This method keeps every request and response in memory, and + * as such, is NOT recommended when sending a large number or an + * indeterminate number of requests concurrently. + * + * @param ClientInterface $client Client used to send the requests + * @param array|\Iterator $requests Requests to send concurrently. + * @param array $options Passes through the options available in + * {@see \GuzzleHttp\Pool::__construct} + * + * @return array Returns an array containing the response or an exception + * in the same order that the requests were sent. + * + * @throws \InvalidArgumentException if the event format is incorrect. + */ + public static function batch(ClientInterface $client, $requests, array $options = []): array + { + $res = []; + self::cmpCallback($options, 'fulfilled', $res); + self::cmpCallback($options, 'rejected', $res); + $pool = new static($client, $requests, $options); + $pool->promise()->wait(); + \ksort($res); + + return $res; + } + + /** + * Execute callback(s) + */ + private static function cmpCallback(array &$options, string $name, array &$results): void + { + if (!isset($options[$name])) { + $options[$name] = static function ($v, $k) use (&$results) { + $results[$k] = $v; + }; + } else { + $currentFn = $options[$name]; + $options[$name] = static function ($v, $k) use (&$results, $currentFn) { + $currentFn($v, $k); + $results[$k] = $v; + }; + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php new file mode 100644 index 0000000..7ca6283 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php @@ -0,0 +1,104 @@ +nextHandler = $nextHandler; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $fn = $this->nextHandler; + + // Don't do anything if the request has no body. + if ($request->getBody()->getSize() === 0) { + return $fn($request, $options); + } + + $modify = []; + + // Add a default content-type if possible. + if (!$request->hasHeader('Content-Type')) { + if ($uri = $request->getBody()->getMetadata('uri')) { + if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) { + $modify['set_headers']['Content-Type'] = $type; + } + } + } + + // Add a default content-length or transfer-encoding header. + if (!$request->hasHeader('Content-Length') + && !$request->hasHeader('Transfer-Encoding') + ) { + $size = $request->getBody()->getSize(); + if ($size !== null) { + $modify['set_headers']['Content-Length'] = $size; + } else { + $modify['set_headers']['Transfer-Encoding'] = 'chunked'; + } + } + + // Add the expect header if needed. + $this->addExpectHeader($request, $options, $modify); + + return $fn(Psr7\Utils::modifyRequest($request, $modify), $options); + } + + /** + * Add expect header + */ + private function addExpectHeader(RequestInterface $request, array $options, array &$modify): void + { + // Determine if the Expect header should be used + if ($request->hasHeader('Expect')) { + return; + } + + $expect = $options['expect'] ?? null; + + // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 + if ($expect === false || $request->getProtocolVersion() < 1.1) { + return; + } + + // The expect header is unconditionally enabled + if ($expect === true) { + $modify['set_headers']['Expect'] = '100-Continue'; + return; + } + + // By default, send the expect header when the payload is > 1mb + if ($expect === null) { + $expect = 1048576; + } + + // Always add if the body cannot be rewound, the size cannot be + // determined, or the size is greater than the cutoff threshold + $body = $request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { + $modify['set_headers']['Expect'] = '100-Continue'; + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php new file mode 100644 index 0000000..f67d448 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php @@ -0,0 +1,228 @@ + 5, + 'protocols' => ['http', 'https'], + 'strict' => false, + 'referer' => false, + 'track_redirects' => false, + ]; + + /** + * @var callable(RequestInterface, array): PromiseInterface + */ + private $nextHandler; + + /** + * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. + */ + public function __construct(callable $nextHandler) + { + $this->nextHandler = $nextHandler; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $fn = $this->nextHandler; + + if (empty($options['allow_redirects'])) { + return $fn($request, $options); + } + + if ($options['allow_redirects'] === true) { + $options['allow_redirects'] = self::$defaultSettings; + } elseif (!\is_array($options['allow_redirects'])) { + throw new \InvalidArgumentException('allow_redirects must be true, false, or array'); + } else { + // Merge the default settings with the provided settings + $options['allow_redirects'] += self::$defaultSettings; + } + + if (empty($options['allow_redirects']['max'])) { + return $fn($request, $options); + } + + return $fn($request, $options) + ->then(function (ResponseInterface $response) use ($request, $options) { + return $this->checkRedirect($request, $options, $response); + }); + } + + /** + * @return ResponseInterface|PromiseInterface + */ + public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response) + { + if (\strpos((string) $response->getStatusCode(), '3') !== 0 + || !$response->hasHeader('Location') + ) { + return $response; + } + + $this->guardMax($request, $response, $options); + $nextRequest = $this->modifyRequest($request, $options, $response); + + // If authorization is handled by curl, unset it if URI is cross-origin. + if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $nextRequest->getUri()) && defined('\CURLOPT_HTTPAUTH')) { + unset( + $options['curl'][\CURLOPT_HTTPAUTH], + $options['curl'][\CURLOPT_USERPWD] + ); + } + + if (isset($options['allow_redirects']['on_redirect'])) { + ($options['allow_redirects']['on_redirect'])( + $request, + $response, + $nextRequest->getUri() + ); + } + + $promise = $this($nextRequest, $options); + + // Add headers to be able to track history of redirects. + if (!empty($options['allow_redirects']['track_redirects'])) { + return $this->withTracking( + $promise, + (string) $nextRequest->getUri(), + $response->getStatusCode() + ); + } + + return $promise; + } + + /** + * Enable tracking on promise. + */ + private function withTracking(PromiseInterface $promise, string $uri, int $statusCode): PromiseInterface + { + return $promise->then( + static function (ResponseInterface $response) use ($uri, $statusCode) { + // Note that we are pushing to the front of the list as this + // would be an earlier response than what is currently present + // in the history header. + $historyHeader = $response->getHeader(self::HISTORY_HEADER); + $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); + \array_unshift($historyHeader, $uri); + \array_unshift($statusHeader, (string) $statusCode); + + return $response->withHeader(self::HISTORY_HEADER, $historyHeader) + ->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); + } + ); + } + + /** + * Check for too many redirects. + * + * @throws TooManyRedirectsException Too many redirects. + */ + private function guardMax(RequestInterface $request, ResponseInterface $response, array &$options): void + { + $current = $options['__redirect_count'] + ?? 0; + $options['__redirect_count'] = $current + 1; + $max = $options['allow_redirects']['max']; + + if ($options['__redirect_count'] > $max) { + throw new TooManyRedirectsException("Will not follow more than {$max} redirects", $request, $response); + } + } + + public function modifyRequest(RequestInterface $request, array $options, ResponseInterface $response): RequestInterface + { + // Request modifications to apply. + $modify = []; + $protocols = $options['allow_redirects']['protocols']; + + // Use a GET request if this is an entity enclosing request and we are + // not forcing RFC compliance, but rather emulating what all browsers + // would do. + $statusCode = $response->getStatusCode(); + if ($statusCode == 303 || + ($statusCode <= 302 && !$options['allow_redirects']['strict']) + ) { + $safeMethods = ['GET', 'HEAD', 'OPTIONS']; + $requestMethod = $request->getMethod(); + + $modify['method'] = in_array($requestMethod, $safeMethods) ? $requestMethod : 'GET'; + $modify['body'] = ''; + } + + $uri = self::redirectUri($request, $response, $protocols); + if (isset($options['idn_conversion']) && ($options['idn_conversion'] !== false)) { + $idnOptions = ($options['idn_conversion'] === true) ? \IDNA_DEFAULT : $options['idn_conversion']; + $uri = Utils::idnUriConvert($uri, $idnOptions); + } + + $modify['uri'] = $uri; + Psr7\Message::rewindBody($request); + + // Add the Referer header if it is told to do so and only + // add the header if we are not redirecting from https to http. + if ($options['allow_redirects']['referer'] + && $modify['uri']->getScheme() === $request->getUri()->getScheme() + ) { + $uri = $request->getUri()->withUserInfo(''); + $modify['set_headers']['Referer'] = (string) $uri; + } else { + $modify['remove_headers'][] = 'Referer'; + } + + // Remove Authorization and Cookie headers if URI is cross-origin. + if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $modify['uri'])) { + $modify['remove_headers'][] = 'Authorization'; + $modify['remove_headers'][] = 'Cookie'; + } + + return Psr7\Utils::modifyRequest($request, $modify); + } + + /** + * Set the appropriate URL on the request based on the location header. + */ + private static function redirectUri( + RequestInterface $request, + ResponseInterface $response, + array $protocols + ): UriInterface { + $location = Psr7\UriResolver::resolve( + $request->getUri(), + new Psr7\Uri($response->getHeaderLine('Location')) + ); + + // Ensure that the redirect URI is allowed based on the protocols. + if (!\in_array($location->getScheme(), $protocols)) { + throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', $location, \implode(', ', $protocols)), $request, $response); + } + + return $location; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/RequestOptions.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/RequestOptions.php new file mode 100644 index 0000000..20b31bc --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/RequestOptions.php @@ -0,0 +1,264 @@ +decider = $decider; + $this->nextHandler = $nextHandler; + $this->delay = $delay ?: __CLASS__ . '::exponentialDelay'; + } + + /** + * Default exponential backoff delay function. + * + * @return int milliseconds. + */ + public static function exponentialDelay(int $retries): int + { + return (int) \pow(2, $retries - 1) * 1000; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (!isset($options['retries'])) { + $options['retries'] = 0; + } + + $fn = $this->nextHandler; + return $fn($request, $options) + ->then( + $this->onFulfilled($request, $options), + $this->onRejected($request, $options) + ); + } + + /** + * Execute fulfilled closure + */ + private function onFulfilled(RequestInterface $request, array $options): callable + { + return function ($value) use ($request, $options) { + if (!($this->decider)( + $options['retries'], + $request, + $value, + null + )) { + return $value; + } + return $this->doRetry($request, $options, $value); + }; + } + + /** + * Execute rejected closure + */ + private function onRejected(RequestInterface $req, array $options): callable + { + return function ($reason) use ($req, $options) { + if (!($this->decider)( + $options['retries'], + $req, + null, + $reason + )) { + return P\Create::rejectionFor($reason); + } + return $this->doRetry($req, $options); + }; + } + + private function doRetry(RequestInterface $request, array $options, ResponseInterface $response = null): PromiseInterface + { + $options['delay'] = ($this->delay)(++$options['retries'], $response, $request); + + return $this($request, $options); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/TransferStats.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/TransferStats.php new file mode 100644 index 0000000..93fa334 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/TransferStats.php @@ -0,0 +1,133 @@ +request = $request; + $this->response = $response; + $this->transferTime = $transferTime; + $this->handlerErrorData = $handlerErrorData; + $this->handlerStats = $handlerStats; + } + + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Returns the response that was received (if any). + */ + public function getResponse(): ?ResponseInterface + { + return $this->response; + } + + /** + * Returns true if a response was received. + */ + public function hasResponse(): bool + { + return $this->response !== null; + } + + /** + * Gets handler specific error data. + * + * This might be an exception, a integer representing an error code, or + * anything else. Relying on this value assumes that you know what handler + * you are using. + * + * @return mixed + */ + public function getHandlerErrorData() + { + return $this->handlerErrorData; + } + + /** + * Get the effective URI the request was sent to. + */ + public function getEffectiveUri(): UriInterface + { + return $this->request->getUri(); + } + + /** + * Get the estimated time the request was being transferred by the handler. + * + * @return float|null Time in seconds. + */ + public function getTransferTime(): ?float + { + return $this->transferTime; + } + + /** + * Gets an array of all of the handler specific transfer data. + */ + public function getHandlerStats(): array + { + return $this->handlerStats; + } + + /** + * Get a specific handler statistic from the handler by name. + * + * @param string $stat Handler specific transfer stat to retrieve. + * + * @return mixed|null + */ + public function getHandlerStat(string $stat) + { + return $this->handlerStats[$stat] ?? null; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Utils.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Utils.php new file mode 100644 index 0000000..e355f32 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/Utils.php @@ -0,0 +1,385 @@ +getHost()) { + $asciiHost = self::idnToAsci($uri->getHost(), $options, $info); + if ($asciiHost === false) { + $errorBitSet = $info['errors'] ?? 0; + + $errorConstants = array_filter(array_keys(get_defined_constants()), static function (string $name): bool { + return substr($name, 0, 11) === 'IDNA_ERROR_'; + }); + + $errors = []; + foreach ($errorConstants as $errorConstant) { + if ($errorBitSet & constant($errorConstant)) { + $errors[] = $errorConstant; + } + } + + $errorMessage = 'IDN conversion failed'; + if ($errors) { + $errorMessage .= ' (errors: ' . implode(', ', $errors) . ')'; + } + + throw new InvalidArgumentException($errorMessage); + } + if ($uri->getHost() !== $asciiHost) { + // Replace URI only if the ASCII version is different + $uri = $uri->withHost($asciiHost); + } + } + + return $uri; + } + + /** + * @internal + */ + public static function getenv(string $name): ?string + { + if (isset($_SERVER[$name])) { + return (string) $_SERVER[$name]; + } + + if (\PHP_SAPI === 'cli' && ($value = \getenv($name)) !== false && $value !== null) { + return (string) $value; + } + + return null; + } + + /** + * @return string|false + */ + private static function idnToAsci(string $domain, int $options, ?array &$info = []) + { + if (\function_exists('idn_to_ascii') && \defined('INTL_IDNA_VARIANT_UTS46')) { + return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info); + } + + throw new \Error('ext-idn or symfony/polyfill-intl-idn not loaded or too old'); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/functions.php b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/functions.php new file mode 100644 index 0000000..a70d2cb --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/guzzle/src/functions.php @@ -0,0 +1,167 @@ + +Copyright (c) 2015 Graham Campbell +Copyright (c) 2017 Tobias Schultze +Copyright (c) 2020 Tobias Nyholm + +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/plugins/login-oauth2/vendor/guzzlehttp/promises/README.md b/plugins/login-oauth2/vendor/guzzlehttp/promises/README.md new file mode 100644 index 0000000..1ea667a --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/README.md @@ -0,0 +1,546 @@ +# Guzzle Promises + +[Promises/A+](https://promisesaplus.com/) implementation that handles promise +chaining and resolution iteratively, allowing for "infinite" promise chaining +while keeping the stack size constant. Read [this blog post](https://blog.domenic.me/youre-missing-the-point-of-promises/) +for a general introduction to promises. + +- [Features](#features) +- [Quick start](#quick-start) +- [Synchronous wait](#synchronous-wait) +- [Cancellation](#cancellation) +- [API](#api) + - [Promise](#promise) + - [FulfilledPromise](#fulfilledpromise) + - [RejectedPromise](#rejectedpromise) +- [Promise interop](#promise-interop) +- [Implementation notes](#implementation-notes) + + +## Features + +- [Promises/A+](https://promisesaplus.com/) implementation. +- Promise resolution and chaining is handled iteratively, allowing for + "infinite" promise chaining. +- Promises have a synchronous `wait` method. +- Promises can be cancelled. +- Works with any object that has a `then` function. +- C# style async/await coroutine promises using + `GuzzleHttp\Promise\Coroutine::of()`. + + +## Quick Start + +A *promise* represents the eventual result of an asynchronous operation. The +primary way of interacting with a promise is through its `then` method, which +registers callbacks to receive either a promise's eventual value or the reason +why the promise cannot be fulfilled. + +### Callbacks + +Callbacks are registered with the `then` method by providing an optional +`$onFulfilled` followed by an optional `$onRejected` function. + + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then( + // $onFulfilled + function ($value) { + echo 'The promise was fulfilled.'; + }, + // $onRejected + function ($reason) { + echo 'The promise was rejected.'; + } +); +``` + +*Resolving* a promise means that you either fulfill a promise with a *value* or +reject a promise with a *reason*. Resolving a promise triggers callbacks +registered with the promise's `then` method. These callbacks are triggered +only once and in the order in which they were added. + +### Resolving a Promise + +Promises are fulfilled using the `resolve($value)` method. Resolving a promise +with any value other than a `GuzzleHttp\Promise\RejectedPromise` will trigger +all of the onFulfilled callbacks (resolving a promise with a rejected promise +will reject the promise and trigger the `$onRejected` callbacks). + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise + ->then(function ($value) { + // Return a value and don't break the chain + return "Hello, " . $value; + }) + // This then is executed after the first then and receives the value + // returned from the first then. + ->then(function ($value) { + echo $value; + }); + +// Resolving the promise triggers the $onFulfilled callbacks and outputs +// "Hello, reader." +$promise->resolve('reader.'); +``` + +### Promise Forwarding + +Promises can be chained one after the other. Each then in the chain is a new +promise. The return value of a promise is what's forwarded to the next +promise in the chain. Returning a promise in a `then` callback will cause the +subsequent promises in the chain to only be fulfilled when the returned promise +has been fulfilled. The next promise in the chain will be invoked with the +resolved value of the promise. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$nextPromise = new Promise(); + +$promise + ->then(function ($value) use ($nextPromise) { + echo $value; + return $nextPromise; + }) + ->then(function ($value) { + echo $value; + }); + +// Triggers the first callback and outputs "A" +$promise->resolve('A'); +// Triggers the second callback and outputs "B" +$nextPromise->resolve('B'); +``` + +### Promise Rejection + +When a promise is rejected, the `$onRejected` callbacks are invoked with the +rejection reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + echo $reason; +}); + +$promise->reject('Error!'); +// Outputs "Error!" +``` + +### Rejection Forwarding + +If an exception is thrown in an `$onRejected` callback, subsequent +`$onRejected` callbacks are invoked with the thrown exception as the reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + throw new Exception($reason); +})->then(null, function ($reason) { + assert($reason->getMessage() === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +You can also forward a rejection down the promise chain by returning a +`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or +`$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + return new RejectedPromise($reason); +})->then(null, function ($reason) { + assert($reason === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +If an exception is not thrown in a `$onRejected` callback and the callback +does not return a rejected promise, downstream `$onFulfilled` callbacks are +invoked using the value returned from the `$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise + ->then(null, function ($reason) { + return "It's ok"; + }) + ->then(function ($value) { + assert($value === "It's ok"); + }); + +$promise->reject('Error!'); +``` + + +## Synchronous Wait + +You can synchronously force promises to complete using a promise's `wait` +method. When creating a promise, you can provide a wait function that is used +to synchronously force a promise to complete. When a wait function is invoked +it is expected to deliver a value to the promise or reject the promise. If the +wait function does not deliver a value, then an exception is thrown. The wait +function provided to a promise constructor is invoked when the `wait` function +of the promise is called. + +```php +$promise = new Promise(function () use (&$promise) { + $promise->resolve('foo'); +}); + +// Calling wait will return the value of the promise. +echo $promise->wait(); // outputs "foo" +``` + +If an exception is encountered while invoking the wait function of a promise, +the promise is rejected with the exception and the exception is thrown. + +```php +$promise = new Promise(function () use (&$promise) { + throw new Exception('foo'); +}); + +$promise->wait(); // throws the exception. +``` + +Calling `wait` on a promise that has been fulfilled will not trigger the wait +function. It will simply return the previously resolved value. + +```php +$promise = new Promise(function () { die('this is not called!'); }); +$promise->resolve('foo'); +echo $promise->wait(); // outputs "foo" +``` + +Calling `wait` on a promise that has been rejected will throw an exception. If +the rejection reason is an instance of `\Exception` the reason is thrown. +Otherwise, a `GuzzleHttp\Promise\RejectionException` is thrown and the reason +can be obtained by calling the `getReason` method of the exception. + +```php +$promise = new Promise(); +$promise->reject('foo'); +$promise->wait(); +``` + +> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with value: foo' + +### Unwrapping a Promise + +When synchronously waiting on a promise, you are joining the state of the +promise into the current state of execution (i.e., return the value of the +promise if it was fulfilled or throw an exception if it was rejected). This is +called "unwrapping" the promise. Waiting on a promise will by default unwrap +the promise state. + +You can force a promise to resolve and *not* unwrap the state of the promise +by passing `false` to the first argument of the `wait` function: + +```php +$promise = new Promise(); +$promise->reject('foo'); +// This will not throw an exception. It simply ensures the promise has +// been resolved. +$promise->wait(false); +``` + +When unwrapping a promise, the resolved value of the promise will be waited +upon until the unwrapped value is not a promise. This means that if you resolve +promise A with a promise B and unwrap promise A, the value returned by the +wait function will be the value delivered to promise B. + +**Note**: when you do not unwrap the promise, no value is returned. + + +## Cancellation + +You can cancel a promise that has not yet been fulfilled using the `cancel()` +method of a promise. When creating a promise you can provide an optional +cancel function that when invoked cancels the action of computing a resolution +of the promise. + + +## API + +### Promise + +When creating a promise object, you can provide an optional `$waitFn` and +`$cancelFn`. `$waitFn` is a function that is invoked with no arguments and is +expected to resolve the promise. `$cancelFn` is a function with no arguments +that is expected to cancel the computation of a promise. It is invoked when the +`cancel()` method of a promise is called. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise( + function () use (&$promise) { + $promise->resolve('waited'); + }, + function () { + // do something that will cancel the promise computation (e.g., close + // a socket, cancel a database query, etc...) + } +); + +assert('waited' === $promise->wait()); +``` + +A promise has the following methods: + +- `then(callable $onFulfilled, callable $onRejected) : PromiseInterface` + + Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler. + +- `otherwise(callable $onRejected) : PromiseInterface` + + Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled. + +- `wait($unwrap = true) : mixed` + + Synchronously waits on the promise to complete. + + `$unwrap` controls whether or not the value of the promise is returned for a + fulfilled promise or if an exception is thrown if the promise is rejected. + This is set to `true` by default. + +- `cancel()` + + Attempts to cancel the promise if possible. The promise being cancelled and + the parent most ancestor that has not yet been resolved will also be + cancelled. Any promises waiting on the cancelled promise to resolve will also + be cancelled. + +- `getState() : string` + + Returns the state of the promise. One of `pending`, `fulfilled`, or + `rejected`. + +- `resolve($value)` + + Fulfills the promise with the given `$value`. + +- `reject($reason)` + + Rejects the promise with the given `$reason`. + + +### FulfilledPromise + +A fulfilled promise can be created to represent a promise that has been +fulfilled. + +```php +use GuzzleHttp\Promise\FulfilledPromise; + +$promise = new FulfilledPromise('value'); + +// Fulfilled callbacks are immediately invoked. +$promise->then(function ($value) { + echo $value; +}); +``` + + +### RejectedPromise + +A rejected promise can be created to represent a promise that has been +rejected. + +```php +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new RejectedPromise('Error'); + +// Rejected callbacks are immediately invoked. +$promise->then(null, function ($reason) { + echo $reason; +}); +``` + + +## Promise Interoperability + +This library works with foreign promises that have a `then` method. This means +you can use Guzzle promises with [React promises](https://github.com/reactphp/promise) +for example. When a foreign promise is returned inside of a then method +callback, promise resolution will occur recursively. + +```php +// Create a React promise +$deferred = new React\Promise\Deferred(); +$reactPromise = $deferred->promise(); + +// Create a Guzzle promise that is fulfilled with a React promise. +$guzzlePromise = new GuzzleHttp\Promise\Promise(); +$guzzlePromise->then(function ($value) use ($reactPromise) { + // Do something something with the value... + // Return the React promise + return $reactPromise; +}); +``` + +Please note that wait and cancel chaining is no longer possible when forwarding +a foreign promise. You will need to wrap a third-party promise with a Guzzle +promise in order to utilize wait and cancel functions with foreign promises. + + +### Event Loop Integration + +In order to keep the stack size constant, Guzzle promises are resolved +asynchronously using a task queue. When waiting on promises synchronously, the +task queue will be automatically run to ensure that the blocking promise and +any forwarded promises are resolved. When using promises asynchronously in an +event loop, you will need to run the task queue on each tick of the loop. If +you do not run the task queue, then promises will not be resolved. + +You can run the task queue using the `run()` method of the global task queue +instance. + +```php +// Get the global task queue +$queue = GuzzleHttp\Promise\Utils::queue(); +$queue->run(); +``` + +For example, you could use Guzzle promises with React using a periodic timer: + +```php +$loop = React\EventLoop\Factory::create(); +$loop->addPeriodicTimer(0, [$queue, 'run']); +``` + +*TODO*: Perhaps adding a `futureTick()` on each tick would be faster? + + +## Implementation Notes + +### Promise Resolution and Chaining is Handled Iteratively + +By shuffling pending handlers from one owner to another, promises are +resolved iteratively, allowing for "infinite" then chaining. + +```php +then(function ($v) { + // The stack size remains constant (a good thing) + echo xdebug_get_stack_depth() . ', '; + return $v + 1; + }); +} + +$parent->resolve(0); +var_dump($p->wait()); // int(1000) + +``` + +When a promise is fulfilled or rejected with a non-promise value, the promise +then takes ownership of the handlers of each child promise and delivers values +down the chain without using recursion. + +When a promise is resolved with another promise, the original promise transfers +all of its pending handlers to the new promise. When the new promise is +eventually resolved, all of the pending handlers are delivered the forwarded +value. + +### A Promise is the Deferred + +Some promise libraries implement promises using a deferred object to represent +a computation and a promise object to represent the delivery of the result of +the computation. This is a nice separation of computation and delivery because +consumers of the promise cannot modify the value that will be eventually +delivered. + +One side effect of being able to implement promise resolution and chaining +iteratively is that you need to be able for one promise to reach into the state +of another promise to shuffle around ownership of handlers. In order to achieve +this without making the handlers of a promise publicly mutable, a promise is +also the deferred value, allowing promises of the same parent class to reach +into and modify the private properties of promises of the same type. While this +does allow consumers of the value to modify the resolution or rejection of the +deferred, it is a small price to pay for keeping the stack size constant. + +```php +$promise = new Promise(); +$promise->then(function ($value) { echo $value; }); +// The promise is the deferred value, so you can deliver a value to it. +$promise->resolve('foo'); +// prints "foo" +``` + + +## Upgrading from Function API + +A static API was first introduced in 1.4.0, in order to mitigate problems with +functions conflicting between global and local copies of the package. The +function API will be removed in 2.0.0. A migration table has been provided here +for your convenience: + +| Original Function | Replacement Method | +|----------------|----------------| +| `queue` | `Utils::queue` | +| `task` | `Utils::task` | +| `promise_for` | `Create::promiseFor` | +| `rejection_for` | `Create::rejectionFor` | +| `exception_for` | `Create::exceptionFor` | +| `iter_for` | `Create::iterFor` | +| `inspect` | `Utils::inspect` | +| `inspect_all` | `Utils::inspectAll` | +| `unwrap` | `Utils::unwrap` | +| `all` | `Utils::all` | +| `some` | `Utils::some` | +| `any` | `Utils::any` | +| `settle` | `Utils::settle` | +| `each` | `Each::of` | +| `each_limit` | `Each::ofLimit` | +| `each_limit_all` | `Each::ofLimitAll` | +| `!is_fulfilled` | `Is::pending` | +| `is_fulfilled` | `Is::fulfilled` | +| `is_rejected` | `Is::rejected` | +| `is_settled` | `Is::settled` | +| `coroutine` | `Coroutine::of` | + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/promises/security/policy) for more information. + + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-promises?utm_source=packagist-guzzlehttp-promises&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/composer.json b/plugins/login-oauth2/vendor/guzzlehttp/promises/composer.json new file mode 100644 index 0000000..c959fb3 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/composer.json @@ -0,0 +1,58 @@ +{ + "name": "guzzlehttp/promises", + "description": "Guzzle promises library", + "keywords": ["promise"], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": ">=5.5" + }, + "require-dev": { + "symfony/phpunit-bridge": "^4.4 || ^5.1" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": ["src/functions_include.php"] + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Promise\\Tests\\": "tests/" + } + }, + "scripts": { + "test": "vendor/bin/simple-phpunit", + "test-ci": "vendor/bin/simple-phpunit --coverage-text" + }, + "extra": { + "branch-alias": { + "dev-master": "1.5-dev" + } + }, + "config": { + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/AggregateException.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/AggregateException.php new file mode 100644 index 0000000..d2b5712 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/AggregateException.php @@ -0,0 +1,17 @@ +then(function ($v) { echo $v; }); + * + * @param callable $generatorFn Generator function to wrap into a promise. + * + * @return Promise + * + * @link https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration + */ +final class Coroutine implements PromiseInterface +{ + /** + * @var PromiseInterface|null + */ + private $currentPromise; + + /** + * @var Generator + */ + private $generator; + + /** + * @var Promise + */ + private $result; + + public function __construct(callable $generatorFn) + { + $this->generator = $generatorFn(); + $this->result = new Promise(function () { + while (isset($this->currentPromise)) { + $this->currentPromise->wait(); + } + }); + try { + $this->nextCoroutine($this->generator->current()); + } catch (\Exception $exception) { + $this->result->reject($exception); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * Create a new coroutine. + * + * @return self + */ + public static function of(callable $generatorFn) + { + return new self($generatorFn); + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + return $this->result->then($onFulfilled, $onRejected); + } + + public function otherwise(callable $onRejected) + { + return $this->result->otherwise($onRejected); + } + + public function wait($unwrap = true) + { + return $this->result->wait($unwrap); + } + + public function getState() + { + return $this->result->getState(); + } + + public function resolve($value) + { + $this->result->resolve($value); + } + + public function reject($reason) + { + $this->result->reject($reason); + } + + public function cancel() + { + $this->currentPromise->cancel(); + $this->result->cancel(); + } + + private function nextCoroutine($yielded) + { + $this->currentPromise = Create::promiseFor($yielded) + ->then([$this, '_handleSuccess'], [$this, '_handleFailure']); + } + + /** + * @internal + */ + public function _handleSuccess($value) + { + unset($this->currentPromise); + try { + $next = $this->generator->send($value); + if ($this->generator->valid()) { + $this->nextCoroutine($next); + } else { + $this->result->resolve($value); + } + } catch (Exception $exception) { + $this->result->reject($exception); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * @internal + */ + public function _handleFailure($reason) + { + unset($this->currentPromise); + try { + $nextYield = $this->generator->throw(Create::exceptionFor($reason)); + // The throw was caught, so keep iterating on the coroutine + $this->nextCoroutine($nextYield); + } catch (Exception $exception) { + $this->result->reject($exception); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Create.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Create.php new file mode 100644 index 0000000..8d038e9 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Create.php @@ -0,0 +1,84 @@ +then([$promise, 'resolve'], [$promise, 'reject']); + return $promise; + } + + return new FulfilledPromise($value); + } + + /** + * Creates a rejected promise for a reason if the reason is not a promise. + * If the provided reason is a promise, then it is returned as-is. + * + * @param mixed $reason Promise or reason. + * + * @return PromiseInterface + */ + public static function rejectionFor($reason) + { + if ($reason instanceof PromiseInterface) { + return $reason; + } + + return new RejectedPromise($reason); + } + + /** + * Create an exception for a rejected promise value. + * + * @param mixed $reason + * + * @return \Exception|\Throwable + */ + public static function exceptionFor($reason) + { + if ($reason instanceof \Exception || $reason instanceof \Throwable) { + return $reason; + } + + return new RejectionException($reason); + } + + /** + * Returns an iterator for the given value. + * + * @param mixed $value + * + * @return \Iterator + */ + public static function iterFor($value) + { + if ($value instanceof \Iterator) { + return $value; + } + + if (is_array($value)) { + return new \ArrayIterator($value); + } + + return new \ArrayIterator([$value]); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Each.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Each.php new file mode 100644 index 0000000..1dda354 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Each.php @@ -0,0 +1,90 @@ + $onFulfilled, + 'rejected' => $onRejected + ]))->promise(); + } + + /** + * Like of, but only allows a certain number of outstanding promises at any + * given time. + * + * $concurrency may be an integer or a function that accepts the number of + * pending promises and returns a numeric concurrency limit value to allow + * for dynamic a concurrency size. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * @param callable $onRejected + * + * @return PromiseInterface + */ + public static function ofLimit( + $iterable, + $concurrency, + callable $onFulfilled = null, + callable $onRejected = null + ) { + return (new EachPromise($iterable, [ + 'fulfilled' => $onFulfilled, + 'rejected' => $onRejected, + 'concurrency' => $concurrency + ]))->promise(); + } + + /** + * Like limit, but ensures that no promise in the given $iterable argument + * is rejected. If any promise is rejected, then the aggregate promise is + * rejected with the encountered rejection. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * + * @return PromiseInterface + */ + public static function ofLimitAll( + $iterable, + $concurrency, + callable $onFulfilled = null + ) { + return each_limit( + $iterable, + $concurrency, + $onFulfilled, + function ($reason, $idx, PromiseInterface $aggregate) { + $aggregate->reject($reason); + } + ); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/EachPromise.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/EachPromise.php new file mode 100644 index 0000000..280d799 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/EachPromise.php @@ -0,0 +1,247 @@ +iterable = Create::iterFor($iterable); + + if (isset($config['concurrency'])) { + $this->concurrency = $config['concurrency']; + } + + if (isset($config['fulfilled'])) { + $this->onFulfilled = $config['fulfilled']; + } + + if (isset($config['rejected'])) { + $this->onRejected = $config['rejected']; + } + } + + /** @psalm-suppress InvalidNullableReturnType */ + public function promise() + { + if ($this->aggregate) { + return $this->aggregate; + } + + try { + $this->createPromise(); + /** @psalm-assert Promise $this->aggregate */ + $this->iterable->rewind(); + $this->refillPending(); + } catch (\Throwable $e) { + $this->aggregate->reject($e); + } catch (\Exception $e) { + $this->aggregate->reject($e); + } + + /** + * @psalm-suppress NullableReturnStatement + * @phpstan-ignore-next-line + */ + return $this->aggregate; + } + + private function createPromise() + { + $this->mutex = false; + $this->aggregate = new Promise(function () { + if ($this->checkIfFinished()) { + return; + } + reset($this->pending); + // Consume a potentially fluctuating list of promises while + // ensuring that indexes are maintained (precluding array_shift). + while ($promise = current($this->pending)) { + next($this->pending); + $promise->wait(); + if (Is::settled($this->aggregate)) { + return; + } + } + }); + + // Clear the references when the promise is resolved. + $clearFn = function () { + $this->iterable = $this->concurrency = $this->pending = null; + $this->onFulfilled = $this->onRejected = null; + $this->nextPendingIndex = 0; + }; + + $this->aggregate->then($clearFn, $clearFn); + } + + private function refillPending() + { + if (!$this->concurrency) { + // Add all pending promises. + while ($this->addPending() && $this->advanceIterator()); + return; + } + + // Add only up to N pending promises. + $concurrency = is_callable($this->concurrency) + ? call_user_func($this->concurrency, count($this->pending)) + : $this->concurrency; + $concurrency = max($concurrency - count($this->pending), 0); + // Concurrency may be set to 0 to disallow new promises. + if (!$concurrency) { + return; + } + // Add the first pending promise. + $this->addPending(); + // Note this is special handling for concurrency=1 so that we do + // not advance the iterator after adding the first promise. This + // helps work around issues with generators that might not have the + // next value to yield until promise callbacks are called. + while (--$concurrency + && $this->advanceIterator() + && $this->addPending()); + } + + private function addPending() + { + if (!$this->iterable || !$this->iterable->valid()) { + return false; + } + + $promise = Create::promiseFor($this->iterable->current()); + $key = $this->iterable->key(); + + // Iterable keys may not be unique, so we use a counter to + // guarantee uniqueness + $idx = $this->nextPendingIndex++; + + $this->pending[$idx] = $promise->then( + function ($value) use ($idx, $key) { + if ($this->onFulfilled) { + call_user_func( + $this->onFulfilled, + $value, + $key, + $this->aggregate + ); + } + $this->step($idx); + }, + function ($reason) use ($idx, $key) { + if ($this->onRejected) { + call_user_func( + $this->onRejected, + $reason, + $key, + $this->aggregate + ); + } + $this->step($idx); + } + ); + + return true; + } + + private function advanceIterator() + { + // Place a lock on the iterator so that we ensure to not recurse, + // preventing fatal generator errors. + if ($this->mutex) { + return false; + } + + $this->mutex = true; + + try { + $this->iterable->next(); + $this->mutex = false; + return true; + } catch (\Throwable $e) { + $this->aggregate->reject($e); + $this->mutex = false; + return false; + } catch (\Exception $e) { + $this->aggregate->reject($e); + $this->mutex = false; + return false; + } + } + + private function step($idx) + { + // If the promise was already resolved, then ignore this step. + if (Is::settled($this->aggregate)) { + return; + } + + unset($this->pending[$idx]); + + // Only refill pending promises if we are not locked, preventing the + // EachPromise to recursively invoke the provided iterator, which + // cause a fatal error: "Cannot resume an already running generator" + if ($this->advanceIterator() && !$this->checkIfFinished()) { + // Add more pending promises if possible. + $this->refillPending(); + } + } + + private function checkIfFinished() + { + if (!$this->pending && !$this->iterable->valid()) { + // Resolve the promise if there's nothing left to do. + $this->aggregate->resolve(null); + return true; + } + + return false; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/FulfilledPromise.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/FulfilledPromise.php new file mode 100644 index 0000000..98f72a6 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/FulfilledPromise.php @@ -0,0 +1,84 @@ +value = $value; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + // Return itself if there is no onFulfilled function. + if (!$onFulfilled) { + return $this; + } + + $queue = Utils::queue(); + $p = new Promise([$queue, 'run']); + $value = $this->value; + $queue->add(static function () use ($p, $value, $onFulfilled) { + if (Is::pending($p)) { + try { + $p->resolve($onFulfilled($value)); + } catch (\Throwable $e) { + $p->reject($e); + } catch (\Exception $e) { + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true, $defaultDelivery = null) + { + return $unwrap ? $this->value : null; + } + + public function getState() + { + return self::FULFILLED; + } + + public function resolve($value) + { + if ($value !== $this->value) { + throw new \LogicException("Cannot resolve a fulfilled promise"); + } + } + + public function reject($reason) + { + throw new \LogicException("Cannot reject a fulfilled promise"); + } + + public function cancel() + { + // pass + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Is.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Is.php new file mode 100644 index 0000000..c3ed8d0 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Is.php @@ -0,0 +1,46 @@ +getState() === PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled or rejected. + * + * @return bool + */ + public static function settled(PromiseInterface $promise) + { + return $promise->getState() !== PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled. + * + * @return bool + */ + public static function fulfilled(PromiseInterface $promise) + { + return $promise->getState() === PromiseInterface::FULFILLED; + } + + /** + * Returns true if a promise is rejected. + * + * @return bool + */ + public static function rejected(PromiseInterface $promise) + { + return $promise->getState() === PromiseInterface::REJECTED; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Promise.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Promise.php new file mode 100644 index 0000000..7593905 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/Promise.php @@ -0,0 +1,278 @@ +waitFn = $waitFn; + $this->cancelFn = $cancelFn; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + if ($this->state === self::PENDING) { + $p = new Promise(null, [$this, 'cancel']); + $this->handlers[] = [$p, $onFulfilled, $onRejected]; + $p->waitList = $this->waitList; + $p->waitList[] = $this; + return $p; + } + + // Return a fulfilled promise and immediately invoke any callbacks. + if ($this->state === self::FULFILLED) { + $promise = Create::promiseFor($this->result); + return $onFulfilled ? $promise->then($onFulfilled) : $promise; + } + + // It's either cancelled or rejected, so return a rejected promise + // and immediately invoke any callbacks. + $rejection = Create::rejectionFor($this->result); + return $onRejected ? $rejection->then(null, $onRejected) : $rejection; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true) + { + $this->waitIfPending(); + + if ($this->result instanceof PromiseInterface) { + return $this->result->wait($unwrap); + } + if ($unwrap) { + if ($this->state === self::FULFILLED) { + return $this->result; + } + // It's rejected so "unwrap" and throw an exception. + throw Create::exceptionFor($this->result); + } + } + + public function getState() + { + return $this->state; + } + + public function cancel() + { + if ($this->state !== self::PENDING) { + return; + } + + $this->waitFn = $this->waitList = null; + + if ($this->cancelFn) { + $fn = $this->cancelFn; + $this->cancelFn = null; + try { + $fn(); + } catch (\Throwable $e) { + $this->reject($e); + } catch (\Exception $e) { + $this->reject($e); + } + } + + // Reject the promise only if it wasn't rejected in a then callback. + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject(new CancellationException('Promise has been cancelled')); + } + } + + public function resolve($value) + { + $this->settle(self::FULFILLED, $value); + } + + public function reject($reason) + { + $this->settle(self::REJECTED, $reason); + } + + private function settle($state, $value) + { + if ($this->state !== self::PENDING) { + // Ignore calls with the same resolution. + if ($state === $this->state && $value === $this->result) { + return; + } + throw $this->state === $state + ? new \LogicException("The promise is already {$state}.") + : new \LogicException("Cannot change a {$this->state} promise to {$state}"); + } + + if ($value === $this) { + throw new \LogicException('Cannot fulfill or reject a promise with itself'); + } + + // Clear out the state of the promise but stash the handlers. + $this->state = $state; + $this->result = $value; + $handlers = $this->handlers; + $this->handlers = null; + $this->waitList = $this->waitFn = null; + $this->cancelFn = null; + + if (!$handlers) { + return; + } + + // If the value was not a settled promise or a thenable, then resolve + // it in the task queue using the correct ID. + if (!is_object($value) || !method_exists($value, 'then')) { + $id = $state === self::FULFILLED ? 1 : 2; + // It's a success, so resolve the handlers in the queue. + Utils::queue()->add(static function () use ($id, $value, $handlers) { + foreach ($handlers as $handler) { + self::callHandler($id, $value, $handler); + } + }); + } elseif ($value instanceof Promise && Is::pending($value)) { + // We can just merge our handlers onto the next promise. + $value->handlers = array_merge($value->handlers, $handlers); + } else { + // Resolve the handlers when the forwarded promise is resolved. + $value->then( + static function ($value) use ($handlers) { + foreach ($handlers as $handler) { + self::callHandler(1, $value, $handler); + } + }, + static function ($reason) use ($handlers) { + foreach ($handlers as $handler) { + self::callHandler(2, $reason, $handler); + } + } + ); + } + } + + /** + * Call a stack of handlers using a specific callback index and value. + * + * @param int $index 1 (resolve) or 2 (reject). + * @param mixed $value Value to pass to the callback. + * @param array $handler Array of handler data (promise and callbacks). + */ + private static function callHandler($index, $value, array $handler) + { + /** @var PromiseInterface $promise */ + $promise = $handler[0]; + + // The promise may have been cancelled or resolved before placing + // this thunk in the queue. + if (Is::settled($promise)) { + return; + } + + try { + if (isset($handler[$index])) { + /* + * If $f throws an exception, then $handler will be in the exception + * stack trace. Since $handler contains a reference to the callable + * itself we get a circular reference. We clear the $handler + * here to avoid that memory leak. + */ + $f = $handler[$index]; + unset($handler); + $promise->resolve($f($value)); + } elseif ($index === 1) { + // Forward resolution values as-is. + $promise->resolve($value); + } else { + // Forward rejections down the chain. + $promise->reject($value); + } + } catch (\Throwable $reason) { + $promise->reject($reason); + } catch (\Exception $reason) { + $promise->reject($reason); + } + } + + private function waitIfPending() + { + if ($this->state !== self::PENDING) { + return; + } elseif ($this->waitFn) { + $this->invokeWaitFn(); + } elseif ($this->waitList) { + $this->invokeWaitList(); + } else { + // If there's no wait function, then reject the promise. + $this->reject('Cannot wait on a promise that has ' + . 'no internal wait function. You must provide a wait ' + . 'function when constructing the promise to be able to ' + . 'wait on a promise.'); + } + + Utils::queue()->run(); + + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject('Invoking the wait callback did not resolve the promise'); + } + } + + private function invokeWaitFn() + { + try { + $wfn = $this->waitFn; + $this->waitFn = null; + $wfn(true); + } catch (\Exception $reason) { + if ($this->state === self::PENDING) { + // The promise has not been resolved yet, so reject the promise + // with the exception. + $this->reject($reason); + } else { + // The promise was already resolved, so there's a problem in + // the application. + throw $reason; + } + } + } + + private function invokeWaitList() + { + $waitList = $this->waitList; + $this->waitList = null; + + foreach ($waitList as $result) { + do { + $result->waitIfPending(); + $result = $result->result; + } while ($result instanceof Promise); + + if ($result instanceof PromiseInterface) { + $result->wait(false); + } + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/PromiseInterface.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/PromiseInterface.php new file mode 100644 index 0000000..e598331 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/PromiseInterface.php @@ -0,0 +1,97 @@ +reason = $reason; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + // If there's no onRejected callback then just return self. + if (!$onRejected) { + return $this; + } + + $queue = Utils::queue(); + $reason = $this->reason; + $p = new Promise([$queue, 'run']); + $queue->add(static function () use ($p, $reason, $onRejected) { + if (Is::pending($p)) { + try { + // Return a resolved promise if onRejected does not throw. + $p->resolve($onRejected($reason)); + } catch (\Throwable $e) { + // onRejected threw, so return a rejected promise. + $p->reject($e); + } catch (\Exception $e) { + // onRejected threw, so return a rejected promise. + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true, $defaultDelivery = null) + { + if ($unwrap) { + throw Create::exceptionFor($this->reason); + } + + return null; + } + + public function getState() + { + return self::REJECTED; + } + + public function resolve($value) + { + throw new \LogicException("Cannot resolve a rejected promise"); + } + + public function reject($reason) + { + if ($reason !== $this->reason) { + throw new \LogicException("Cannot reject a rejected promise"); + } + } + + public function cancel() + { + // pass + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/RejectionException.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/RejectionException.php new file mode 100644 index 0000000..e2f1377 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/RejectionException.php @@ -0,0 +1,48 @@ +reason = $reason; + + $message = 'The promise was rejected'; + + if ($description) { + $message .= ' with reason: ' . $description; + } elseif (is_string($reason) + || (is_object($reason) && method_exists($reason, '__toString')) + ) { + $message .= ' with reason: ' . $this->reason; + } elseif ($reason instanceof \JsonSerializable) { + $message .= ' with reason: ' + . json_encode($this->reason, JSON_PRETTY_PRINT); + } + + parent::__construct($message); + } + + /** + * Returns the rejection reason. + * + * @return mixed + */ + public function getReason() + { + return $this->reason; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/TaskQueue.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/TaskQueue.php new file mode 100644 index 0000000..f0fba2c --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/TaskQueue.php @@ -0,0 +1,67 @@ +run(); + */ +class TaskQueue implements TaskQueueInterface +{ + private $enableShutdown = true; + private $queue = []; + + public function __construct($withShutdown = true) + { + if ($withShutdown) { + register_shutdown_function(function () { + if ($this->enableShutdown) { + // Only run the tasks if an E_ERROR didn't occur. + $err = error_get_last(); + if (!$err || ($err['type'] ^ E_ERROR)) { + $this->run(); + } + } + }); + } + } + + public function isEmpty() + { + return !$this->queue; + } + + public function add(callable $task) + { + $this->queue[] = $task; + } + + public function run() + { + while ($task = array_shift($this->queue)) { + /** @var callable $task */ + $task(); + } + } + + /** + * The task queue will be run and exhausted by default when the process + * exits IFF the exit is not the result of a PHP E_ERROR error. + * + * You can disable running the automatic shutdown of the queue by calling + * this function. If you disable the task queue shutdown process, then you + * MUST either run the task queue (as a result of running your event loop + * or manually using the run() method) or wait on each outstanding promise. + * + * Note: This shutdown will occur before any destructors are triggered. + */ + public function disableShutdown() + { + $this->enableShutdown = false; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/TaskQueueInterface.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/TaskQueueInterface.php new file mode 100644 index 0000000..723d4d5 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/TaskQueueInterface.php @@ -0,0 +1,24 @@ + + * while ($eventLoop->isRunning()) { + * GuzzleHttp\Promise\Utils::queue()->run(); + * } + * + * + * @param TaskQueueInterface $assign Optionally specify a new queue instance. + * + * @return TaskQueueInterface + */ + public static function queue(TaskQueueInterface $assign = null) + { + static $queue; + + if ($assign) { + $queue = $assign; + } elseif (!$queue) { + $queue = new TaskQueue(); + } + + return $queue; + } + + /** + * Adds a function to run in the task queue when it is next `run()` and + * returns a promise that is fulfilled or rejected with the result. + * + * @param callable $task Task function to run. + * + * @return PromiseInterface + */ + public static function task(callable $task) + { + $queue = self::queue(); + $promise = new Promise([$queue, 'run']); + $queue->add(function () use ($task, $promise) { + try { + if (Is::pending($promise)) { + $promise->resolve($task()); + } + } catch (\Throwable $e) { + $promise->reject($e); + } catch (\Exception $e) { + $promise->reject($e); + } + }); + + return $promise; + } + + /** + * Synchronously waits on a promise to resolve and returns an inspection + * state array. + * + * Returns a state associative array containing a "state" key mapping to a + * valid promise state. If the state of the promise is "fulfilled", the + * array will contain a "value" key mapping to the fulfilled value of the + * promise. If the promise is rejected, the array will contain a "reason" + * key mapping to the rejection reason of the promise. + * + * @param PromiseInterface $promise Promise or value. + * + * @return array + */ + public static function inspect(PromiseInterface $promise) + { + try { + return [ + 'state' => PromiseInterface::FULFILLED, + 'value' => $promise->wait() + ]; + } catch (RejectionException $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()]; + } catch (\Throwable $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; + } catch (\Exception $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; + } + } + + /** + * Waits on all of the provided promises, but does not unwrap rejected + * promises as thrown exception. + * + * Returns an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param PromiseInterface[] $promises Traversable of promises to wait upon. + * + * @return array + */ + public static function inspectAll($promises) + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = inspect($promise); + } + + return $results; + } + + /** + * Waits on all of the provided promises and returns the fulfilled values. + * + * Returns an array that contains the value of each promise (in the same + * order the promises were provided). An exception is thrown if any of the + * promises are rejected. + * + * @param iterable $promises Iterable of PromiseInterface objects to wait on. + * + * @return array + * + * @throws \Exception on error + * @throws \Throwable on error in PHP >=7 + */ + public static function unwrap($promises) + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = $promise->wait(); + } + + return $results; + } + + /** + * Given an array of promises, return a promise that is fulfilled when all + * the items in the array are fulfilled. + * + * The promise's fulfillment value is an array with fulfillment values at + * respective positions to the original array. If any promise in the array + * rejects, the returned promise is rejected with the rejection reason. + * + * @param mixed $promises Promises or values. + * @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution. + * + * @return PromiseInterface + */ + public static function all($promises, $recursive = false) + { + $results = []; + $promise = Each::of( + $promises, + function ($value, $idx) use (&$results) { + $results[$idx] = $value; + }, + function ($reason, $idx, Promise $aggregate) { + $aggregate->reject($reason); + } + )->then(function () use (&$results) { + ksort($results); + return $results; + }); + + if (true === $recursive) { + $promise = $promise->then(function ($results) use ($recursive, &$promises) { + foreach ($promises as $promise) { + if (Is::pending($promise)) { + return self::all($promises, $recursive); + } + } + return $results; + }); + } + + return $promise; + } + + /** + * Initiate a competitive race between multiple promises or values (values + * will become immediately fulfilled promises). + * + * When count amount of promises have been fulfilled, the returned promise + * is fulfilled with an array that contains the fulfillment values of the + * winners in order of resolution. + * + * This promise is rejected with a {@see AggregateException} if the number + * of fulfilled promises is less than the desired $count. + * + * @param int $count Total number of promises. + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ + public static function some($count, $promises) + { + $results = []; + $rejections = []; + + return Each::of( + $promises, + function ($value, $idx, PromiseInterface $p) use (&$results, $count) { + if (Is::settled($p)) { + return; + } + $results[$idx] = $value; + if (count($results) >= $count) { + $p->resolve(null); + } + }, + function ($reason) use (&$rejections) { + $rejections[] = $reason; + } + )->then( + function () use (&$results, &$rejections, $count) { + if (count($results) !== $count) { + throw new AggregateException( + 'Not enough promises to fulfill count', + $rejections + ); + } + ksort($results); + return array_values($results); + } + ); + } + + /** + * Like some(), with 1 as count. However, if the promise fulfills, the + * fulfillment value is not an array of 1 but the value directly. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ + public static function any($promises) + { + return self::some(1, $promises)->then(function ($values) { + return $values[0]; + }); + } + + /** + * Returns a promise that is fulfilled when all of the provided promises have + * been fulfilled or rejected. + * + * The returned promise is fulfilled with an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ + public static function settle($promises) + { + $results = []; + + return Each::of( + $promises, + function ($value, $idx) use (&$results) { + $results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value]; + }, + function ($reason, $idx) use (&$results) { + $results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason]; + } + )->then(function () use (&$results) { + ksort($results); + return $results; + }); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/functions.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/functions.php new file mode 100644 index 0000000..c03d39d --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/functions.php @@ -0,0 +1,363 @@ + + * while ($eventLoop->isRunning()) { + * GuzzleHttp\Promise\queue()->run(); + * } + * + * + * @param TaskQueueInterface $assign Optionally specify a new queue instance. + * + * @return TaskQueueInterface + * + * @deprecated queue will be removed in guzzlehttp/promises:2.0. Use Utils::queue instead. + */ +function queue(TaskQueueInterface $assign = null) +{ + return Utils::queue($assign); +} + +/** + * Adds a function to run in the task queue when it is next `run()` and returns + * a promise that is fulfilled or rejected with the result. + * + * @param callable $task Task function to run. + * + * @return PromiseInterface + * + * @deprecated task will be removed in guzzlehttp/promises:2.0. Use Utils::task instead. + */ +function task(callable $task) +{ + return Utils::task($task); +} + +/** + * Creates a promise for a value if the value is not a promise. + * + * @param mixed $value Promise or value. + * + * @return PromiseInterface + * + * @deprecated promise_for will be removed in guzzlehttp/promises:2.0. Use Create::promiseFor instead. + */ +function promise_for($value) +{ + return Create::promiseFor($value); +} + +/** + * Creates a rejected promise for a reason if the reason is not a promise. If + * the provided reason is a promise, then it is returned as-is. + * + * @param mixed $reason Promise or reason. + * + * @return PromiseInterface + * + * @deprecated rejection_for will be removed in guzzlehttp/promises:2.0. Use Create::rejectionFor instead. + */ +function rejection_for($reason) +{ + return Create::rejectionFor($reason); +} + +/** + * Create an exception for a rejected promise value. + * + * @param mixed $reason + * + * @return \Exception|\Throwable + * + * @deprecated exception_for will be removed in guzzlehttp/promises:2.0. Use Create::exceptionFor instead. + */ +function exception_for($reason) +{ + return Create::exceptionFor($reason); +} + +/** + * Returns an iterator for the given value. + * + * @param mixed $value + * + * @return \Iterator + * + * @deprecated iter_for will be removed in guzzlehttp/promises:2.0. Use Create::iterFor instead. + */ +function iter_for($value) +{ + return Create::iterFor($value); +} + +/** + * Synchronously waits on a promise to resolve and returns an inspection state + * array. + * + * Returns a state associative array containing a "state" key mapping to a + * valid promise state. If the state of the promise is "fulfilled", the array + * will contain a "value" key mapping to the fulfilled value of the promise. If + * the promise is rejected, the array will contain a "reason" key mapping to + * the rejection reason of the promise. + * + * @param PromiseInterface $promise Promise or value. + * + * @return array + * + * @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspect instead. + */ +function inspect(PromiseInterface $promise) +{ + return Utils::inspect($promise); +} + +/** + * Waits on all of the provided promises, but does not unwrap rejected promises + * as thrown exception. + * + * Returns an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param PromiseInterface[] $promises Traversable of promises to wait upon. + * + * @return array + * + * @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspectAll instead. + */ +function inspect_all($promises) +{ + return Utils::inspectAll($promises); +} + +/** + * Waits on all of the provided promises and returns the fulfilled values. + * + * Returns an array that contains the value of each promise (in the same order + * the promises were provided). An exception is thrown if any of the promises + * are rejected. + * + * @param iterable $promises Iterable of PromiseInterface objects to wait on. + * + * @return array + * + * @throws \Exception on error + * @throws \Throwable on error in PHP >=7 + * + * @deprecated unwrap will be removed in guzzlehttp/promises:2.0. Use Utils::unwrap instead. + */ +function unwrap($promises) +{ + return Utils::unwrap($promises); +} + +/** + * Given an array of promises, return a promise that is fulfilled when all the + * items in the array are fulfilled. + * + * The promise's fulfillment value is an array with fulfillment values at + * respective positions to the original array. If any promise in the array + * rejects, the returned promise is rejected with the rejection reason. + * + * @param mixed $promises Promises or values. + * @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution. + * + * @return PromiseInterface + * + * @deprecated all will be removed in guzzlehttp/promises:2.0. Use Utils::all instead. + */ +function all($promises, $recursive = false) +{ + return Utils::all($promises, $recursive); +} + +/** + * Initiate a competitive race between multiple promises or values (values will + * become immediately fulfilled promises). + * + * When count amount of promises have been fulfilled, the returned promise is + * fulfilled with an array that contains the fulfillment values of the winners + * in order of resolution. + * + * This promise is rejected with a {@see AggregateException} if the number of + * fulfilled promises is less than the desired $count. + * + * @param int $count Total number of promises. + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + * + * @deprecated some will be removed in guzzlehttp/promises:2.0. Use Utils::some instead. + */ +function some($count, $promises) +{ + return Utils::some($count, $promises); +} + +/** + * Like some(), with 1 as count. However, if the promise fulfills, the + * fulfillment value is not an array of 1 but the value directly. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + * + * @deprecated any will be removed in guzzlehttp/promises:2.0. Use Utils::any instead. + */ +function any($promises) +{ + return Utils::any($promises); +} + +/** + * Returns a promise that is fulfilled when all of the provided promises have + * been fulfilled or rejected. + * + * The returned promise is fulfilled with an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + * + * @deprecated settle will be removed in guzzlehttp/promises:2.0. Use Utils::settle instead. + */ +function settle($promises) +{ + return Utils::settle($promises); +} + +/** + * Given an iterator that yields promises or values, returns a promise that is + * fulfilled with a null value when the iterator has been consumed or the + * aggregate promise has been fulfilled or rejected. + * + * $onFulfilled is a function that accepts the fulfilled value, iterator index, + * and the aggregate promise. The callback can invoke any necessary side + * effects and choose to resolve or reject the aggregate if needed. + * + * $onRejected is a function that accepts the rejection reason, iterator index, + * and the aggregate promise. The callback can invoke any necessary side + * effects and choose to resolve or reject the aggregate if needed. + * + * @param mixed $iterable Iterator or array to iterate over. + * @param callable $onFulfilled + * @param callable $onRejected + * + * @return PromiseInterface + * + * @deprecated each will be removed in guzzlehttp/promises:2.0. Use Each::of instead. + */ +function each( + $iterable, + callable $onFulfilled = null, + callable $onRejected = null +) { + return Each::of($iterable, $onFulfilled, $onRejected); +} + +/** + * Like each, but only allows a certain number of outstanding promises at any + * given time. + * + * $concurrency may be an integer or a function that accepts the number of + * pending promises and returns a numeric concurrency limit value to allow for + * dynamic a concurrency size. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * @param callable $onRejected + * + * @return PromiseInterface + * + * @deprecated each_limit will be removed in guzzlehttp/promises:2.0. Use Each::ofLimit instead. + */ +function each_limit( + $iterable, + $concurrency, + callable $onFulfilled = null, + callable $onRejected = null +) { + return Each::ofLimit($iterable, $concurrency, $onFulfilled, $onRejected); +} + +/** + * Like each_limit, but ensures that no promise in the given $iterable argument + * is rejected. If any promise is rejected, then the aggregate promise is + * rejected with the encountered rejection. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * + * @return PromiseInterface + * + * @deprecated each_limit_all will be removed in guzzlehttp/promises:2.0. Use Each::ofLimitAll instead. + */ +function each_limit_all( + $iterable, + $concurrency, + callable $onFulfilled = null +) { + return Each::ofLimitAll($iterable, $concurrency, $onFulfilled); +} + +/** + * Returns true if a promise is fulfilled. + * + * @return bool + * + * @deprecated is_fulfilled will be removed in guzzlehttp/promises:2.0. Use Is::fulfilled instead. + */ +function is_fulfilled(PromiseInterface $promise) +{ + return Is::fulfilled($promise); +} + +/** + * Returns true if a promise is rejected. + * + * @return bool + * + * @deprecated is_rejected will be removed in guzzlehttp/promises:2.0. Use Is::rejected instead. + */ +function is_rejected(PromiseInterface $promise) +{ + return Is::rejected($promise); +} + +/** + * Returns true if a promise is fulfilled or rejected. + * + * @return bool + * + * @deprecated is_settled will be removed in guzzlehttp/promises:2.0. Use Is::settled instead. + */ +function is_settled(PromiseInterface $promise) +{ + return Is::settled($promise); +} + +/** + * Create a new coroutine. + * + * @see Coroutine + * + * @return PromiseInterface + * + * @deprecated coroutine will be removed in guzzlehttp/promises:2.0. Use Coroutine::of instead. + */ +function coroutine(callable $generatorFn) +{ + return Coroutine::of($generatorFn); +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/promises/src/functions_include.php b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/functions_include.php new file mode 100644 index 0000000..34cd171 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/promises/src/functions_include.php @@ -0,0 +1,6 @@ +withPath('foo')->withHost('example.com')` will throw an exception + because the path of a URI with an authority must start with a slash "/" or be empty + - `(new Uri())->withScheme('http')` will return `'http://localhost'` + +### Deprecated + +- `Uri::resolve` in favor of `UriResolver::resolve` +- `Uri::removeDotSegments` in favor of `UriResolver::removeDotSegments` + +### Fixed + +- `Stream::read` when length parameter <= 0. +- `copy_to_stream` reads bytes in chunks instead of `maxLen` into memory. +- `ServerRequest::getUriFromGlobals` when `Host` header contains port. +- Compatibility of URIs with `file` scheme and empty host. + + +## [1.3.1] - 2016-06-25 + +### Fixed + +- `Uri::__toString` for network path references, e.g. `//example.org`. +- Missing lowercase normalization for host. +- Handling of URI components in case they are `'0'` in a lot of places, + e.g. as a user info password. +- `Uri::withAddedHeader` to correctly merge headers with different case. +- Trimming of header values in `Uri::withAddedHeader`. Header values may + be surrounded by whitespace which should be ignored according to RFC 7230 + Section 3.2.4. This does not apply to header names. +- `Uri::withAddedHeader` with an array of header values. +- `Uri::resolve` when base path has no slash and handling of fragment. +- Handling of encoding in `Uri::with(out)QueryValue` so one can pass the + key/value both in encoded as well as decoded form to those methods. This is + consistent with withPath, withQuery etc. +- `ServerRequest::withoutAttribute` when attribute value is null. + + +## [1.3.0] - 2016-04-13 + +### Added + +- Remaining interfaces needed for full PSR7 compatibility + (ServerRequestInterface, UploadedFileInterface, etc.). +- Support for stream_for from scalars. + +### Changed + +- Can now extend Uri. + +### Fixed +- A bug in validating request methods by making it more permissive. + + +## [1.2.3] - 2016-02-18 + +### Fixed + +- Support in `GuzzleHttp\Psr7\CachingStream` for seeking forward on remote + streams, which can sometimes return fewer bytes than requested with `fread`. +- Handling of gzipped responses with FNAME headers. + + +## [1.2.2] - 2016-01-22 + +### Added + +- Support for URIs without any authority. +- Support for HTTP 451 'Unavailable For Legal Reasons.' +- Support for using '0' as a filename. +- Support for including non-standard ports in Host headers. + + +## [1.2.1] - 2015-11-02 + +### Changes + +- Now supporting negative offsets when seeking to SEEK_END. + + +## [1.2.0] - 2015-08-15 + +### Changed + +- Body as `"0"` is now properly added to a response. +- Now allowing forward seeking in CachingStream. +- Now properly parsing HTTP requests that contain proxy targets in + `parse_request`. +- functions.php is now conditionally required. +- user-info is no longer dropped when resolving URIs. + + +## [1.1.0] - 2015-06-24 + +### Changed + +- URIs can now be relative. +- `multipart/form-data` headers are now overridden case-insensitively. +- URI paths no longer encode the following characters because they are allowed + in URIs: "(", ")", "*", "!", "'" +- A port is no longer added to a URI when the scheme is missing and no port is + present. + + +## 1.0.0 - 2015-05-19 + +Initial release. + +Currently unsupported: + +- `Psr\Http\Message\ServerRequestInterface` +- `Psr\Http\Message\UploadedFileInterface` + + + +[1.6.0]: https://github.com/guzzle/psr7/compare/1.5.2...1.6.0 +[1.5.2]: https://github.com/guzzle/psr7/compare/1.5.1...1.5.2 +[1.5.1]: https://github.com/guzzle/psr7/compare/1.5.0...1.5.1 +[1.5.0]: https://github.com/guzzle/psr7/compare/1.4.2...1.5.0 +[1.4.2]: https://github.com/guzzle/psr7/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/guzzle/psr7/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/guzzle/psr7/compare/1.3.1...1.4.0 +[1.3.1]: https://github.com/guzzle/psr7/compare/1.3.0...1.3.1 +[1.3.0]: https://github.com/guzzle/psr7/compare/1.2.3...1.3.0 +[1.2.3]: https://github.com/guzzle/psr7/compare/1.2.2...1.2.3 +[1.2.2]: https://github.com/guzzle/psr7/compare/1.2.1...1.2.2 +[1.2.1]: https://github.com/guzzle/psr7/compare/1.2.0...1.2.1 +[1.2.0]: https://github.com/guzzle/psr7/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/guzzle/psr7/compare/1.0.0...1.1.0 diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/LICENSE b/plugins/login-oauth2/vendor/guzzlehttp/psr7/LICENSE new file mode 100644 index 0000000..51c7ec8 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/LICENSE @@ -0,0 +1,26 @@ +The MIT License (MIT) + +Copyright (c) 2015 Michael Dowling +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Graham Campbell +Copyright (c) 2016 Tobias Schultze +Copyright (c) 2016 George Mponos +Copyright (c) 2018 Tobias Nyholm + +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/plugins/login-oauth2/vendor/guzzlehttp/psr7/README.md b/plugins/login-oauth2/vendor/guzzlehttp/psr7/README.md new file mode 100644 index 0000000..8b9929a --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/README.md @@ -0,0 +1,872 @@ +# PSR-7 Message Implementation + +This repository contains a full [PSR-7](https://www.php-fig.org/psr/psr-7/) +message implementation, several stream decorators, and some helpful +functionality like query string parsing. + +![CI](https://github.com/guzzle/psr7/workflows/CI/badge.svg) +![Static analysis](https://github.com/guzzle/psr7/workflows/Static%20analysis/badge.svg) + + +# Stream implementation + +This package comes with a number of stream implementations and stream +decorators. + + +## AppendStream + +`GuzzleHttp\Psr7\AppendStream` + +Reads from multiple streams, one after the other. + +```php +use GuzzleHttp\Psr7; + +$a = Psr7\Utils::streamFor('abc, '); +$b = Psr7\Utils::streamFor('123.'); +$composed = new Psr7\AppendStream([$a, $b]); + +$composed->addStream(Psr7\Utils::streamFor(' Above all listen to me')); + +echo $composed; // abc, 123. Above all listen to me. +``` + + +## BufferStream + +`GuzzleHttp\Psr7\BufferStream` + +Provides a buffer stream that can be written to fill a buffer, and read +from to remove bytes from the buffer. + +This stream returns a "hwm" metadata value that tells upstream consumers +what the configured high water mark of the stream is, or the maximum +preferred size of the buffer. + +```php +use GuzzleHttp\Psr7; + +// When more than 1024 bytes are in the buffer, it will begin returning +// false to writes. This is an indication that writers should slow down. +$buffer = new Psr7\BufferStream(1024); +``` + + +## CachingStream + +The CachingStream is used to allow seeking over previously read bytes on +non-seekable streams. This can be useful when transferring a non-seekable +entity body fails due to needing to rewind the stream (for example, resulting +from a redirect). Data that is read from the remote stream will be buffered in +a PHP temp stream so that previously read bytes are cached first in memory, +then on disk. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r')); +$stream = new Psr7\CachingStream($original); + +$stream->read(1024); +echo $stream->tell(); +// 1024 + +$stream->seek(0); +echo $stream->tell(); +// 0 +``` + + +## DroppingStream + +`GuzzleHttp\Psr7\DroppingStream` + +Stream decorator that begins dropping data once the size of the underlying +stream becomes too full. + +```php +use GuzzleHttp\Psr7; + +// Create an empty stream +$stream = Psr7\Utils::streamFor(); + +// Start dropping data when the stream has more than 10 bytes +$dropping = new Psr7\DroppingStream($stream, 10); + +$dropping->write('01234567890123456789'); +echo $stream; // 0123456789 +``` + + +## FnStream + +`GuzzleHttp\Psr7\FnStream` + +Compose stream implementations based on a hash of functions. + +Allows for easy testing and extension of a provided stream without needing +to create a concrete class for a simple extension point. + +```php + +use GuzzleHttp\Psr7; + +$stream = Psr7\Utils::streamFor('hi'); +$fnStream = Psr7\FnStream::decorate($stream, [ + 'rewind' => function () use ($stream) { + echo 'About to rewind - '; + $stream->rewind(); + echo 'rewound!'; + } +]); + +$fnStream->rewind(); +// Outputs: About to rewind - rewound! +``` + + +## InflateStream + +`GuzzleHttp\Psr7\InflateStream` + +Uses PHP's zlib.inflate filter to inflate zlib (HTTP deflate, RFC1950) or gzipped (RFC1952) content. + +This stream decorator converts the provided stream to a PHP stream resource, +then appends the zlib.inflate filter. The stream is then converted back +to a Guzzle stream resource to be used as a Guzzle stream. + + +## LazyOpenStream + +`GuzzleHttp\Psr7\LazyOpenStream` + +Lazily reads or writes to a file that is opened only after an IO operation +take place on the stream. + +```php +use GuzzleHttp\Psr7; + +$stream = new Psr7\LazyOpenStream('/path/to/file', 'r'); +// The file has not yet been opened... + +echo $stream->read(10); +// The file is opened and read from only when needed. +``` + + +## LimitStream + +`GuzzleHttp\Psr7\LimitStream` + +LimitStream can be used to read a subset or slice of an existing stream object. +This can be useful for breaking a large file into smaller pieces to be sent in +chunks (e.g. Amazon S3's multipart upload API). + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+')); +echo $original->getSize(); +// >>> 1048576 + +// Limit the size of the body to 1024 bytes and start reading from byte 2048 +$stream = new Psr7\LimitStream($original, 1024, 2048); +echo $stream->getSize(); +// >>> 1024 +echo $stream->tell(); +// >>> 0 +``` + + +## MultipartStream + +`GuzzleHttp\Psr7\MultipartStream` + +Stream that when read returns bytes for a streaming multipart or +multipart/form-data stream. + + +## NoSeekStream + +`GuzzleHttp\Psr7\NoSeekStream` + +NoSeekStream wraps a stream and does not allow seeking. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); +$noSeek = new Psr7\NoSeekStream($original); + +echo $noSeek->read(3); +// foo +var_export($noSeek->isSeekable()); +// false +$noSeek->seek(0); +var_export($noSeek->read(3)); +// NULL +``` + + +## PumpStream + +`GuzzleHttp\Psr7\PumpStream` + +Provides a read only stream that pumps data from a PHP callable. + +When invoking the provided callable, the PumpStream will pass the amount of +data requested to read to the callable. The callable can choose to ignore +this value and return fewer or more bytes than requested. Any extra data +returned by the provided callable is buffered internally until drained using +the read() function of the PumpStream. The provided callable MUST return +false when there is no more data to read. + + +## Implementing stream decorators + +Creating a stream decorator is very easy thanks to the +`GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that +implement `Psr\Http\Message\StreamInterface` by proxying to an underlying +stream. Just `use` the `StreamDecoratorTrait` and implement your custom +methods. + +For example, let's say we wanted to call a specific function each time the last +byte is read from a stream. This could be implemented by overriding the +`read()` method. + +```php +use Psr\Http\Message\StreamInterface; +use GuzzleHttp\Psr7\StreamDecoratorTrait; + +class EofCallbackStream implements StreamInterface +{ + use StreamDecoratorTrait; + + private $callback; + + public function __construct(StreamInterface $stream, callable $cb) + { + $this->stream = $stream; + $this->callback = $cb; + } + + public function read($length) + { + $result = $this->stream->read($length); + + // Invoke the callback when EOF is hit. + if ($this->eof()) { + call_user_func($this->callback); + } + + return $result; + } +} +``` + +This decorator could be added to any existing stream and used like so: + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); + +$eofStream = new EofCallbackStream($original, function () { + echo 'EOF!'; +}); + +$eofStream->read(2); +$eofStream->read(1); +// echoes "EOF!" +$eofStream->seek(0); +$eofStream->read(3); +// echoes "EOF!" +``` + + +## PHP StreamWrapper + +You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a +PSR-7 stream as a PHP stream resource. + +Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP +stream from a PSR-7 stream. + +```php +use GuzzleHttp\Psr7\StreamWrapper; + +$stream = GuzzleHttp\Psr7\Utils::streamFor('hello!'); +$resource = StreamWrapper::getResource($stream); +echo fread($resource, 6); // outputs hello! +``` + + +# Static API + +There are various static methods available under the `GuzzleHttp\Psr7` namespace. + + +## `GuzzleHttp\Psr7\Message::toString` + +`public static function toString(MessageInterface $message): string` + +Returns the string representation of an HTTP message. + +```php +$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com'); +echo GuzzleHttp\Psr7\Message::toString($request); +``` + + +## `GuzzleHttp\Psr7\Message::bodySummary` + +`public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null` + +Get a short summary of the message body. + +Will return `null` if the response is not printable. + + +## `GuzzleHttp\Psr7\Message::rewindBody` + +`public static function rewindBody(MessageInterface $message): void` + +Attempts to rewind a message body and throws an exception on failure. + +The body of the message will only be rewound if a call to `tell()` +returns a value other than `0`. + + +## `GuzzleHttp\Psr7\Message::parseMessage` + +`public static function parseMessage(string $message): array` + +Parses an HTTP message into an associative array. + +The array contains the "start-line" key containing the start line of +the message, "headers" key containing an associative array of header +array values, and a "body" key containing the body of the message. + + +## `GuzzleHttp\Psr7\Message::parseRequestUri` + +`public static function parseRequestUri(string $path, array $headers): string` + +Constructs a URI for an HTTP request message. + + +## `GuzzleHttp\Psr7\Message::parseRequest` + +`public static function parseRequest(string $message): Request` + +Parses a request message string into a request object. + + +## `GuzzleHttp\Psr7\Message::parseResponse` + +`public static function parseResponse(string $message): Response` + +Parses a response message string into a response object. + + +## `GuzzleHttp\Psr7\Header::parse` + +`public static function parse(string|array $header): array` + +Parse an array of header values containing ";" separated data into an +array of associative arrays representing the header key value pair data +of the header. When a parameter does not contain a value, but just +contains a key, this function will inject a key with a '' string value. + + +## `GuzzleHttp\Psr7\Header::splitList` + +`public static function splitList(string|string[] $header): string[]` + +Splits a HTTP header defined to contain a comma-separated list into +each individual value: + +``` +$knownEtags = Header::splitList($request->getHeader('if-none-match')); +``` + +Example headers include `accept`, `cache-control` and `if-none-match`. + + +## `GuzzleHttp\Psr7\Header::normalize` (deprecated) + +`public static function normalize(string|array $header): array` + +`Header::normalize()` is deprecated in favor of [`Header::splitList()`](README.md#guzzlehttppsr7headersplitlist) +which performs the same operation with a cleaned up API and improved +documentation. + +Converts an array of header values that may contain comma separated +headers into an array of headers with no comma separated values. + + +## `GuzzleHttp\Psr7\Query::parse` + +`public static function parse(string $str, int|bool $urlEncoding = true): array` + +Parse a query string into an associative array. + +If multiple values are found for the same key, the value of that key +value pair will become an array. This function does not parse nested +PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2` +will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`. + + +## `GuzzleHttp\Psr7\Query::build` + +`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string` + +Build a query string from an array of key value pairs. + +This function can use the return value of `parse()` to build a query +string. This function does not modify the provided keys when an array is +encountered (like `http_build_query()` would). + + +## `GuzzleHttp\Psr7\Utils::caselessRemove` + +`public static function caselessRemove(iterable $keys, $keys, array $data): array` + +Remove the items given by the keys, case insensitively from the data. + + +## `GuzzleHttp\Psr7\Utils::copyToStream` + +`public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void` + +Copy the contents of a stream into another stream until the given number +of bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::copyToString` + +`public static function copyToString(StreamInterface $stream, int $maxLen = -1): string` + +Copy the contents of a stream into a string until the given number of +bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::hash` + +`public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string` + +Calculate a hash of a stream. + +This method reads the entire stream to calculate a rolling hash, based on +PHP's `hash_init` functions. + + +## `GuzzleHttp\Psr7\Utils::modifyRequest` + +`public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface` + +Clone and modify a request with the given changes. + +This method is useful for reducing the number of clones needed to mutate +a message. + +- method: (string) Changes the HTTP method. +- set_headers: (array) Sets the given headers. +- remove_headers: (array) Remove the given headers. +- body: (mixed) Sets the given body. +- uri: (UriInterface) Set the URI. +- query: (string) Set the query string value of the URI. +- version: (string) Set the protocol version. + + +## `GuzzleHttp\Psr7\Utils::readLine` + +`public static function readLine(StreamInterface $stream, int $maxLength = null): string` + +Read a line from the stream up to the maximum allowed buffer length. + + +## `GuzzleHttp\Psr7\Utils::streamFor` + +`public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface` + +Create a new stream based on the input type. + +Options is an associative array that can contain the following keys: + +- metadata: Array of custom metadata. +- size: Size of the stream. + +This method accepts the following `$resource` types: + +- `Psr\Http\Message\StreamInterface`: Returns the value as-is. +- `string`: Creates a stream object that uses the given string as the contents. +- `resource`: Creates a stream object that wraps the given PHP stream resource. +- `Iterator`: If the provided value implements `Iterator`, then a read-only + stream object will be created that wraps the given iterable. Each time the + stream is read from, data from the iterator will fill a buffer and will be + continuously called until the buffer is equal to the requested read size. + Subsequent read calls will first read from the buffer and then call `next` + on the underlying iterator until it is exhausted. +- `object` with `__toString()`: If the object has the `__toString()` method, + the object will be cast to a string and then a stream will be returned that + uses the string value. +- `NULL`: When `null` is passed, an empty stream object is returned. +- `callable` When a callable is passed, a read-only stream object will be + created that invokes the given callable. The callable is invoked with the + number of suggested bytes to read. The callable can return any number of + bytes, but MUST return `false` when there is no more data to return. The + stream object that wraps the callable will invoke the callable until the + number of requested bytes are available. Any additional bytes will be + buffered and used in subsequent reads. + +```php +$stream = GuzzleHttp\Psr7\Utils::streamFor('foo'); +$stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r')); + +$generator = function ($bytes) { + for ($i = 0; $i < $bytes; $i++) { + yield ' '; + } +} + +$stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100)); +``` + + +## `GuzzleHttp\Psr7\Utils::tryFopen` + +`public static function tryFopen(string $filename, string $mode): resource` + +Safely opens a PHP stream resource using a filename. + +When fopen fails, PHP normally raises a warning. This function adds an +error handler that checks for errors and throws an exception instead. + + +## `GuzzleHttp\Psr7\Utils::tryGetContents` + +`public static function tryGetContents(resource $stream): string` + +Safely gets the contents of a given stream. + +When stream_get_contents fails, PHP normally raises a warning. This +function adds an error handler that checks for errors and throws an +exception instead. + + +## `GuzzleHttp\Psr7\Utils::uriFor` + +`public static function uriFor(string|UriInterface $uri): UriInterface` + +Returns a UriInterface for the given value. + +This function accepts a string or UriInterface and returns a +UriInterface for the given value. If the value is already a +UriInterface, it is returned as-is. + + +## `GuzzleHttp\Psr7\MimeType::fromFilename` + +`public static function fromFilename(string $filename): string|null` + +Determines the mimetype of a file by looking at its extension. + + +## `GuzzleHttp\Psr7\MimeType::fromExtension` + +`public static function fromExtension(string $extension): string|null` + +Maps a file extensions to a mimetype. + + +## Upgrading from Function API + +The static API was first introduced in 1.7.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API was removed in 2.0.0. A migration table has been provided here for your convenience: + +| Original Function | Replacement Method | +|----------------|----------------| +| `str` | `Message::toString` | +| `uri_for` | `Utils::uriFor` | +| `stream_for` | `Utils::streamFor` | +| `parse_header` | `Header::parse` | +| `normalize_header` | `Header::normalize` | +| `modify_request` | `Utils::modifyRequest` | +| `rewind_body` | `Message::rewindBody` | +| `try_fopen` | `Utils::tryFopen` | +| `copy_to_string` | `Utils::copyToString` | +| `copy_to_stream` | `Utils::copyToStream` | +| `hash` | `Utils::hash` | +| `readline` | `Utils::readLine` | +| `parse_request` | `Message::parseRequest` | +| `parse_response` | `Message::parseResponse` | +| `parse_query` | `Query::parse` | +| `build_query` | `Query::build` | +| `mimetype_from_filename` | `MimeType::fromFilename` | +| `mimetype_from_extension` | `MimeType::fromExtension` | +| `_parse_message` | `Message::parseMessage` | +| `_parse_request_uri` | `Message::parseRequestUri` | +| `get_message_body_summary` | `Message::bodySummary` | +| `_caseless_remove` | `Utils::caselessRemove` | + + +# Additional URI Methods + +Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class, +this library also provides additional functionality when working with URIs as static methods. + +## URI Types + +An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference. +An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI, +the base URI. Relative references can be divided into several forms according to +[RFC 3986 Section 4.2](https://tools.ietf.org/html/rfc3986#section-4.2): + +- network-path references, e.g. `//example.com/path` +- absolute-path references, e.g. `/path` +- relative-path references, e.g. `subpath` + +The following methods can be used to identify the type of the URI. + +### `GuzzleHttp\Psr7\Uri::isAbsolute` + +`public static function isAbsolute(UriInterface $uri): bool` + +Whether the URI is absolute, i.e. it has a scheme. + +### `GuzzleHttp\Psr7\Uri::isNetworkPathReference` + +`public static function isNetworkPathReference(UriInterface $uri): bool` + +Whether the URI is a network-path reference. A relative reference that begins with two slash characters is +termed an network-path reference. + +### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference` + +`public static function isAbsolutePathReference(UriInterface $uri): bool` + +Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is +termed an absolute-path reference. + +### `GuzzleHttp\Psr7\Uri::isRelativePathReference` + +`public static function isRelativePathReference(UriInterface $uri): bool` + +Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is +termed a relative-path reference. + +### `GuzzleHttp\Psr7\Uri::isSameDocumentReference` + +`public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool` + +Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its +fragment component, identical to the base URI. When no base URI is given, only an empty URI reference +(apart from its fragment) is considered a same-document reference. + +## URI Components + +Additional methods to work with URI components. + +### `GuzzleHttp\Psr7\Uri::isDefaultPort` + +`public static function isDefaultPort(UriInterface $uri): bool` + +Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null +or the standard port. This method can be used independently of the implementation. + +### `GuzzleHttp\Psr7\Uri::composeComponents` + +`public static function composeComponents($scheme, $authority, $path, $query, $fragment): string` + +Composes a URI reference string from its various components according to +[RFC 3986 Section 5.3](https://tools.ietf.org/html/rfc3986#section-5.3). Usually this method does not need to be called +manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`. + +### `GuzzleHttp\Psr7\Uri::fromParts` + +`public static function fromParts(array $parts): UriInterface` + +Creates a URI from a hash of [`parse_url`](https://www.php.net/manual/en/function.parse-url.php) components. + + +### `GuzzleHttp\Psr7\Uri::withQueryValue` + +`public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface` + +Creates a new URI with a specific query string value. Any existing query string values that exactly match the +provided key are removed and replaced with the given key value pair. A value of null will set the query string +key without a value, e.g. "key" instead of "key=value". + +### `GuzzleHttp\Psr7\Uri::withQueryValues` + +`public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface` + +Creates a new URI with multiple query string values. It has the same behavior as `withQueryValue()` but for an +associative array of key => value. + +### `GuzzleHttp\Psr7\Uri::withoutQueryValue` + +`public static function withoutQueryValue(UriInterface $uri, $key): UriInterface` + +Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the +provided key are removed. + +## Cross-Origin Detection + +`GuzzleHttp\Psr7\UriComparator` provides methods to determine if a modified URL should be considered cross-origin. + +### `GuzzleHttp\Psr7\UriComparator::isCrossOrigin` + +`public static function isCrossOrigin(UriInterface $original, UriInterface $modified): bool` + +Determines if a modified URL should be considered cross-origin with respect to an original URL. + +## Reference Resolution + +`GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according +to [RFC 3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5). This is for example also what web browsers +do when resolving a link in a website based on the current request URI. + +### `GuzzleHttp\Psr7\UriResolver::resolve` + +`public static function resolve(UriInterface $base, UriInterface $rel): UriInterface` + +Converts the relative URI into a new URI that is resolved against the base URI. + +### `GuzzleHttp\Psr7\UriResolver::removeDotSegments` + +`public static function removeDotSegments(string $path): string` + +Removes dot segments from a path and returns the new path according to +[RFC 3986 Section 5.2.4](https://tools.ietf.org/html/rfc3986#section-5.2.4). + +### `GuzzleHttp\Psr7\UriResolver::relativize` + +`public static function relativize(UriInterface $base, UriInterface $target): UriInterface` + +Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve(): + +```php +(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) +``` + +One use-case is to use the current request URI as base URI and then generate relative links in your documents +to reduce the document size or offer self-contained downloadable document archives. + +```php +$base = new Uri('http://example.com/a/b/'); +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. +echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. +``` + +## Normalization and Comparison + +`GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to +[RFC 3986 Section 6](https://tools.ietf.org/html/rfc3986#section-6). + +### `GuzzleHttp\Psr7\UriNormalizer::normalize` + +`public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface` + +Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface. +This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask +of normalizations to apply. The following normalizations are available: + +- `UriNormalizer::PRESERVING_NORMALIZATIONS` + + Default normalizations which only include the ones that preserve semantics. + +- `UriNormalizer::CAPITALIZE_PERCENT_ENCODING` + + All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized. + + Example: `http://example.org/a%c2%b1b` → `http://example.org/a%C2%B1b` + +- `UriNormalizer::DECODE_UNRESERVED_CHARACTERS` + + Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of + ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should + not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved + characters by URI normalizers. + + Example: `http://example.org/%7Eusern%61me/` → `http://example.org/~username/` + +- `UriNormalizer::CONVERT_EMPTY_PATH` + + Converts the empty path to "/" for http and https URIs. + + Example: `http://example.org` → `http://example.org/` + +- `UriNormalizer::REMOVE_DEFAULT_HOST` + + Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host + "localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to + RFC 3986. + + Example: `file://localhost/myfile` → `file:///myfile` + +- `UriNormalizer::REMOVE_DEFAULT_PORT` + + Removes the default port of the given URI scheme from the URI. + + Example: `http://example.org:80/` → `http://example.org/` + +- `UriNormalizer::REMOVE_DOT_SEGMENTS` + + Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would + change the semantics of the URI reference. + + Example: `http://example.org/../a/b/../c/./d.html` → `http://example.org/a/c/d.html` + +- `UriNormalizer::REMOVE_DUPLICATE_SLASHES` + + Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes + and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization + may change the semantics. Encoded slashes (%2F) are not removed. + + Example: `http://example.org//foo///bar.html` → `http://example.org/foo/bar.html` + +- `UriNormalizer::SORT_QUERY_PARAMETERS` + + Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be + significant (this is not defined by the standard). So this normalization is not safe and may change the semantics + of the URI. + + Example: `?lang=en&article=fred` → `?article=fred&lang=en` + +### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent` + +`public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool` + +Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given +`$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent. +This of course assumes they will be resolved against the same base URI. If this is not the case, determination of +equivalence or difference of relative references does not mean anything. + + +## Version Guidance + +| Version | Status | PHP Version | +|---------|----------------|------------------| +| 1.x | Security fixes | >=5.4,<8.1 | +| 2.x | Latest | ^7.2.5 \|\| ^8.0 | + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/psr7/security/policy) for more information. + + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-psr7?utm_source=packagist-guzzlehttp-psr7&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/composer.json b/plugins/login-oauth2/vendor/guzzlehttp/psr7/composer.json new file mode 100644 index 0000000..cd91040 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/composer.json @@ -0,0 +1,96 @@ +{ + "name": "guzzlehttp/psr7", + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "request", + "response", + "message", + "stream", + "http", + "uri", + "url", + "psr-7" + ], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.1", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.29 || ^9.5.23" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\Psr7\\": "tests/" + } + }, + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + }, + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "config": { + "allow-plugins": { + "bamarni/composer-bin-plugin": true + }, + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/AppendStream.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/AppendStream.php new file mode 100644 index 0000000..cbcfaee --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/AppendStream.php @@ -0,0 +1,248 @@ +addStream($stream); + } + } + + public function __toString(): string + { + try { + $this->rewind(); + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + /** + * Add a stream to the AppendStream + * + * @param StreamInterface $stream Stream to append. Must be readable. + * + * @throws \InvalidArgumentException if the stream is not readable + */ + public function addStream(StreamInterface $stream): void + { + if (!$stream->isReadable()) { + throw new \InvalidArgumentException('Each stream must be readable'); + } + + // The stream is only seekable if all streams are seekable + if (!$stream->isSeekable()) { + $this->seekable = false; + } + + $this->streams[] = $stream; + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Closes each attached stream. + */ + public function close(): void + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->close(); + } + + $this->streams = []; + } + + /** + * Detaches each attached stream. + * + * Returns null as it's not clear which underlying stream resource to return. + */ + public function detach() + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->detach(); + } + + $this->streams = []; + + return null; + } + + public function tell(): int + { + return $this->pos; + } + + /** + * Tries to calculate the size by adding the size of each stream. + * + * If any of the streams do not return a valid number, then the size of the + * append stream cannot be determined and null is returned. + */ + public function getSize(): ?int + { + $size = 0; + + foreach ($this->streams as $stream) { + $s = $stream->getSize(); + if ($s === null) { + return null; + } + $size += $s; + } + + return $size; + } + + public function eof(): bool + { + return !$this->streams || + ($this->current >= count($this->streams) - 1 && + $this->streams[$this->current]->eof()); + } + + public function rewind(): void + { + $this->seek(0); + } + + /** + * Attempts to seek to the given position. Only supports SEEK_SET. + */ + public function seek($offset, $whence = SEEK_SET): void + { + if (!$this->seekable) { + throw new \RuntimeException('This AppendStream is not seekable'); + } elseif ($whence !== SEEK_SET) { + throw new \RuntimeException('The AppendStream can only seek with SEEK_SET'); + } + + $this->pos = $this->current = 0; + + // Rewind each stream + foreach ($this->streams as $i => $stream) { + try { + $stream->rewind(); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to seek stream ' + . $i . ' of the AppendStream', 0, $e); + } + } + + // Seek to the actual position by reading from each stream + while ($this->pos < $offset && !$this->eof()) { + $result = $this->read(min(8096, $offset - $this->pos)); + if ($result === '') { + break; + } + } + } + + /** + * Reads from all of the appended streams until the length is met or EOF. + */ + public function read($length): string + { + $buffer = ''; + $total = count($this->streams) - 1; + $remaining = $length; + $progressToNext = false; + + while ($remaining > 0) { + // Progress to the next stream if needed. + if ($progressToNext || $this->streams[$this->current]->eof()) { + $progressToNext = false; + if ($this->current === $total) { + break; + } + $this->current++; + } + + $result = $this->streams[$this->current]->read($remaining); + + if ($result === '') { + $progressToNext = true; + continue; + } + + $buffer .= $result; + $remaining = $length - strlen($buffer); + } + + $this->pos += strlen($buffer); + + return $buffer; + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return false; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function write($string): int + { + throw new \RuntimeException('Cannot write to an AppendStream'); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + return $key ? null : []; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/BufferStream.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/BufferStream.php new file mode 100644 index 0000000..21be8c0 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/BufferStream.php @@ -0,0 +1,149 @@ +hwm = $hwm; + } + + public function __toString(): string + { + return $this->getContents(); + } + + public function getContents(): string + { + $buffer = $this->buffer; + $this->buffer = ''; + + return $buffer; + } + + public function close(): void + { + $this->buffer = ''; + } + + public function detach() + { + $this->close(); + + return null; + } + + public function getSize(): ?int + { + return strlen($this->buffer); + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return true; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a BufferStream'); + } + + public function eof(): bool + { + return strlen($this->buffer) === 0; + } + + public function tell(): int + { + throw new \RuntimeException('Cannot determine the position of a BufferStream'); + } + + /** + * Reads data from the buffer. + */ + public function read($length): string + { + $currentLength = strlen($this->buffer); + + if ($length >= $currentLength) { + // No need to slice the buffer because we don't have enough data. + $result = $this->buffer; + $this->buffer = ''; + } else { + // Slice up the result to provide a subset of the buffer. + $result = substr($this->buffer, 0, $length); + $this->buffer = substr($this->buffer, $length); + } + + return $result; + } + + /** + * Writes data to the buffer. + */ + public function write($string): int + { + $this->buffer .= $string; + + if (strlen($this->buffer) >= $this->hwm) { + return 0; + } + + return strlen($string); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + if ($key === 'hwm') { + return $this->hwm; + } + + return $key ? null : []; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/CachingStream.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/CachingStream.php new file mode 100644 index 0000000..f34722c --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/CachingStream.php @@ -0,0 +1,153 @@ +remoteStream = $stream; + $this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+')); + } + + public function getSize(): ?int + { + $remoteSize = $this->remoteStream->getSize(); + + if (null === $remoteSize) { + return null; + } + + return max($this->stream->getSize(), $remoteSize); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + if ($whence === SEEK_SET) { + $byte = $offset; + } elseif ($whence === SEEK_CUR) { + $byte = $offset + $this->tell(); + } elseif ($whence === SEEK_END) { + $size = $this->remoteStream->getSize(); + if ($size === null) { + $size = $this->cacheEntireStream(); + } + $byte = $size + $offset; + } else { + throw new \InvalidArgumentException('Invalid whence'); + } + + $diff = $byte - $this->stream->getSize(); + + if ($diff > 0) { + // Read the remoteStream until we have read in at least the amount + // of bytes requested, or we reach the end of the file. + while ($diff > 0 && !$this->remoteStream->eof()) { + $this->read($diff); + $diff = $byte - $this->stream->getSize(); + } + } else { + // We can just do a normal seek since we've already seen this byte. + $this->stream->seek($byte); + } + } + + public function read($length): string + { + // Perform a regular read on any previously read data from the buffer + $data = $this->stream->read($length); + $remaining = $length - strlen($data); + + // More data was requested so read from the remote stream + if ($remaining) { + // If data was written to the buffer in a position that would have + // been filled from the remote stream, then we must skip bytes on + // the remote stream to emulate overwriting bytes from that + // position. This mimics the behavior of other PHP stream wrappers. + $remoteData = $this->remoteStream->read( + $remaining + $this->skipReadBytes + ); + + if ($this->skipReadBytes) { + $len = strlen($remoteData); + $remoteData = substr($remoteData, $this->skipReadBytes); + $this->skipReadBytes = max(0, $this->skipReadBytes - $len); + } + + $data .= $remoteData; + $this->stream->write($remoteData); + } + + return $data; + } + + public function write($string): int + { + // When appending to the end of the currently read stream, you'll want + // to skip bytes from being read from the remote stream to emulate + // other stream wrappers. Basically replacing bytes of data of a fixed + // length. + $overflow = (strlen($string) + $this->tell()) - $this->remoteStream->tell(); + if ($overflow > 0) { + $this->skipReadBytes += $overflow; + } + + return $this->stream->write($string); + } + + public function eof(): bool + { + return $this->stream->eof() && $this->remoteStream->eof(); + } + + /** + * Close both the remote stream and buffer stream + */ + public function close(): void + { + $this->remoteStream->close(); + $this->stream->close(); + } + + private function cacheEntireStream(): int + { + $target = new FnStream(['write' => 'strlen']); + Utils::copyToStream($this, $target); + + return $this->tell(); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/DroppingStream.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/DroppingStream.php new file mode 100644 index 0000000..6e3d209 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/DroppingStream.php @@ -0,0 +1,49 @@ +stream = $stream; + $this->maxLength = $maxLength; + } + + public function write($string): int + { + $diff = $this->maxLength - $this->stream->getSize(); + + // Begin returning 0 when the underlying stream is too large. + if ($diff <= 0) { + return 0; + } + + // Write the stream or a subset of the stream if needed. + if (strlen($string) < $diff) { + return $this->stream->write($string); + } + + return $this->stream->write(substr($string, 0, $diff)); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php new file mode 100644 index 0000000..3a08477 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Exception/MalformedUriException.php @@ -0,0 +1,14 @@ + */ + private $methods; + + /** + * @param array $methods Hash of method name to a callable. + */ + public function __construct(array $methods) + { + $this->methods = $methods; + + // Create the functions on the class + foreach ($methods as $name => $fn) { + $this->{'_fn_' . $name} = $fn; + } + } + + /** + * Lazily determine which methods are not implemented. + * + * @throws \BadMethodCallException + */ + public function __get(string $name): void + { + throw new \BadMethodCallException(str_replace('_fn_', '', $name) + . '() is not implemented in the FnStream'); + } + + /** + * The close method is called on the underlying stream only if possible. + */ + public function __destruct() + { + if (isset($this->_fn_close)) { + call_user_func($this->_fn_close); + } + } + + /** + * An unserialize would allow the __destruct to run when the unserialized value goes out of scope. + * + * @throws \LogicException + */ + public function __wakeup(): void + { + throw new \LogicException('FnStream should never be unserialized'); + } + + /** + * Adds custom functionality to an underlying stream by intercepting + * specific method calls. + * + * @param StreamInterface $stream Stream to decorate + * @param array $methods Hash of method name to a closure + * + * @return FnStream + */ + public static function decorate(StreamInterface $stream, array $methods) + { + // If any of the required methods were not provided, then simply + // proxy to the decorated stream. + foreach (array_diff(self::SLOTS, array_keys($methods)) as $diff) { + /** @var callable $callable */ + $callable = [$stream, $diff]; + $methods[$diff] = $callable; + } + + return new self($methods); + } + + public function __toString(): string + { + try { + return call_user_func($this->_fn___toString); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function close(): void + { + call_user_func($this->_fn_close); + } + + public function detach() + { + return call_user_func($this->_fn_detach); + } + + public function getSize(): ?int + { + return call_user_func($this->_fn_getSize); + } + + public function tell(): int + { + return call_user_func($this->_fn_tell); + } + + public function eof(): bool + { + return call_user_func($this->_fn_eof); + } + + public function isSeekable(): bool + { + return call_user_func($this->_fn_isSeekable); + } + + public function rewind(): void + { + call_user_func($this->_fn_rewind); + } + + public function seek($offset, $whence = SEEK_SET): void + { + call_user_func($this->_fn_seek, $offset, $whence); + } + + public function isWritable(): bool + { + return call_user_func($this->_fn_isWritable); + } + + public function write($string): int + { + return call_user_func($this->_fn_write, $string); + } + + public function isReadable(): bool + { + return call_user_func($this->_fn_isReadable); + } + + public function read($length): string + { + return call_user_func($this->_fn_read, $length); + } + + public function getContents(): string + { + return call_user_func($this->_fn_getContents); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + return call_user_func($this->_fn_getMetadata, $key); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Header.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Header.php new file mode 100644 index 0000000..4d7005b --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Header.php @@ -0,0 +1,134 @@ +]+>|[^=]+/', $kvp, $matches)) { + $m = $matches[0]; + if (isset($m[1])) { + $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed); + } else { + $part[] = trim($m[0], $trimmed); + } + } + } + if ($part) { + $params[] = $part; + } + } + } + + return $params; + } + + /** + * Converts an array of header values that may contain comma separated + * headers into an array of headers with no comma separated values. + * + * @param string|array $header Header to normalize. + * + * @deprecated Use self::splitList() instead. + */ + public static function normalize($header): array + { + $result = []; + foreach ((array) $header as $value) { + foreach (self::splitList($value) as $parsed) { + $result[] = $parsed; + } + } + + return $result; + } + + /** + * Splits a HTTP header defined to contain a comma-separated list into + * each individual value. Empty values will be removed. + * + * Example headers include 'accept', 'cache-control' and 'if-none-match'. + * + * This method must not be used to parse headers that are not defined as + * a list, such as 'user-agent' or 'set-cookie'. + * + * @param string|string[] $values Header value as returned by MessageInterface::getHeader() + * + * @return string[] + */ + public static function splitList($values): array + { + if (!\is_array($values)) { + $values = [$values]; + } + + $result = []; + foreach ($values as $value) { + if (!\is_string($value)) { + throw new \TypeError('$header must either be a string or an array containing strings.'); + } + + $v = ''; + $isQuoted = false; + $isEscaped = false; + for ($i = 0, $max = \strlen($value); $i < $max; $i++) { + if ($isEscaped) { + $v .= $value[$i]; + $isEscaped = false; + + continue; + } + + if (!$isQuoted && $value[$i] === ',') { + $v = \trim($v); + if ($v !== '') { + $result[] = $v; + } + + $v = ''; + continue; + } + + if ($isQuoted && $value[$i] === '\\') { + $isEscaped = true; + $v .= $value[$i]; + + continue; + } + if ($value[$i] === '"') { + $isQuoted = !$isQuoted; + $v .= $value[$i]; + + continue; + } + + $v .= $value[$i]; + } + + $v = \trim($v); + if ($v !== '') { + $result[] = $v; + } + } + + return $result; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/HttpFactory.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/HttpFactory.php new file mode 100644 index 0000000..30be222 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/HttpFactory.php @@ -0,0 +1,100 @@ +getSize(); + } + + return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType); + } + + public function createStream(string $content = ''): StreamInterface + { + return Utils::streamFor($content); + } + + public function createStreamFromFile(string $file, string $mode = 'r'): StreamInterface + { + try { + $resource = Utils::tryFopen($file, $mode); + } catch (\RuntimeException $e) { + if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'], true)) { + throw new \InvalidArgumentException(sprintf('Invalid file opening mode "%s"', $mode), 0, $e); + } + + throw $e; + } + + return Utils::streamFor($resource); + } + + public function createStreamFromResource($resource): StreamInterface + { + return Utils::streamFor($resource); + } + + public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface + { + if (empty($method)) { + if (!empty($serverParams['REQUEST_METHOD'])) { + $method = $serverParams['REQUEST_METHOD']; + } else { + throw new \InvalidArgumentException('Cannot determine HTTP method'); + } + } + + return new ServerRequest($method, $uri, [], null, '1.1', $serverParams); + } + + public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface + { + return new Response($code, [], null, '1.1', $reasonPhrase); + } + + public function createRequest(string $method, $uri): RequestInterface + { + return new Request($method, $uri); + } + + public function createUri(string $uri = ''): UriInterface + { + return new Uri($uri); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/InflateStream.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/InflateStream.php new file mode 100644 index 0000000..8e00f1c --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/InflateStream.php @@ -0,0 +1,37 @@ + 15 + 32]); + $this->stream = $stream->isSeekable() ? new Stream($resource) : new NoSeekStream(new Stream($resource)); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/LazyOpenStream.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/LazyOpenStream.php new file mode 100644 index 0000000..5618331 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/LazyOpenStream.php @@ -0,0 +1,41 @@ +filename = $filename; + $this->mode = $mode; + } + + /** + * Creates the underlying stream lazily when required. + */ + protected function createStream(): StreamInterface + { + return Utils::streamFor(Utils::tryFopen($this->filename, $this->mode)); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/LimitStream.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/LimitStream.php new file mode 100644 index 0000000..fb22325 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/LimitStream.php @@ -0,0 +1,157 @@ +stream = $stream; + $this->setLimit($limit); + $this->setOffset($offset); + } + + public function eof(): bool + { + // Always return true if the underlying stream is EOF + if ($this->stream->eof()) { + return true; + } + + // No limit and the underlying stream is not at EOF + if ($this->limit === -1) { + return false; + } + + return $this->stream->tell() >= $this->offset + $this->limit; + } + + /** + * Returns the size of the limited subset of data + */ + public function getSize(): ?int + { + if (null === ($length = $this->stream->getSize())) { + return null; + } elseif ($this->limit === -1) { + return $length - $this->offset; + } else { + return min($this->limit, $length - $this->offset); + } + } + + /** + * Allow for a bounded seek on the read limited stream + */ + public function seek($offset, $whence = SEEK_SET): void + { + if ($whence !== SEEK_SET || $offset < 0) { + throw new \RuntimeException(sprintf( + 'Cannot seek to offset %s with whence %s', + $offset, + $whence + )); + } + + $offset += $this->offset; + + if ($this->limit !== -1) { + if ($offset > $this->offset + $this->limit) { + $offset = $this->offset + $this->limit; + } + } + + $this->stream->seek($offset); + } + + /** + * Give a relative tell() + */ + public function tell(): int + { + return $this->stream->tell() - $this->offset; + } + + /** + * Set the offset to start limiting from + * + * @param int $offset Offset to seek to and begin byte limiting from + * + * @throws \RuntimeException if the stream cannot be seeked. + */ + public function setOffset(int $offset): void + { + $current = $this->stream->tell(); + + if ($current !== $offset) { + // If the stream cannot seek to the offset position, then read to it + if ($this->stream->isSeekable()) { + $this->stream->seek($offset); + } elseif ($current > $offset) { + throw new \RuntimeException("Could not seek to stream offset $offset"); + } else { + $this->stream->read($offset - $current); + } + } + + $this->offset = $offset; + } + + /** + * Set the limit of bytes that the decorator allows to be read from the + * stream. + * + * @param int $limit Number of bytes to allow to be read from the stream. + * Use -1 for no limit. + */ + public function setLimit(int $limit): void + { + $this->limit = $limit; + } + + public function read($length): string + { + if ($this->limit === -1) { + return $this->stream->read($length); + } + + // Check if the current position is less than the total allowed + // bytes + original offset + $remaining = ($this->offset + $this->limit) - $this->stream->tell(); + if ($remaining > 0) { + // Only return the amount of requested data, ensuring that the byte + // limit is not exceeded + return $this->stream->read(min($remaining, $length)); + } + + return ''; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Message.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Message.php new file mode 100644 index 0000000..61c1a5d --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Message.php @@ -0,0 +1,246 @@ +getMethod() . ' ' + . $message->getRequestTarget()) + . ' HTTP/' . $message->getProtocolVersion(); + if (!$message->hasHeader('host')) { + $msg .= "\r\nHost: " . $message->getUri()->getHost(); + } + } elseif ($message instanceof ResponseInterface) { + $msg = 'HTTP/' . $message->getProtocolVersion() . ' ' + . $message->getStatusCode() . ' ' + . $message->getReasonPhrase(); + } else { + throw new \InvalidArgumentException('Unknown message type'); + } + + foreach ($message->getHeaders() as $name => $values) { + if (strtolower($name) === 'set-cookie') { + foreach ($values as $value) { + $msg .= "\r\n{$name}: " . $value; + } + } else { + $msg .= "\r\n{$name}: " . implode(', ', $values); + } + } + + return "{$msg}\r\n\r\n" . $message->getBody(); + } + + /** + * Get a short summary of the message body. + * + * Will return `null` if the response is not printable. + * + * @param MessageInterface $message The message to get the body summary + * @param int $truncateAt The maximum allowed size of the summary + */ + public static function bodySummary(MessageInterface $message, int $truncateAt = 120): ?string + { + $body = $message->getBody(); + + if (!$body->isSeekable() || !$body->isReadable()) { + return null; + } + + $size = $body->getSize(); + + if ($size === 0) { + return null; + } + + $body->rewind(); + $summary = $body->read($truncateAt); + $body->rewind(); + + if ($size > $truncateAt) { + $summary .= ' (truncated...)'; + } + + // Matches any printable character, including unicode characters: + // letters, marks, numbers, punctuation, spacing, and separators. + if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary)) { + return null; + } + + return $summary; + } + + /** + * Attempts to rewind a message body and throws an exception on failure. + * + * The body of the message will only be rewound if a call to `tell()` + * returns a value other than `0`. + * + * @param MessageInterface $message Message to rewind + * + * @throws \RuntimeException + */ + public static function rewindBody(MessageInterface $message): void + { + $body = $message->getBody(); + + if ($body->tell()) { + $body->rewind(); + } + } + + /** + * Parses an HTTP message into an associative array. + * + * The array contains the "start-line" key containing the start line of + * the message, "headers" key containing an associative array of header + * array values, and a "body" key containing the body of the message. + * + * @param string $message HTTP request or response to parse. + */ + public static function parseMessage(string $message): array + { + if (!$message) { + throw new \InvalidArgumentException('Invalid message'); + } + + $message = ltrim($message, "\r\n"); + + $messageParts = preg_split("/\r?\n\r?\n/", $message, 2); + + if ($messageParts === false || count($messageParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing header delimiter'); + } + + [$rawHeaders, $body] = $messageParts; + $rawHeaders .= "\r\n"; // Put back the delimiter we split previously + $headerParts = preg_split("/\r?\n/", $rawHeaders, 2); + + if ($headerParts === false || count($headerParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing status line'); + } + + [$startLine, $rawHeaders] = $headerParts; + + if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') { + // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0 + $rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders); + } + + /** @var array[] $headerLines */ + $count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER); + + // If these aren't the same, then one line didn't match and there's an invalid header. + if ($count !== substr_count($rawHeaders, "\n")) { + // Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4 + if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) { + throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding'); + } + + throw new \InvalidArgumentException('Invalid header syntax'); + } + + $headers = []; + + foreach ($headerLines as $headerLine) { + $headers[$headerLine[1]][] = $headerLine[2]; + } + + return [ + 'start-line' => $startLine, + 'headers' => $headers, + 'body' => $body, + ]; + } + + /** + * Constructs a URI for an HTTP request message. + * + * @param string $path Path from the start-line + * @param array $headers Array of headers (each value an array). + */ + public static function parseRequestUri(string $path, array $headers): string + { + $hostKey = array_filter(array_keys($headers), function ($k) { + // Numeric array keys are converted to int by PHP. + $k = (string) $k; + + return strtolower($k) === 'host'; + }); + + // If no host is found, then a full URI cannot be constructed. + if (!$hostKey) { + return $path; + } + + $host = $headers[reset($hostKey)][0]; + $scheme = substr($host, -4) === ':443' ? 'https' : 'http'; + + return $scheme . '://' . $host . '/' . ltrim($path, '/'); + } + + /** + * Parses a request message string into a request object. + * + * @param string $message Request message string. + */ + public static function parseRequest(string $message): RequestInterface + { + $data = self::parseMessage($message); + $matches = []; + if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) { + throw new \InvalidArgumentException('Invalid request string'); + } + $parts = explode(' ', $data['start-line'], 3); + $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1'; + + $request = new Request( + $parts[0], + $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1], + $data['headers'], + $data['body'], + $version + ); + + return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]); + } + + /** + * Parses a response message string into a response object. + * + * @param string $message Response message string. + */ + public static function parseResponse(string $message): ResponseInterface + { + $data = self::parseMessage($message); + // According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space + // between status-code and reason-phrase is required. But browsers accept + // responses without space and reason as well. + if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) { + throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']); + } + $parts = explode(' ', $data['start-line'], 3); + + return new Response( + (int) $parts[1], + $data['headers'], + $data['body'], + explode('/', $parts[0])[1], + $parts[2] ?? null + ); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MessageTrait.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MessageTrait.php new file mode 100644 index 0000000..d2dc28b --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MessageTrait.php @@ -0,0 +1,264 @@ + Map of all registered headers, as original name => array of values */ + private $headers = []; + + /** @var array Map of lowercase header name => original name at registration */ + private $headerNames = []; + + /** @var string */ + private $protocol = '1.1'; + + /** @var StreamInterface|null */ + private $stream; + + public function getProtocolVersion(): string + { + return $this->protocol; + } + + public function withProtocolVersion($version): MessageInterface + { + if ($this->protocol === $version) { + return $this; + } + + $new = clone $this; + $new->protocol = $version; + return $new; + } + + public function getHeaders(): array + { + return $this->headers; + } + + public function hasHeader($header): bool + { + return isset($this->headerNames[strtolower($header)]); + } + + public function getHeader($header): array + { + $header = strtolower($header); + + if (!isset($this->headerNames[$header])) { + return []; + } + + $header = $this->headerNames[$header]; + + return $this->headers[$header]; + } + + public function getHeaderLine($header): string + { + return implode(', ', $this->getHeader($header)); + } + + public function withHeader($header, $value): MessageInterface + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + unset($new->headers[$new->headerNames[$normalized]]); + } + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + + return $new; + } + + public function withAddedHeader($header, $value): MessageInterface + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $new->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + } + + return $new; + } + + public function withoutHeader($header): MessageInterface + { + $normalized = strtolower($header); + + if (!isset($this->headerNames[$normalized])) { + return $this; + } + + $header = $this->headerNames[$normalized]; + + $new = clone $this; + unset($new->headers[$header], $new->headerNames[$normalized]); + + return $new; + } + + public function getBody(): StreamInterface + { + if (!$this->stream) { + $this->stream = Utils::streamFor(''); + } + + return $this->stream; + } + + public function withBody(StreamInterface $body): MessageInterface + { + if ($body === $this->stream) { + return $this; + } + + $new = clone $this; + $new->stream = $body; + return $new; + } + + /** + * @param array $headers + */ + private function setHeaders(array $headers): void + { + $this->headerNames = $this->headers = []; + foreach ($headers as $header => $value) { + // Numeric array keys are converted to int by PHP. + $header = (string) $header; + + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + if (isset($this->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $this->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $this->headerNames[$normalized] = $header; + $this->headers[$header] = $value; + } + } + } + + /** + * @param mixed $value + * + * @return string[] + */ + private function normalizeHeaderValue($value): array + { + if (!is_array($value)) { + return $this->trimAndValidateHeaderValues([$value]); + } + + if (count($value) === 0) { + throw new \InvalidArgumentException('Header value can not be an empty array.'); + } + + return $this->trimAndValidateHeaderValues($value); + } + + /** + * Trims whitespace from the header values. + * + * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field. + * + * header-field = field-name ":" OWS field-value OWS + * OWS = *( SP / HTAB ) + * + * @param mixed[] $values Header values + * + * @return string[] Trimmed header values + * + * @see https://tools.ietf.org/html/rfc7230#section-3.2.4 + */ + private function trimAndValidateHeaderValues(array $values): array + { + return array_map(function ($value) { + if (!is_scalar($value) && null !== $value) { + throw new \InvalidArgumentException(sprintf( + 'Header value must be scalar or null but %s provided.', + is_object($value) ? get_class($value) : gettype($value) + )); + } + + $trimmed = trim((string) $value, " \t"); + $this->assertValue($trimmed); + + return $trimmed; + }, array_values($values)); + } + + /** + * @see https://tools.ietf.org/html/rfc7230#section-3.2 + * + * @param mixed $header + */ + private function assertHeader($header): void + { + if (!is_string($header)) { + throw new \InvalidArgumentException(sprintf( + 'Header name must be a string but %s provided.', + is_object($header) ? get_class($header) : gettype($header) + )); + } + + if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/', $header)) { + throw new \InvalidArgumentException( + sprintf( + '"%s" is not valid header name', + $header + ) + ); + } + } + + /** + * @see https://tools.ietf.org/html/rfc7230#section-3.2 + * + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * VCHAR = %x21-7E + * obs-text = %x80-FF + * obs-fold = CRLF 1*( SP / HTAB ) + */ + private function assertValue(string $value): void + { + // The regular expression intentionally does not support the obs-fold production, because as + // per RFC 7230#3.2.4: + // + // A sender MUST NOT generate a message that includes + // line folding (i.e., that has any field-value that contains a match to + // the obs-fold rule) unless the message is intended for packaging + // within the message/http media type. + // + // Clients must not send a request with line folding and a server sending folded headers is + // likely very rare. Line folding is a fairly obscure feature of HTTP/1.1 and thus not accepting + // folding is not likely to break any legitimate use case. + if (! preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/', $value)) { + throw new \InvalidArgumentException(sprintf('"%s" is not valid header value', $value)); + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MimeType.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MimeType.php new file mode 100644 index 0000000..0debbd1 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MimeType.php @@ -0,0 +1,1237 @@ + 'application/vnd.1000minds.decision-model+xml', + '3dml' => 'text/vnd.in3d.3dml', + '3ds' => 'image/x-3ds', + '3g2' => 'video/3gpp2', + '3gp' => 'video/3gp', + '3gpp' => 'video/3gpp', + '3mf' => 'model/3mf', + '7z' => 'application/x-7z-compressed', + '7zip' => 'application/x-7z-compressed', + '123' => 'application/vnd.lotus-1-2-3', + 'aab' => 'application/x-authorware-bin', + 'aac' => 'audio/x-acc', + 'aam' => 'application/x-authorware-map', + 'aas' => 'application/x-authorware-seg', + 'abw' => 'application/x-abiword', + 'ac' => 'application/vnd.nokia.n-gage.ac+xml', + 'ac3' => 'audio/ac3', + 'acc' => 'application/vnd.americandynamics.acc', + 'ace' => 'application/x-ace-compressed', + 'acu' => 'application/vnd.acucobol', + 'acutc' => 'application/vnd.acucorp', + 'adp' => 'audio/adpcm', + 'aep' => 'application/vnd.audiograph', + 'afm' => 'application/x-font-type1', + 'afp' => 'application/vnd.ibm.modcap', + 'age' => 'application/vnd.age', + 'ahead' => 'application/vnd.ahead.space', + 'ai' => 'application/pdf', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'air' => 'application/vnd.adobe.air-application-installer-package+zip', + 'ait' => 'application/vnd.dvb.ait', + 'ami' => 'application/vnd.amiga.ami', + 'amr' => 'audio/amr', + 'apk' => 'application/vnd.android.package-archive', + 'apng' => 'image/apng', + 'appcache' => 'text/cache-manifest', + 'application' => 'application/x-ms-application', + 'apr' => 'application/vnd.lotus-approach', + 'arc' => 'application/x-freearc', + 'arj' => 'application/x-arj', + 'asc' => 'application/pgp-signature', + 'asf' => 'video/x-ms-asf', + 'asm' => 'text/x-asm', + 'aso' => 'application/vnd.accpac.simply.aso', + 'asx' => 'video/x-ms-asf', + 'atc' => 'application/vnd.acucorp', + 'atom' => 'application/atom+xml', + 'atomcat' => 'application/atomcat+xml', + 'atomdeleted' => 'application/atomdeleted+xml', + 'atomsvc' => 'application/atomsvc+xml', + 'atx' => 'application/vnd.antix.game-component', + 'au' => 'audio/x-au', + 'avci' => 'image/avci', + 'avcs' => 'image/avcs', + 'avi' => 'video/x-msvideo', + 'avif' => 'image/avif', + 'aw' => 'application/applixware', + 'azf' => 'application/vnd.airzip.filesecure.azf', + 'azs' => 'application/vnd.airzip.filesecure.azs', + 'azv' => 'image/vnd.airzip.accelerator.azv', + 'azw' => 'application/vnd.amazon.ebook', + 'b16' => 'image/vnd.pco.b16', + 'bat' => 'application/x-msdownload', + 'bcpio' => 'application/x-bcpio', + 'bdf' => 'application/x-font-bdf', + 'bdm' => 'application/vnd.syncml.dm+wbxml', + 'bdoc' => 'application/x-bdoc', + 'bed' => 'application/vnd.realvnc.bed', + 'bh2' => 'application/vnd.fujitsu.oasysprs', + 'bin' => 'application/octet-stream', + 'blb' => 'application/x-blorb', + 'blorb' => 'application/x-blorb', + 'bmi' => 'application/vnd.bmi', + 'bmml' => 'application/vnd.balsamiq.bmml+xml', + 'bmp' => 'image/bmp', + 'book' => 'application/vnd.framemaker', + 'box' => 'application/vnd.previewsystems.box', + 'boz' => 'application/x-bzip2', + 'bpk' => 'application/octet-stream', + 'bpmn' => 'application/octet-stream', + 'bsp' => 'model/vnd.valve.source.compiled-map', + 'btif' => 'image/prs.btif', + 'buffer' => 'application/octet-stream', + 'bz' => 'application/x-bzip', + 'bz2' => 'application/x-bzip2', + 'c' => 'text/x-c', + 'c4d' => 'application/vnd.clonk.c4group', + 'c4f' => 'application/vnd.clonk.c4group', + 'c4g' => 'application/vnd.clonk.c4group', + 'c4p' => 'application/vnd.clonk.c4group', + 'c4u' => 'application/vnd.clonk.c4group', + 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', + 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', + 'cab' => 'application/vnd.ms-cab-compressed', + 'caf' => 'audio/x-caf', + 'cap' => 'application/vnd.tcpdump.pcap', + 'car' => 'application/vnd.curl.car', + 'cat' => 'application/vnd.ms-pki.seccat', + 'cb7' => 'application/x-cbr', + 'cba' => 'application/x-cbr', + 'cbr' => 'application/x-cbr', + 'cbt' => 'application/x-cbr', + 'cbz' => 'application/x-cbr', + 'cc' => 'text/x-c', + 'cco' => 'application/x-cocoa', + 'cct' => 'application/x-director', + 'ccxml' => 'application/ccxml+xml', + 'cdbcmsg' => 'application/vnd.contact.cmsg', + 'cdf' => 'application/x-netcdf', + 'cdfx' => 'application/cdfx+xml', + 'cdkey' => 'application/vnd.mediastation.cdkey', + 'cdmia' => 'application/cdmi-capability', + 'cdmic' => 'application/cdmi-container', + 'cdmid' => 'application/cdmi-domain', + 'cdmio' => 'application/cdmi-object', + 'cdmiq' => 'application/cdmi-queue', + 'cdr' => 'application/cdr', + 'cdx' => 'chemical/x-cdx', + 'cdxml' => 'application/vnd.chemdraw+xml', + 'cdy' => 'application/vnd.cinderella', + 'cer' => 'application/pkix-cert', + 'cfs' => 'application/x-cfs-compressed', + 'cgm' => 'image/cgm', + 'chat' => 'application/x-chat', + 'chm' => 'application/vnd.ms-htmlhelp', + 'chrt' => 'application/vnd.kde.kchart', + 'cif' => 'chemical/x-cif', + 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', + 'cil' => 'application/vnd.ms-artgalry', + 'cjs' => 'application/node', + 'cla' => 'application/vnd.claymore', + 'class' => 'application/octet-stream', + 'clkk' => 'application/vnd.crick.clicker.keyboard', + 'clkp' => 'application/vnd.crick.clicker.palette', + 'clkt' => 'application/vnd.crick.clicker.template', + 'clkw' => 'application/vnd.crick.clicker.wordbank', + 'clkx' => 'application/vnd.crick.clicker', + 'clp' => 'application/x-msclip', + 'cmc' => 'application/vnd.cosmocaller', + 'cmdf' => 'chemical/x-cmdf', + 'cml' => 'chemical/x-cml', + 'cmp' => 'application/vnd.yellowriver-custom-menu', + 'cmx' => 'image/x-cmx', + 'cod' => 'application/vnd.rim.cod', + 'coffee' => 'text/coffeescript', + 'com' => 'application/x-msdownload', + 'conf' => 'text/plain', + 'cpio' => 'application/x-cpio', + 'cpl' => 'application/cpl+xml', + 'cpp' => 'text/x-c', + 'cpt' => 'application/mac-compactpro', + 'crd' => 'application/x-mscardfile', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'crx' => 'application/x-chrome-extension', + 'cryptonote' => 'application/vnd.rig.cryptonote', + 'csh' => 'application/x-csh', + 'csl' => 'application/vnd.citationstyles.style+xml', + 'csml' => 'chemical/x-csml', + 'csp' => 'application/vnd.commonspace', + 'csr' => 'application/octet-stream', + 'css' => 'text/css', + 'cst' => 'application/x-director', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'curl' => 'text/vnd.curl', + 'cww' => 'application/prs.cww', + 'cxt' => 'application/x-director', + 'cxx' => 'text/x-c', + 'dae' => 'model/vnd.collada+xml', + 'daf' => 'application/vnd.mobius.daf', + 'dart' => 'application/vnd.dart', + 'dataless' => 'application/vnd.fdsn.seed', + 'davmount' => 'application/davmount+xml', + 'dbf' => 'application/vnd.dbf', + 'dbk' => 'application/docbook+xml', + 'dcr' => 'application/x-director', + 'dcurl' => 'text/vnd.curl.dcurl', + 'dd2' => 'application/vnd.oma.dd2+xml', + 'ddd' => 'application/vnd.fujixerox.ddd', + 'ddf' => 'application/vnd.syncml.dmddf+xml', + 'dds' => 'image/vnd.ms-dds', + 'deb' => 'application/x-debian-package', + 'def' => 'text/plain', + 'deploy' => 'application/octet-stream', + 'der' => 'application/x-x509-ca-cert', + 'dfac' => 'application/vnd.dreamfactory', + 'dgc' => 'application/x-dgc-compressed', + 'dic' => 'text/x-c', + 'dir' => 'application/x-director', + 'dis' => 'application/vnd.mobius.dis', + 'disposition-notification' => 'message/disposition-notification', + 'dist' => 'application/octet-stream', + 'distz' => 'application/octet-stream', + 'djv' => 'image/vnd.djvu', + 'djvu' => 'image/vnd.djvu', + 'dll' => 'application/octet-stream', + 'dmg' => 'application/x-apple-diskimage', + 'dmn' => 'application/octet-stream', + 'dmp' => 'application/vnd.tcpdump.pcap', + 'dms' => 'application/octet-stream', + 'dna' => 'application/vnd.dna', + 'doc' => 'application/msword', + 'docm' => 'application/vnd.ms-word.template.macroEnabled.12', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dot' => 'application/msword', + 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'dp' => 'application/vnd.osgi.dp', + 'dpg' => 'application/vnd.dpgraph', + 'dra' => 'audio/vnd.dra', + 'drle' => 'image/dicom-rle', + 'dsc' => 'text/prs.lines.tag', + 'dssc' => 'application/dssc+der', + 'dtb' => 'application/x-dtbook+xml', + 'dtd' => 'application/xml-dtd', + 'dts' => 'audio/vnd.dts', + 'dtshd' => 'audio/vnd.dts.hd', + 'dump' => 'application/octet-stream', + 'dvb' => 'video/vnd.dvb.file', + 'dvi' => 'application/x-dvi', + 'dwd' => 'application/atsc-dwd+xml', + 'dwf' => 'model/vnd.dwf', + 'dwg' => 'image/vnd.dwg', + 'dxf' => 'image/vnd.dxf', + 'dxp' => 'application/vnd.spotfire.dxp', + 'dxr' => 'application/x-director', + 'ear' => 'application/java-archive', + 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', + 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', + 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', + 'ecma' => 'application/ecmascript', + 'edm' => 'application/vnd.novadigm.edm', + 'edx' => 'application/vnd.novadigm.edx', + 'efif' => 'application/vnd.picsel', + 'ei6' => 'application/vnd.pg.osasli', + 'elc' => 'application/octet-stream', + 'emf' => 'image/emf', + 'eml' => 'message/rfc822', + 'emma' => 'application/emma+xml', + 'emotionml' => 'application/emotionml+xml', + 'emz' => 'application/x-msmetafile', + 'eol' => 'audio/vnd.digital-winds', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'es' => 'application/ecmascript', + 'es3' => 'application/vnd.eszigno3+xml', + 'esa' => 'application/vnd.osgi.subsystem', + 'esf' => 'application/vnd.epson.esf', + 'et3' => 'application/vnd.eszigno3+xml', + 'etx' => 'text/x-setext', + 'eva' => 'application/x-eva', + 'evy' => 'application/x-envoy', + 'exe' => 'application/octet-stream', + 'exi' => 'application/exi', + 'exp' => 'application/express', + 'exr' => 'image/aces', + 'ext' => 'application/vnd.novadigm.ext', + 'ez' => 'application/andrew-inset', + 'ez2' => 'application/vnd.ezpix-album', + 'ez3' => 'application/vnd.ezpix-package', + 'f' => 'text/x-fortran', + 'f4v' => 'video/mp4', + 'f77' => 'text/x-fortran', + 'f90' => 'text/x-fortran', + 'fbs' => 'image/vnd.fastbidsheet', + 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', + 'fcs' => 'application/vnd.isac.fcs', + 'fdf' => 'application/vnd.fdf', + 'fdt' => 'application/fdt+xml', + 'fe_launch' => 'application/vnd.denovo.fcselayout-link', + 'fg5' => 'application/vnd.fujitsu.oasysgp', + 'fgd' => 'application/x-director', + 'fh' => 'image/x-freehand', + 'fh4' => 'image/x-freehand', + 'fh5' => 'image/x-freehand', + 'fh7' => 'image/x-freehand', + 'fhc' => 'image/x-freehand', + 'fig' => 'application/x-xfig', + 'fits' => 'image/fits', + 'flac' => 'audio/x-flac', + 'fli' => 'video/x-fli', + 'flo' => 'application/vnd.micrografx.flo', + 'flv' => 'video/x-flv', + 'flw' => 'application/vnd.kde.kivio', + 'flx' => 'text/vnd.fmi.flexstor', + 'fly' => 'text/vnd.fly', + 'fm' => 'application/vnd.framemaker', + 'fnc' => 'application/vnd.frogans.fnc', + 'fo' => 'application/vnd.software602.filler.form+xml', + 'for' => 'text/x-fortran', + 'fpx' => 'image/vnd.fpx', + 'frame' => 'application/vnd.framemaker', + 'fsc' => 'application/vnd.fsc.weblaunch', + 'fst' => 'image/vnd.fst', + 'ftc' => 'application/vnd.fluxtime.clip', + 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', + 'fvt' => 'video/vnd.fvt', + 'fxp' => 'application/vnd.adobe.fxp', + 'fxpl' => 'application/vnd.adobe.fxp', + 'fzs' => 'application/vnd.fuzzysheet', + 'g2w' => 'application/vnd.geoplan', + 'g3' => 'image/g3fax', + 'g3w' => 'application/vnd.geospace', + 'gac' => 'application/vnd.groove-account', + 'gam' => 'application/x-tads', + 'gbr' => 'application/rpki-ghostbusters', + 'gca' => 'application/x-gca-compressed', + 'gdl' => 'model/vnd.gdl', + 'gdoc' => 'application/vnd.google-apps.document', + 'ged' => 'text/vnd.familysearch.gedcom', + 'geo' => 'application/vnd.dynageo', + 'geojson' => 'application/geo+json', + 'gex' => 'application/vnd.geometry-explorer', + 'ggb' => 'application/vnd.geogebra.file', + 'ggt' => 'application/vnd.geogebra.tool', + 'ghf' => 'application/vnd.groove-help', + 'gif' => 'image/gif', + 'gim' => 'application/vnd.groove-identity-message', + 'glb' => 'model/gltf-binary', + 'gltf' => 'model/gltf+json', + 'gml' => 'application/gml+xml', + 'gmx' => 'application/vnd.gmx', + 'gnumeric' => 'application/x-gnumeric', + 'gpg' => 'application/gpg-keys', + 'gph' => 'application/vnd.flographit', + 'gpx' => 'application/gpx+xml', + 'gqf' => 'application/vnd.grafeq', + 'gqs' => 'application/vnd.grafeq', + 'gram' => 'application/srgs', + 'gramps' => 'application/x-gramps-xml', + 'gre' => 'application/vnd.geometry-explorer', + 'grv' => 'application/vnd.groove-injector', + 'grxml' => 'application/srgs+xml', + 'gsf' => 'application/x-font-ghostscript', + 'gsheet' => 'application/vnd.google-apps.spreadsheet', + 'gslides' => 'application/vnd.google-apps.presentation', + 'gtar' => 'application/x-gtar', + 'gtm' => 'application/vnd.groove-tool-message', + 'gtw' => 'model/vnd.gtw', + 'gv' => 'text/vnd.graphviz', + 'gxf' => 'application/gxf', + 'gxt' => 'application/vnd.geonext', + 'gz' => 'application/gzip', + 'gzip' => 'application/gzip', + 'h' => 'text/x-c', + 'h261' => 'video/h261', + 'h263' => 'video/h263', + 'h264' => 'video/h264', + 'hal' => 'application/vnd.hal+xml', + 'hbci' => 'application/vnd.hbci', + 'hbs' => 'text/x-handlebars-template', + 'hdd' => 'application/x-virtualbox-hdd', + 'hdf' => 'application/x-hdf', + 'heic' => 'image/heic', + 'heics' => 'image/heic-sequence', + 'heif' => 'image/heif', + 'heifs' => 'image/heif-sequence', + 'hej2' => 'image/hej2k', + 'held' => 'application/atsc-held+xml', + 'hh' => 'text/x-c', + 'hjson' => 'application/hjson', + 'hlp' => 'application/winhlp', + 'hpgl' => 'application/vnd.hp-hpgl', + 'hpid' => 'application/vnd.hp-hpid', + 'hps' => 'application/vnd.hp-hps', + 'hqx' => 'application/mac-binhex40', + 'hsj2' => 'image/hsj2', + 'htc' => 'text/x-component', + 'htke' => 'application/vnd.kenameaapp', + 'htm' => 'text/html', + 'html' => 'text/html', + 'hvd' => 'application/vnd.yamaha.hv-dic', + 'hvp' => 'application/vnd.yamaha.hv-voice', + 'hvs' => 'application/vnd.yamaha.hv-script', + 'i2g' => 'application/vnd.intergeo', + 'icc' => 'application/vnd.iccprofile', + 'ice' => 'x-conference/x-cooltalk', + 'icm' => 'application/vnd.iccprofile', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ief' => 'image/ief', + 'ifb' => 'text/calendar', + 'ifm' => 'application/vnd.shana.informed.formdata', + 'iges' => 'model/iges', + 'igl' => 'application/vnd.igloader', + 'igm' => 'application/vnd.insors.igm', + 'igs' => 'model/iges', + 'igx' => 'application/vnd.micrografx.igx', + 'iif' => 'application/vnd.shana.informed.interchange', + 'img' => 'application/octet-stream', + 'imp' => 'application/vnd.accpac.simply.imp', + 'ims' => 'application/vnd.ms-ims', + 'in' => 'text/plain', + 'ini' => 'text/plain', + 'ink' => 'application/inkml+xml', + 'inkml' => 'application/inkml+xml', + 'install' => 'application/x-install-instructions', + 'iota' => 'application/vnd.astraea-software.iota', + 'ipfix' => 'application/ipfix', + 'ipk' => 'application/vnd.shana.informed.package', + 'irm' => 'application/vnd.ibm.rights-management', + 'irp' => 'application/vnd.irepository.package+xml', + 'iso' => 'application/x-iso9660-image', + 'itp' => 'application/vnd.shana.informed.formtemplate', + 'its' => 'application/its+xml', + 'ivp' => 'application/vnd.immervision-ivp', + 'ivu' => 'application/vnd.immervision-ivu', + 'jad' => 'text/vnd.sun.j2me.app-descriptor', + 'jade' => 'text/jade', + 'jam' => 'application/vnd.jam', + 'jar' => 'application/java-archive', + 'jardiff' => 'application/x-java-archive-diff', + 'java' => 'text/x-java-source', + 'jhc' => 'image/jphc', + 'jisp' => 'application/vnd.jisp', + 'jls' => 'image/jls', + 'jlt' => 'application/vnd.hp-jlyt', + 'jng' => 'image/x-jng', + 'jnlp' => 'application/x-java-jnlp-file', + 'joda' => 'application/vnd.joost.joda-archive', + 'jp2' => 'image/jp2', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpf' => 'image/jpx', + 'jpg' => 'image/jpeg', + 'jpg2' => 'image/jp2', + 'jpgm' => 'video/jpm', + 'jpgv' => 'video/jpeg', + 'jph' => 'image/jph', + 'jpm' => 'video/jpm', + 'jpx' => 'image/jpx', + 'js' => 'application/javascript', + 'json' => 'application/json', + 'json5' => 'application/json5', + 'jsonld' => 'application/ld+json', + 'jsonml' => 'application/jsonml+json', + 'jsx' => 'text/jsx', + 'jxr' => 'image/jxr', + 'jxra' => 'image/jxra', + 'jxrs' => 'image/jxrs', + 'jxs' => 'image/jxs', + 'jxsc' => 'image/jxsc', + 'jxsi' => 'image/jxsi', + 'jxss' => 'image/jxss', + 'kar' => 'audio/midi', + 'karbon' => 'application/vnd.kde.karbon', + 'kdb' => 'application/octet-stream', + 'kdbx' => 'application/x-keepass2', + 'key' => 'application/x-iwork-keynote-sffkey', + 'kfo' => 'application/vnd.kde.kformula', + 'kia' => 'application/vnd.kidspiration', + 'kml' => 'application/vnd.google-earth.kml+xml', + 'kmz' => 'application/vnd.google-earth.kmz', + 'kne' => 'application/vnd.kinar', + 'knp' => 'application/vnd.kinar', + 'kon' => 'application/vnd.kde.kontour', + 'kpr' => 'application/vnd.kde.kpresenter', + 'kpt' => 'application/vnd.kde.kpresenter', + 'kpxx' => 'application/vnd.ds-keypoint', + 'ksp' => 'application/vnd.kde.kspread', + 'ktr' => 'application/vnd.kahootz', + 'ktx' => 'image/ktx', + 'ktx2' => 'image/ktx2', + 'ktz' => 'application/vnd.kahootz', + 'kwd' => 'application/vnd.kde.kword', + 'kwt' => 'application/vnd.kde.kword', + 'lasxml' => 'application/vnd.las.las+xml', + 'latex' => 'application/x-latex', + 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', + 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', + 'les' => 'application/vnd.hhe.lesson-player', + 'less' => 'text/less', + 'lgr' => 'application/lgr+xml', + 'lha' => 'application/octet-stream', + 'link66' => 'application/vnd.route66.link66+xml', + 'list' => 'text/plain', + 'list3820' => 'application/vnd.ibm.modcap', + 'listafp' => 'application/vnd.ibm.modcap', + 'litcoffee' => 'text/coffeescript', + 'lnk' => 'application/x-ms-shortcut', + 'log' => 'text/plain', + 'lostxml' => 'application/lost+xml', + 'lrf' => 'application/octet-stream', + 'lrm' => 'application/vnd.ms-lrm', + 'ltf' => 'application/vnd.frogans.ltf', + 'lua' => 'text/x-lua', + 'luac' => 'application/x-lua-bytecode', + 'lvp' => 'audio/vnd.lucent.voice', + 'lwp' => 'application/vnd.lotus-wordpro', + 'lzh' => 'application/octet-stream', + 'm1v' => 'video/mpeg', + 'm2a' => 'audio/mpeg', + 'm2v' => 'video/mpeg', + 'm3a' => 'audio/mpeg', + 'm3u' => 'text/plain', + 'm3u8' => 'application/vnd.apple.mpegurl', + 'm4a' => 'audio/x-m4a', + 'm4p' => 'application/mp4', + 'm4s' => 'video/iso.segment', + 'm4u' => 'application/vnd.mpegurl', + 'm4v' => 'video/x-m4v', + 'm13' => 'application/x-msmediaview', + 'm14' => 'application/x-msmediaview', + 'm21' => 'application/mp21', + 'ma' => 'application/mathematica', + 'mads' => 'application/mads+xml', + 'maei' => 'application/mmt-aei+xml', + 'mag' => 'application/vnd.ecowin.chart', + 'maker' => 'application/vnd.framemaker', + 'man' => 'text/troff', + 'manifest' => 'text/cache-manifest', + 'map' => 'application/json', + 'mar' => 'application/octet-stream', + 'markdown' => 'text/markdown', + 'mathml' => 'application/mathml+xml', + 'mb' => 'application/mathematica', + 'mbk' => 'application/vnd.mobius.mbk', + 'mbox' => 'application/mbox', + 'mc1' => 'application/vnd.medcalcdata', + 'mcd' => 'application/vnd.mcd', + 'mcurl' => 'text/vnd.curl.mcurl', + 'md' => 'text/markdown', + 'mdb' => 'application/x-msaccess', + 'mdi' => 'image/vnd.ms-modi', + 'mdx' => 'text/mdx', + 'me' => 'text/troff', + 'mesh' => 'model/mesh', + 'meta4' => 'application/metalink4+xml', + 'metalink' => 'application/metalink+xml', + 'mets' => 'application/mets+xml', + 'mfm' => 'application/vnd.mfmp', + 'mft' => 'application/rpki-manifest', + 'mgp' => 'application/vnd.osgeo.mapguide.package', + 'mgz' => 'application/vnd.proteus.magazine', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mie' => 'application/x-mie', + 'mif' => 'application/vnd.mif', + 'mime' => 'message/rfc822', + 'mj2' => 'video/mj2', + 'mjp2' => 'video/mj2', + 'mjs' => 'application/javascript', + 'mk3d' => 'video/x-matroska', + 'mka' => 'audio/x-matroska', + 'mkd' => 'text/x-markdown', + 'mks' => 'video/x-matroska', + 'mkv' => 'video/x-matroska', + 'mlp' => 'application/vnd.dolby.mlp', + 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', + 'mmf' => 'application/vnd.smaf', + 'mml' => 'text/mathml', + 'mmr' => 'image/vnd.fujixerox.edmics-mmr', + 'mng' => 'video/x-mng', + 'mny' => 'application/x-msmoney', + 'mobi' => 'application/x-mobipocket-ebook', + 'mods' => 'application/mods+xml', + 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'audio/mpeg', + 'mp2a' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4s' => 'application/mp4', + 'mp4v' => 'video/mp4', + 'mp21' => 'application/mp21', + 'mpc' => 'application/vnd.mophun.certificate', + 'mpd' => 'application/dash+xml', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpf' => 'application/media-policy-dataset+xml', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'mpga' => 'audio/mpeg', + 'mpkg' => 'application/vnd.apple.installer+xml', + 'mpm' => 'application/vnd.blueice.multipass', + 'mpn' => 'application/vnd.mophun.application', + 'mpp' => 'application/vnd.ms-project', + 'mpt' => 'application/vnd.ms-project', + 'mpy' => 'application/vnd.ibm.minipay', + 'mqy' => 'application/vnd.mobius.mqy', + 'mrc' => 'application/marc', + 'mrcx' => 'application/marcxml+xml', + 'ms' => 'text/troff', + 'mscml' => 'application/mediaservercontrol+xml', + 'mseed' => 'application/vnd.fdsn.mseed', + 'mseq' => 'application/vnd.mseq', + 'msf' => 'application/vnd.epson.msf', + 'msg' => 'application/vnd.ms-outlook', + 'msh' => 'model/mesh', + 'msi' => 'application/x-msdownload', + 'msl' => 'application/vnd.mobius.msl', + 'msm' => 'application/octet-stream', + 'msp' => 'application/octet-stream', + 'msty' => 'application/vnd.muvee.style', + 'mtl' => 'model/mtl', + 'mts' => 'model/vnd.mts', + 'mus' => 'application/vnd.musician', + 'musd' => 'application/mmt-usd+xml', + 'musicxml' => 'application/vnd.recordare.musicxml+xml', + 'mvb' => 'application/x-msmediaview', + 'mvt' => 'application/vnd.mapbox-vector-tile', + 'mwf' => 'application/vnd.mfer', + 'mxf' => 'application/mxf', + 'mxl' => 'application/vnd.recordare.musicxml', + 'mxmf' => 'audio/mobile-xmf', + 'mxml' => 'application/xv+xml', + 'mxs' => 'application/vnd.triscape.mxs', + 'mxu' => 'video/vnd.mpegurl', + 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', + 'n3' => 'text/n3', + 'nb' => 'application/mathematica', + 'nbp' => 'application/vnd.wolfram.player', + 'nc' => 'application/x-netcdf', + 'ncx' => 'application/x-dtbncx+xml', + 'nfo' => 'text/x-nfo', + 'ngdat' => 'application/vnd.nokia.n-gage.data', + 'nitf' => 'application/vnd.nitf', + 'nlu' => 'application/vnd.neurolanguage.nlu', + 'nml' => 'application/vnd.enliven', + 'nnd' => 'application/vnd.noblenet-directory', + 'nns' => 'application/vnd.noblenet-sealer', + 'nnw' => 'application/vnd.noblenet-web', + 'npx' => 'image/vnd.net-fpx', + 'nq' => 'application/n-quads', + 'nsc' => 'application/x-conference', + 'nsf' => 'application/vnd.lotus-notes', + 'nt' => 'application/n-triples', + 'ntf' => 'application/vnd.nitf', + 'numbers' => 'application/x-iwork-numbers-sffnumbers', + 'nzb' => 'application/x-nzb', + 'oa2' => 'application/vnd.fujitsu.oasys2', + 'oa3' => 'application/vnd.fujitsu.oasys3', + 'oas' => 'application/vnd.fujitsu.oasys', + 'obd' => 'application/x-msbinder', + 'obgx' => 'application/vnd.openblox.game+xml', + 'obj' => 'model/obj', + 'oda' => 'application/oda', + 'odb' => 'application/vnd.oasis.opendocument.database', + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'odf' => 'application/vnd.oasis.opendocument.formula', + 'odft' => 'application/vnd.oasis.opendocument.formula-template', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'odi' => 'application/vnd.oasis.opendocument.image', + 'odm' => 'application/vnd.oasis.opendocument.text-master', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'odt' => 'application/vnd.oasis.opendocument.text', + 'oga' => 'audio/ogg', + 'ogex' => 'model/vnd.opengex', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'omdoc' => 'application/omdoc+xml', + 'onepkg' => 'application/onenote', + 'onetmp' => 'application/onenote', + 'onetoc' => 'application/onenote', + 'onetoc2' => 'application/onenote', + 'opf' => 'application/oebps-package+xml', + 'opml' => 'text/x-opml', + 'oprc' => 'application/vnd.palm', + 'opus' => 'audio/ogg', + 'org' => 'text/x-org', + 'osf' => 'application/vnd.yamaha.openscoreformat', + 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', + 'osm' => 'application/vnd.openstreetmap.data+xml', + 'otc' => 'application/vnd.oasis.opendocument.chart-template', + 'otf' => 'font/otf', + 'otg' => 'application/vnd.oasis.opendocument.graphics-template', + 'oth' => 'application/vnd.oasis.opendocument.text-web', + 'oti' => 'application/vnd.oasis.opendocument.image-template', + 'otp' => 'application/vnd.oasis.opendocument.presentation-template', + 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', + 'ott' => 'application/vnd.oasis.opendocument.text-template', + 'ova' => 'application/x-virtualbox-ova', + 'ovf' => 'application/x-virtualbox-ovf', + 'owl' => 'application/rdf+xml', + 'oxps' => 'application/oxps', + 'oxt' => 'application/vnd.openofficeorg.extension', + 'p' => 'text/x-pascal', + 'p7a' => 'application/x-pkcs7-signature', + 'p7b' => 'application/x-pkcs7-certificates', + 'p7c' => 'application/pkcs7-mime', + 'p7m' => 'application/pkcs7-mime', + 'p7r' => 'application/x-pkcs7-certreqresp', + 'p7s' => 'application/pkcs7-signature', + 'p8' => 'application/pkcs8', + 'p10' => 'application/x-pkcs10', + 'p12' => 'application/x-pkcs12', + 'pac' => 'application/x-ns-proxy-autoconfig', + 'pages' => 'application/x-iwork-pages-sffpages', + 'pas' => 'text/x-pascal', + 'paw' => 'application/vnd.pawaafile', + 'pbd' => 'application/vnd.powerbuilder6', + 'pbm' => 'image/x-portable-bitmap', + 'pcap' => 'application/vnd.tcpdump.pcap', + 'pcf' => 'application/x-font-pcf', + 'pcl' => 'application/vnd.hp-pcl', + 'pclxl' => 'application/vnd.hp-pclxl', + 'pct' => 'image/x-pict', + 'pcurl' => 'application/vnd.curl.pcurl', + 'pcx' => 'image/x-pcx', + 'pdb' => 'application/x-pilot', + 'pde' => 'text/x-processing', + 'pdf' => 'application/pdf', + 'pem' => 'application/x-x509-user-cert', + 'pfa' => 'application/x-font-type1', + 'pfb' => 'application/x-font-type1', + 'pfm' => 'application/x-font-type1', + 'pfr' => 'application/font-tdpfr', + 'pfx' => 'application/x-pkcs12', + 'pgm' => 'image/x-portable-graymap', + 'pgn' => 'application/x-chess-pgn', + 'pgp' => 'application/pgp', + 'phar' => 'application/octet-stream', + 'php' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'phtml' => 'application/x-httpd-php', + 'pic' => 'image/x-pict', + 'pkg' => 'application/octet-stream', + 'pki' => 'application/pkixcmp', + 'pkipath' => 'application/pkix-pkipath', + 'pkpass' => 'application/vnd.apple.pkpass', + 'pl' => 'application/x-perl', + 'plb' => 'application/vnd.3gpp.pic-bw-large', + 'plc' => 'application/vnd.mobius.plc', + 'plf' => 'application/vnd.pocketlearn', + 'pls' => 'application/pls+xml', + 'pm' => 'application/x-perl', + 'pml' => 'application/vnd.ctc-posml', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'portpkg' => 'application/vnd.macports.portpkg', + 'pot' => 'application/vnd.ms-powerpoint', + 'potm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppa' => 'application/vnd.ms-powerpoint', + 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12', + 'ppd' => 'application/vnd.cups-ppd', + 'ppm' => 'image/x-portable-pixmap', + 'pps' => 'application/vnd.ms-powerpoint', + 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'ppt' => 'application/powerpoint', + 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'pqa' => 'application/vnd.palm', + 'prc' => 'model/prc', + 'pre' => 'application/vnd.lotus-freelance', + 'prf' => 'application/pics-rules', + 'provx' => 'application/provenance+xml', + 'ps' => 'application/postscript', + 'psb' => 'application/vnd.3gpp.pic-bw-small', + 'psd' => 'application/x-photoshop', + 'psf' => 'application/x-font-linux-psf', + 'pskcxml' => 'application/pskc+xml', + 'pti' => 'image/prs.pti', + 'ptid' => 'application/vnd.pvi.ptid1', + 'pub' => 'application/x-mspublisher', + 'pvb' => 'application/vnd.3gpp.pic-bw-var', + 'pwn' => 'application/vnd.3m.post-it-notes', + 'pya' => 'audio/vnd.ms-playready.media.pya', + 'pyv' => 'video/vnd.ms-playready.media.pyv', + 'qam' => 'application/vnd.epson.quickanime', + 'qbo' => 'application/vnd.intu.qbo', + 'qfx' => 'application/vnd.intu.qfx', + 'qps' => 'application/vnd.publishare-delta-tree', + 'qt' => 'video/quicktime', + 'qwd' => 'application/vnd.quark.quarkxpress', + 'qwt' => 'application/vnd.quark.quarkxpress', + 'qxb' => 'application/vnd.quark.quarkxpress', + 'qxd' => 'application/vnd.quark.quarkxpress', + 'qxl' => 'application/vnd.quark.quarkxpress', + 'qxt' => 'application/vnd.quark.quarkxpress', + 'ra' => 'audio/x-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'raml' => 'application/raml+yaml', + 'rapd' => 'application/route-apd+xml', + 'rar' => 'application/x-rar', + 'ras' => 'image/x-cmu-raster', + 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', + 'rdf' => 'application/rdf+xml', + 'rdz' => 'application/vnd.data-vision.rdz', + 'relo' => 'application/p2p-overlay+xml', + 'rep' => 'application/vnd.businessobjects', + 'res' => 'application/x-dtbresource+xml', + 'rgb' => 'image/x-rgb', + 'rif' => 'application/reginfo+xml', + 'rip' => 'audio/vnd.rip', + 'ris' => 'application/x-research-info-systems', + 'rl' => 'application/resource-lists+xml', + 'rlc' => 'image/vnd.fujixerox.edmics-rlc', + 'rld' => 'application/resource-lists-diff+xml', + 'rm' => 'audio/x-pn-realaudio', + 'rmi' => 'audio/midi', + 'rmp' => 'audio/x-pn-realaudio-plugin', + 'rms' => 'application/vnd.jcp.javame.midlet-rms', + 'rmvb' => 'application/vnd.rn-realmedia-vbr', + 'rnc' => 'application/relax-ng-compact-syntax', + 'rng' => 'application/xml', + 'roa' => 'application/rpki-roa', + 'roff' => 'text/troff', + 'rp9' => 'application/vnd.cloanto.rp9', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'rpss' => 'application/vnd.nokia.radio-presets', + 'rpst' => 'application/vnd.nokia.radio-preset', + 'rq' => 'application/sparql-query', + 'rs' => 'application/rls-services+xml', + 'rsa' => 'application/x-pkcs7', + 'rsat' => 'application/atsc-rsat+xml', + 'rsd' => 'application/rsd+xml', + 'rsheet' => 'application/urc-ressheet+xml', + 'rss' => 'application/rss+xml', + 'rtf' => 'text/rtf', + 'rtx' => 'text/richtext', + 'run' => 'application/x-makeself', + 'rusd' => 'application/route-usd+xml', + 'rv' => 'video/vnd.rn-realvideo', + 's' => 'text/x-asm', + 's3m' => 'audio/s3m', + 'saf' => 'application/vnd.yamaha.smaf-audio', + 'sass' => 'text/x-sass', + 'sbml' => 'application/sbml+xml', + 'sc' => 'application/vnd.ibm.secure-container', + 'scd' => 'application/x-msschedule', + 'scm' => 'application/vnd.lotus-screencam', + 'scq' => 'application/scvp-cv-request', + 'scs' => 'application/scvp-cv-response', + 'scss' => 'text/x-scss', + 'scurl' => 'text/vnd.curl.scurl', + 'sda' => 'application/vnd.stardivision.draw', + 'sdc' => 'application/vnd.stardivision.calc', + 'sdd' => 'application/vnd.stardivision.impress', + 'sdkd' => 'application/vnd.solent.sdkm+xml', + 'sdkm' => 'application/vnd.solent.sdkm+xml', + 'sdp' => 'application/sdp', + 'sdw' => 'application/vnd.stardivision.writer', + 'sea' => 'application/octet-stream', + 'see' => 'application/vnd.seemail', + 'seed' => 'application/vnd.fdsn.seed', + 'sema' => 'application/vnd.sema', + 'semd' => 'application/vnd.semd', + 'semf' => 'application/vnd.semf', + 'senmlx' => 'application/senml+xml', + 'sensmlx' => 'application/sensml+xml', + 'ser' => 'application/java-serialized-object', + 'setpay' => 'application/set-payment-initiation', + 'setreg' => 'application/set-registration-initiation', + 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', + 'sfs' => 'application/vnd.spotfire.sfs', + 'sfv' => 'text/x-sfv', + 'sgi' => 'image/sgi', + 'sgl' => 'application/vnd.stardivision.writer-global', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', + 'shex' => 'text/shex', + 'shf' => 'application/shf+xml', + 'shtml' => 'text/html', + 'sid' => 'image/x-mrsid-image', + 'sieve' => 'application/sieve', + 'sig' => 'application/pgp-signature', + 'sil' => 'audio/silk', + 'silo' => 'model/mesh', + 'sis' => 'application/vnd.symbian.install', + 'sisx' => 'application/vnd.symbian.install', + 'sit' => 'application/x-stuffit', + 'sitx' => 'application/x-stuffitx', + 'siv' => 'application/sieve', + 'skd' => 'application/vnd.koan', + 'skm' => 'application/vnd.koan', + 'skp' => 'application/vnd.koan', + 'skt' => 'application/vnd.koan', + 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'slim' => 'text/slim', + 'slm' => 'text/slim', + 'sls' => 'application/route-s-tsid+xml', + 'slt' => 'application/vnd.epson.salt', + 'sm' => 'application/vnd.stepmania.stepchart', + 'smf' => 'application/vnd.stardivision.math', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'smv' => 'video/x-smv', + 'smzip' => 'application/vnd.stepmania.package', + 'snd' => 'audio/basic', + 'snf' => 'application/x-font-snf', + 'so' => 'application/octet-stream', + 'spc' => 'application/x-pkcs7-certificates', + 'spdx' => 'text/spdx', + 'spf' => 'application/vnd.yamaha.smaf-phrase', + 'spl' => 'application/x-futuresplash', + 'spot' => 'text/vnd.in3d.spot', + 'spp' => 'application/scvp-vp-response', + 'spq' => 'application/scvp-vp-request', + 'spx' => 'audio/ogg', + 'sql' => 'application/x-sql', + 'src' => 'application/x-wais-source', + 'srt' => 'application/x-subrip', + 'sru' => 'application/sru+xml', + 'srx' => 'application/sparql-results+xml', + 'ssdl' => 'application/ssdl+xml', + 'sse' => 'application/vnd.kodak-descriptor', + 'ssf' => 'application/vnd.epson.ssf', + 'ssml' => 'application/ssml+xml', + 'sst' => 'application/octet-stream', + 'st' => 'application/vnd.sailingtracker.track', + 'stc' => 'application/vnd.sun.xml.calc.template', + 'std' => 'application/vnd.sun.xml.draw.template', + 'stf' => 'application/vnd.wt.stf', + 'sti' => 'application/vnd.sun.xml.impress.template', + 'stk' => 'application/hyperstudio', + 'stl' => 'model/stl', + 'stpx' => 'model/step+xml', + 'stpxz' => 'model/step-xml+zip', + 'stpz' => 'model/step+zip', + 'str' => 'application/vnd.pg.format', + 'stw' => 'application/vnd.sun.xml.writer.template', + 'styl' => 'text/stylus', + 'stylus' => 'text/stylus', + 'sub' => 'text/vnd.dvb.subtitle', + 'sus' => 'application/vnd.sus-calendar', + 'susp' => 'application/vnd.sus-calendar', + 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', + 'svc' => 'application/vnd.dvb.service', + 'svd' => 'application/vnd.svd', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + 'swa' => 'application/x-director', + 'swf' => 'application/x-shockwave-flash', + 'swi' => 'application/vnd.aristanetworks.swi', + 'swidtag' => 'application/swid+xml', + 'sxc' => 'application/vnd.sun.xml.calc', + 'sxd' => 'application/vnd.sun.xml.draw', + 'sxg' => 'application/vnd.sun.xml.writer.global', + 'sxi' => 'application/vnd.sun.xml.impress', + 'sxm' => 'application/vnd.sun.xml.math', + 'sxw' => 'application/vnd.sun.xml.writer', + 't' => 'text/troff', + 't3' => 'application/x-t3vm-image', + 't38' => 'image/t38', + 'taglet' => 'application/vnd.mynfc', + 'tao' => 'application/vnd.tao.intent-module-archive', + 'tap' => 'image/vnd.tencent.tap', + 'tar' => 'application/x-tar', + 'tcap' => 'application/vnd.3gpp2.tcap', + 'tcl' => 'application/x-tcl', + 'td' => 'application/urc-targetdesc+xml', + 'teacher' => 'application/vnd.smart.teacher', + 'tei' => 'application/tei+xml', + 'teicorpus' => 'application/tei+xml', + 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', + 'texinfo' => 'application/x-texinfo', + 'text' => 'text/plain', + 'tfi' => 'application/thraud+xml', + 'tfm' => 'application/x-tex-tfm', + 'tfx' => 'image/tiff-fx', + 'tga' => 'image/x-tga', + 'tgz' => 'application/x-tar', + 'thmx' => 'application/vnd.ms-officetheme', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'tk' => 'application/x-tcl', + 'tmo' => 'application/vnd.tmobile-livetv', + 'toml' => 'application/toml', + 'torrent' => 'application/x-bittorrent', + 'tpl' => 'application/vnd.groove-tool-template', + 'tpt' => 'application/vnd.trid.tpt', + 'tr' => 'text/troff', + 'tra' => 'application/vnd.trueapp', + 'trig' => 'application/trig', + 'trm' => 'application/x-msterminal', + 'ts' => 'video/mp2t', + 'tsd' => 'application/timestamped-data', + 'tsv' => 'text/tab-separated-values', + 'ttc' => 'font/collection', + 'ttf' => 'font/ttf', + 'ttl' => 'text/turtle', + 'ttml' => 'application/ttml+xml', + 'twd' => 'application/vnd.simtech-mindmapper', + 'twds' => 'application/vnd.simtech-mindmapper', + 'txd' => 'application/vnd.genomatix.tuxedo', + 'txf' => 'application/vnd.mobius.txf', + 'txt' => 'text/plain', + 'u3d' => 'model/u3d', + 'u8dsn' => 'message/global-delivery-status', + 'u8hdr' => 'message/global-headers', + 'u8mdn' => 'message/global-disposition-notification', + 'u8msg' => 'message/global', + 'u32' => 'application/x-authorware-bin', + 'ubj' => 'application/ubjson', + 'udeb' => 'application/x-debian-package', + 'ufd' => 'application/vnd.ufdl', + 'ufdl' => 'application/vnd.ufdl', + 'ulx' => 'application/x-glulx', + 'umj' => 'application/vnd.umajin', + 'unityweb' => 'application/vnd.unity', + 'uoml' => 'application/vnd.uoml+xml', + 'uri' => 'text/uri-list', + 'uris' => 'text/uri-list', + 'urls' => 'text/uri-list', + 'usdz' => 'model/vnd.usdz+zip', + 'ustar' => 'application/x-ustar', + 'utz' => 'application/vnd.uiq.theme', + 'uu' => 'text/x-uuencode', + 'uva' => 'audio/vnd.dece.audio', + 'uvd' => 'application/vnd.dece.data', + 'uvf' => 'application/vnd.dece.data', + 'uvg' => 'image/vnd.dece.graphic', + 'uvh' => 'video/vnd.dece.hd', + 'uvi' => 'image/vnd.dece.graphic', + 'uvm' => 'video/vnd.dece.mobile', + 'uvp' => 'video/vnd.dece.pd', + 'uvs' => 'video/vnd.dece.sd', + 'uvt' => 'application/vnd.dece.ttml+xml', + 'uvu' => 'video/vnd.uvvu.mp4', + 'uvv' => 'video/vnd.dece.video', + 'uvva' => 'audio/vnd.dece.audio', + 'uvvd' => 'application/vnd.dece.data', + 'uvvf' => 'application/vnd.dece.data', + 'uvvg' => 'image/vnd.dece.graphic', + 'uvvh' => 'video/vnd.dece.hd', + 'uvvi' => 'image/vnd.dece.graphic', + 'uvvm' => 'video/vnd.dece.mobile', + 'uvvp' => 'video/vnd.dece.pd', + 'uvvs' => 'video/vnd.dece.sd', + 'uvvt' => 'application/vnd.dece.ttml+xml', + 'uvvu' => 'video/vnd.uvvu.mp4', + 'uvvv' => 'video/vnd.dece.video', + 'uvvx' => 'application/vnd.dece.unspecified', + 'uvvz' => 'application/vnd.dece.zip', + 'uvx' => 'application/vnd.dece.unspecified', + 'uvz' => 'application/vnd.dece.zip', + 'vbox' => 'application/x-virtualbox-vbox', + 'vbox-extpack' => 'application/x-virtualbox-vbox-extpack', + 'vcard' => 'text/vcard', + 'vcd' => 'application/x-cdlink', + 'vcf' => 'text/x-vcard', + 'vcg' => 'application/vnd.groove-vcard', + 'vcs' => 'text/x-vcalendar', + 'vcx' => 'application/vnd.vcx', + 'vdi' => 'application/x-virtualbox-vdi', + 'vds' => 'model/vnd.sap.vds', + 'vhd' => 'application/x-virtualbox-vhd', + 'vis' => 'application/vnd.visionary', + 'viv' => 'video/vnd.vivo', + 'vlc' => 'application/videolan', + 'vmdk' => 'application/x-virtualbox-vmdk', + 'vob' => 'video/x-ms-vob', + 'vor' => 'application/vnd.stardivision.writer', + 'vox' => 'application/x-authorware-bin', + 'vrml' => 'model/vrml', + 'vsd' => 'application/vnd.visio', + 'vsf' => 'application/vnd.vsf', + 'vss' => 'application/vnd.visio', + 'vst' => 'application/vnd.visio', + 'vsw' => 'application/vnd.visio', + 'vtf' => 'image/vnd.valve.source.texture', + 'vtt' => 'text/vtt', + 'vtu' => 'model/vnd.vtu', + 'vxml' => 'application/voicexml+xml', + 'w3d' => 'application/x-director', + 'wad' => 'application/x-doom', + 'wadl' => 'application/vnd.sun.wadl+xml', + 'war' => 'application/java-archive', + 'wasm' => 'application/wasm', + 'wav' => 'audio/x-wav', + 'wax' => 'audio/x-ms-wax', + 'wbmp' => 'image/vnd.wap.wbmp', + 'wbs' => 'application/vnd.criticaltools.wbs+xml', + 'wbxml' => 'application/wbxml', + 'wcm' => 'application/vnd.ms-works', + 'wdb' => 'application/vnd.ms-works', + 'wdp' => 'image/vnd.ms-photo', + 'weba' => 'audio/webm', + 'webapp' => 'application/x-web-app-manifest+json', + 'webm' => 'video/webm', + 'webmanifest' => 'application/manifest+json', + 'webp' => 'image/webp', + 'wg' => 'application/vnd.pmi.widget', + 'wgt' => 'application/widget', + 'wif' => 'application/watcherinfo+xml', + 'wks' => 'application/vnd.ms-works', + 'wm' => 'video/x-ms-wm', + 'wma' => 'audio/x-ms-wma', + 'wmd' => 'application/x-ms-wmd', + 'wmf' => 'image/wmf', + 'wml' => 'text/vnd.wap.wml', + 'wmlc' => 'application/wmlc', + 'wmls' => 'text/vnd.wap.wmlscript', + 'wmlsc' => 'application/vnd.wap.wmlscriptc', + 'wmv' => 'video/x-ms-wmv', + 'wmx' => 'video/x-ms-wmx', + 'wmz' => 'application/x-msmetafile', + 'woff' => 'font/woff', + 'woff2' => 'font/woff2', + 'word' => 'application/msword', + 'wpd' => 'application/vnd.wordperfect', + 'wpl' => 'application/vnd.ms-wpl', + 'wps' => 'application/vnd.ms-works', + 'wqd' => 'application/vnd.wqd', + 'wri' => 'application/x-mswrite', + 'wrl' => 'model/vrml', + 'wsc' => 'message/vnd.wfa.wsc', + 'wsdl' => 'application/wsdl+xml', + 'wspolicy' => 'application/wspolicy+xml', + 'wtb' => 'application/vnd.webturbo', + 'wvx' => 'video/x-ms-wvx', + 'x3d' => 'model/x3d+xml', + 'x3db' => 'model/x3d+fastinfoset', + 'x3dbz' => 'model/x3d+binary', + 'x3dv' => 'model/x3d-vrml', + 'x3dvz' => 'model/x3d+vrml', + 'x3dz' => 'model/x3d+xml', + 'x32' => 'application/x-authorware-bin', + 'x_b' => 'model/vnd.parasolid.transmit.binary', + 'x_t' => 'model/vnd.parasolid.transmit.text', + 'xaml' => 'application/xaml+xml', + 'xap' => 'application/x-silverlight-app', + 'xar' => 'application/vnd.xara', + 'xav' => 'application/xcap-att+xml', + 'xbap' => 'application/x-ms-xbap', + 'xbd' => 'application/vnd.fujixerox.docuworks.binder', + 'xbm' => 'image/x-xbitmap', + 'xca' => 'application/xcap-caps+xml', + 'xcs' => 'application/calendar+xml', + 'xdf' => 'application/xcap-diff+xml', + 'xdm' => 'application/vnd.syncml.dm+xml', + 'xdp' => 'application/vnd.adobe.xdp+xml', + 'xdssc' => 'application/dssc+xml', + 'xdw' => 'application/vnd.fujixerox.docuworks', + 'xel' => 'application/xcap-el+xml', + 'xenc' => 'application/xenc+xml', + 'xer' => 'application/patch-ops-error+xml', + 'xfdf' => 'application/vnd.adobe.xfdf', + 'xfdl' => 'application/vnd.xfdl', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'xhvml' => 'application/xv+xml', + 'xif' => 'image/vnd.xiff', + 'xl' => 'application/excel', + 'xla' => 'application/vnd.ms-excel', + 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', + 'xlc' => 'application/vnd.ms-excel', + 'xlf' => 'application/xliff+xml', + 'xlm' => 'application/vnd.ms-excel', + 'xls' => 'application/vnd.ms-excel', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', + 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xlt' => 'application/vnd.ms-excel', + 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'xlw' => 'application/vnd.ms-excel', + 'xm' => 'audio/xm', + 'xml' => 'application/xml', + 'xns' => 'application/xcap-ns+xml', + 'xo' => 'application/vnd.olpc-sugar', + 'xop' => 'application/xop+xml', + 'xpi' => 'application/x-xpinstall', + 'xpl' => 'application/xproc+xml', + 'xpm' => 'image/x-xpixmap', + 'xpr' => 'application/vnd.is-xpr', + 'xps' => 'application/vnd.ms-xpsdocument', + 'xpw' => 'application/vnd.intercon.formnet', + 'xpx' => 'application/vnd.intercon.formnet', + 'xsd' => 'application/xml', + 'xsl' => 'application/xml', + 'xslt' => 'application/xslt+xml', + 'xsm' => 'application/vnd.syncml+xml', + 'xspf' => 'application/xspf+xml', + 'xul' => 'application/vnd.mozilla.xul+xml', + 'xvm' => 'application/xv+xml', + 'xvml' => 'application/xv+xml', + 'xwd' => 'image/x-xwindowdump', + 'xyz' => 'chemical/x-xyz', + 'xz' => 'application/x-xz', + 'yaml' => 'text/yaml', + 'yang' => 'application/yang', + 'yin' => 'application/yin+xml', + 'yml' => 'text/yaml', + 'ymp' => 'text/x-suse-ymp', + 'z' => 'application/x-compress', + 'z1' => 'application/x-zmachine', + 'z2' => 'application/x-zmachine', + 'z3' => 'application/x-zmachine', + 'z4' => 'application/x-zmachine', + 'z5' => 'application/x-zmachine', + 'z6' => 'application/x-zmachine', + 'z7' => 'application/x-zmachine', + 'z8' => 'application/x-zmachine', + 'zaz' => 'application/vnd.zzazz.deck+xml', + 'zip' => 'application/zip', + 'zir' => 'application/vnd.zul', + 'zirz' => 'application/vnd.zul', + 'zmm' => 'application/vnd.handheld-entertainment+xml', + 'zsh' => 'text/x-scriptzsh', + ]; + + /** + * Determines the mimetype of a file by looking at its extension. + * + * @link https://raw.githubusercontent.com/jshttp/mime-db/master/db.json + */ + public static function fromFilename(string $filename): ?string + { + return self::fromExtension(pathinfo($filename, PATHINFO_EXTENSION)); + } + + /** + * Maps a file extensions to a mimetype. + * + * @link https://raw.githubusercontent.com/jshttp/mime-db/master/db.json + */ + public static function fromExtension(string $extension): ?string + { + return self::MIME_TYPES[strtolower($extension)] ?? null; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MultipartStream.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MultipartStream.php new file mode 100644 index 0000000..3e12b74 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/MultipartStream.php @@ -0,0 +1,159 @@ +boundary = $boundary ?: bin2hex(random_bytes(20)); + $this->stream = $this->createStream($elements); + } + + public function getBoundary(): string + { + return $this->boundary; + } + + public function isWritable(): bool + { + return false; + } + + /** + * Get the headers needed before transferring the content of a POST file + * + * @param array $headers + */ + private function getHeaders(array $headers): string + { + $str = ''; + foreach ($headers as $key => $value) { + $str .= "{$key}: {$value}\r\n"; + } + + return "--{$this->boundary}\r\n" . trim($str) . "\r\n\r\n"; + } + + /** + * Create the aggregate stream that will be used to upload the POST data + */ + protected function createStream(array $elements = []): StreamInterface + { + $stream = new AppendStream(); + + foreach ($elements as $element) { + if (!is_array($element)) { + throw new \UnexpectedValueException("An array is expected"); + } + $this->addElement($stream, $element); + } + + // Add the trailing boundary with CRLF + $stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n")); + + return $stream; + } + + private function addElement(AppendStream $stream, array $element): void + { + foreach (['contents', 'name'] as $key) { + if (!array_key_exists($key, $element)) { + throw new \InvalidArgumentException("A '{$key}' key is required"); + } + } + + $element['contents'] = Utils::streamFor($element['contents']); + + if (empty($element['filename'])) { + $uri = $element['contents']->getMetadata('uri'); + if ($uri && \is_string($uri) && \substr($uri, 0, 6) !== 'php://' && \substr($uri, 0, 7) !== 'data://') { + $element['filename'] = $uri; + } + } + + [$body, $headers] = $this->createElement( + $element['name'], + $element['contents'], + $element['filename'] ?? null, + $element['headers'] ?? [] + ); + + $stream->addStream(Utils::streamFor($this->getHeaders($headers))); + $stream->addStream($body); + $stream->addStream(Utils::streamFor("\r\n")); + } + + private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers): array + { + // Set a default content-disposition header if one was no provided + $disposition = $this->getHeader($headers, 'content-disposition'); + if (!$disposition) { + $headers['Content-Disposition'] = ($filename === '0' || $filename) + ? sprintf( + 'form-data; name="%s"; filename="%s"', + $name, + basename($filename) + ) + : "form-data; name=\"{$name}\""; + } + + // Set a default content-length header if one was no provided + $length = $this->getHeader($headers, 'content-length'); + if (!$length) { + if ($length = $stream->getSize()) { + $headers['Content-Length'] = (string) $length; + } + } + + // Set a default Content-Type if one was not supplied + $type = $this->getHeader($headers, 'content-type'); + if (!$type && ($filename === '0' || $filename)) { + if ($type = MimeType::fromFilename($filename)) { + $headers['Content-Type'] = $type; + } + } + + return [$stream, $headers]; + } + + private function getHeader(array $headers, string $key) + { + $lowercaseHeader = strtolower($key); + foreach ($headers as $k => $v) { + if (strtolower($k) === $lowercaseHeader) { + return $v; + } + } + + return null; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/NoSeekStream.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/NoSeekStream.php new file mode 100644 index 0000000..161a224 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/NoSeekStream.php @@ -0,0 +1,28 @@ +source = $source; + $this->size = $options['size'] ?? null; + $this->metadata = $options['metadata'] ?? []; + $this->buffer = new BufferStream(); + } + + public function __toString(): string + { + try { + return Utils::copyToString($this); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function close(): void + { + $this->detach(); + } + + public function detach() + { + $this->tellPos = 0; + $this->source = null; + + return null; + } + + public function getSize(): ?int + { + return $this->size; + } + + public function tell(): int + { + return $this->tellPos; + } + + public function eof(): bool + { + return $this->source === null; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a PumpStream'); + } + + public function isWritable(): bool + { + return false; + } + + public function write($string): int + { + throw new \RuntimeException('Cannot write to a PumpStream'); + } + + public function isReadable(): bool + { + return true; + } + + public function read($length): string + { + $data = $this->buffer->read($length); + $readLen = strlen($data); + $this->tellPos += $readLen; + $remaining = $length - $readLen; + + if ($remaining) { + $this->pump($remaining); + $data .= $this->buffer->read($remaining); + $this->tellPos += strlen($data) - $readLen; + } + + return $data; + } + + public function getContents(): string + { + $result = ''; + while (!$this->eof()) { + $result .= $this->read(1000000); + } + + return $result; + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + if (!$key) { + return $this->metadata; + } + + return $this->metadata[$key] ?? null; + } + + private function pump(int $length): void + { + if ($this->source) { + do { + $data = call_user_func($this->source, $length); + if ($data === false || $data === null) { + $this->source = null; + return; + } + $this->buffer->write($data); + $length -= strlen($data); + } while ($length > 0); + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Query.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Query.php new file mode 100644 index 0000000..2faab3a --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Query.php @@ -0,0 +1,113 @@ + '1', 'foo[b]' => '2'])`. + * + * @param string $str Query string to parse + * @param int|bool $urlEncoding How the query string is encoded + */ + public static function parse(string $str, $urlEncoding = true): array + { + $result = []; + + if ($str === '') { + return $result; + } + + if ($urlEncoding === true) { + $decoder = function ($value) { + return rawurldecode(str_replace('+', ' ', (string) $value)); + }; + } elseif ($urlEncoding === PHP_QUERY_RFC3986) { + $decoder = 'rawurldecode'; + } elseif ($urlEncoding === PHP_QUERY_RFC1738) { + $decoder = 'urldecode'; + } else { + $decoder = function ($str) { + return $str; + }; + } + + foreach (explode('&', $str) as $kvp) { + $parts = explode('=', $kvp, 2); + $key = $decoder($parts[0]); + $value = isset($parts[1]) ? $decoder($parts[1]) : null; + if (!array_key_exists($key, $result)) { + $result[$key] = $value; + } else { + if (!is_array($result[$key])) { + $result[$key] = [$result[$key]]; + } + $result[$key][] = $value; + } + } + + return $result; + } + + /** + * Build a query string from an array of key value pairs. + * + * This function can use the return value of `parse()` to build a query + * string. This function does not modify the provided keys when an array is + * encountered (like `http_build_query()` would). + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 + * to encode using RFC3986, or PHP_QUERY_RFC1738 + * to encode using RFC1738. + */ + public static function build(array $params, $encoding = PHP_QUERY_RFC3986): string + { + if (!$params) { + return ''; + } + + if ($encoding === false) { + $encoder = function (string $str): string { + return $str; + }; + } elseif ($encoding === PHP_QUERY_RFC3986) { + $encoder = 'rawurlencode'; + } elseif ($encoding === PHP_QUERY_RFC1738) { + $encoder = 'urlencode'; + } else { + throw new \InvalidArgumentException('Invalid type'); + } + + $qs = ''; + foreach ($params as $k => $v) { + $k = $encoder((string) $k); + if (!is_array($v)) { + $qs .= $k; + $v = is_bool($v) ? (int) $v : $v; + if ($v !== null) { + $qs .= '=' . $encoder((string) $v); + } + $qs .= '&'; + } else { + foreach ($v as $vv) { + $qs .= $k; + $vv = is_bool($vv) ? (int) $vv : $vv; + if ($vv !== null) { + $qs .= '=' . $encoder((string) $vv); + } + $qs .= '&'; + } + } + } + + return $qs ? (string) substr($qs, 0, -1) : ''; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Request.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Request.php new file mode 100644 index 0000000..b17af66 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Request.php @@ -0,0 +1,157 @@ + $headers Request headers + * @param string|resource|StreamInterface|null $body Request body + * @param string $version Protocol version + */ + public function __construct( + string $method, + $uri, + array $headers = [], + $body = null, + string $version = '1.1' + ) { + $this->assertMethod($method); + if (!($uri instanceof UriInterface)) { + $uri = new Uri($uri); + } + + $this->method = strtoupper($method); + $this->uri = $uri; + $this->setHeaders($headers); + $this->protocol = $version; + + if (!isset($this->headerNames['host'])) { + $this->updateHostFromUri(); + } + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + } + + public function getRequestTarget(): string + { + if ($this->requestTarget !== null) { + return $this->requestTarget; + } + + $target = $this->uri->getPath(); + if ($target === '') { + $target = '/'; + } + if ($this->uri->getQuery() != '') { + $target .= '?' . $this->uri->getQuery(); + } + + return $target; + } + + public function withRequestTarget($requestTarget): RequestInterface + { + if (preg_match('#\s#', $requestTarget)) { + throw new InvalidArgumentException( + 'Invalid request target provided; cannot contain whitespace' + ); + } + + $new = clone $this; + $new->requestTarget = $requestTarget; + return $new; + } + + public function getMethod(): string + { + return $this->method; + } + + public function withMethod($method): RequestInterface + { + $this->assertMethod($method); + $new = clone $this; + $new->method = strtoupper($method); + return $new; + } + + public function getUri(): UriInterface + { + return $this->uri; + } + + public function withUri(UriInterface $uri, $preserveHost = false): RequestInterface + { + if ($uri === $this->uri) { + return $this; + } + + $new = clone $this; + $new->uri = $uri; + + if (!$preserveHost || !isset($this->headerNames['host'])) { + $new->updateHostFromUri(); + } + + return $new; + } + + private function updateHostFromUri(): void + { + $host = $this->uri->getHost(); + + if ($host == '') { + return; + } + + if (($port = $this->uri->getPort()) !== null) { + $host .= ':' . $port; + } + + if (isset($this->headerNames['host'])) { + $header = $this->headerNames['host']; + } else { + $header = 'Host'; + $this->headerNames['host'] = 'Host'; + } + // Ensure Host is the first header. + // See: http://tools.ietf.org/html/rfc7230#section-5.4 + $this->headers = [$header => [$host]] + $this->headers; + } + + /** + * @param mixed $method + */ + private function assertMethod($method): void + { + if (!is_string($method) || $method === '') { + throw new InvalidArgumentException('Method must be a non-empty string.'); + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Response.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Response.php new file mode 100644 index 0000000..4c6ee6f --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Response.php @@ -0,0 +1,160 @@ + 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-status', + 208 => 'Already Reported', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => 'Switch Proxy', + 307 => 'Temporary Redirect', + 308 => 'Permanent 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 Time-out', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Large', + 415 => 'Unsupported Media Type', + 416 => 'Requested range not satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 425 => 'Unordered Collection', + 426 => 'Upgrade Required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 451 => 'Unavailable For Legal Reasons', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Time-out', + 505 => 'HTTP Version not supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 510 => 'Not Extended', + 511 => 'Network Authentication Required', + ]; + + /** @var string */ + private $reasonPhrase; + + /** @var int */ + private $statusCode; + + /** + * @param int $status Status code + * @param array $headers Response headers + * @param string|resource|StreamInterface|null $body Response body + * @param string $version Protocol version + * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) + */ + public function __construct( + int $status = 200, + array $headers = [], + $body = null, + string $version = '1.1', + string $reason = null + ) { + $this->assertStatusCodeRange($status); + + $this->statusCode = $status; + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + + $this->setHeaders($headers); + if ($reason == '' && isset(self::PHRASES[$this->statusCode])) { + $this->reasonPhrase = self::PHRASES[$this->statusCode]; + } else { + $this->reasonPhrase = (string) $reason; + } + + $this->protocol = $version; + } + + public function getStatusCode(): int + { + return $this->statusCode; + } + + public function getReasonPhrase(): string + { + return $this->reasonPhrase; + } + + public function withStatus($code, $reasonPhrase = ''): ResponseInterface + { + $this->assertStatusCodeIsInteger($code); + $code = (int) $code; + $this->assertStatusCodeRange($code); + + $new = clone $this; + $new->statusCode = $code; + if ($reasonPhrase == '' && isset(self::PHRASES[$new->statusCode])) { + $reasonPhrase = self::PHRASES[$new->statusCode]; + } + $new->reasonPhrase = (string) $reasonPhrase; + return $new; + } + + /** + * @param mixed $statusCode + */ + private function assertStatusCodeIsInteger($statusCode): void + { + if (filter_var($statusCode, FILTER_VALIDATE_INT) === false) { + throw new \InvalidArgumentException('Status code must be an integer value.'); + } + } + + private function assertStatusCodeRange(int $statusCode): void + { + if ($statusCode < 100 || $statusCode >= 600) { + throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.'); + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Rfc7230.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Rfc7230.php new file mode 100644 index 0000000..3022401 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Rfc7230.php @@ -0,0 +1,23 @@ +@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m"; + public const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)"; +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/ServerRequest.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/ServerRequest.php new file mode 100644 index 0000000..43cbb50 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/ServerRequest.php @@ -0,0 +1,344 @@ + $headers Request headers + * @param string|resource|StreamInterface|null $body Request body + * @param string $version Protocol version + * @param array $serverParams Typically the $_SERVER superglobal + */ + public function __construct( + string $method, + $uri, + array $headers = [], + $body = null, + string $version = '1.1', + array $serverParams = [] + ) { + $this->serverParams = $serverParams; + + parent::__construct($method, $uri, $headers, $body, $version); + } + + /** + * Return an UploadedFile instance array. + * + * @param array $files An array which respect $_FILES structure + * + * @throws InvalidArgumentException for unrecognized values + */ + public static function normalizeFiles(array $files): array + { + $normalized = []; + + foreach ($files as $key => $value) { + if ($value instanceof UploadedFileInterface) { + $normalized[$key] = $value; + } elseif (is_array($value) && isset($value['tmp_name'])) { + $normalized[$key] = self::createUploadedFileFromSpec($value); + } elseif (is_array($value)) { + $normalized[$key] = self::normalizeFiles($value); + continue; + } else { + throw new InvalidArgumentException('Invalid value in files specification'); + } + } + + return $normalized; + } + + /** + * Create and return an UploadedFile instance from a $_FILES specification. + * + * If the specification represents an array of values, this method will + * delegate to normalizeNestedFileSpec() and return that return value. + * + * @param array $value $_FILES struct + * + * @return UploadedFileInterface|UploadedFileInterface[] + */ + private static function createUploadedFileFromSpec(array $value) + { + if (is_array($value['tmp_name'])) { + return self::normalizeNestedFileSpec($value); + } + + return new UploadedFile( + $value['tmp_name'], + (int) $value['size'], + (int) $value['error'], + $value['name'], + $value['type'] + ); + } + + /** + * Normalize an array of file specifications. + * + * Loops through all nested files and returns a normalized array of + * UploadedFileInterface instances. + * + * @return UploadedFileInterface[] + */ + private static function normalizeNestedFileSpec(array $files = []): array + { + $normalizedFiles = []; + + foreach (array_keys($files['tmp_name']) as $key) { + $spec = [ + 'tmp_name' => $files['tmp_name'][$key], + 'size' => $files['size'][$key], + 'error' => $files['error'][$key], + 'name' => $files['name'][$key], + 'type' => $files['type'][$key], + ]; + $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec); + } + + return $normalizedFiles; + } + + /** + * Return a ServerRequest populated with superglobals: + * $_GET + * $_POST + * $_COOKIE + * $_FILES + * $_SERVER + */ + public static function fromGlobals(): ServerRequestInterface + { + $method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; + $headers = getallheaders(); + $uri = self::getUriFromGlobals(); + $body = new CachingStream(new LazyOpenStream('php://input', 'r+')); + $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1'; + + $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER); + + return $serverRequest + ->withCookieParams($_COOKIE) + ->withQueryParams($_GET) + ->withParsedBody($_POST) + ->withUploadedFiles(self::normalizeFiles($_FILES)); + } + + private static function extractHostAndPortFromAuthority(string $authority): array + { + $uri = 'http://' . $authority; + $parts = parse_url($uri); + if (false === $parts) { + return [null, null]; + } + + $host = $parts['host'] ?? null; + $port = $parts['port'] ?? null; + + return [$host, $port]; + } + + /** + * Get a Uri populated with values from $_SERVER. + */ + public static function getUriFromGlobals(): UriInterface + { + $uri = new Uri(''); + + $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http'); + + $hasPort = false; + if (isset($_SERVER['HTTP_HOST'])) { + [$host, $port] = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']); + if ($host !== null) { + $uri = $uri->withHost($host); + } + + if ($port !== null) { + $hasPort = true; + $uri = $uri->withPort($port); + } + } elseif (isset($_SERVER['SERVER_NAME'])) { + $uri = $uri->withHost($_SERVER['SERVER_NAME']); + } elseif (isset($_SERVER['SERVER_ADDR'])) { + $uri = $uri->withHost($_SERVER['SERVER_ADDR']); + } + + if (!$hasPort && isset($_SERVER['SERVER_PORT'])) { + $uri = $uri->withPort($_SERVER['SERVER_PORT']); + } + + $hasQuery = false; + if (isset($_SERVER['REQUEST_URI'])) { + $requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2); + $uri = $uri->withPath($requestUriParts[0]); + if (isset($requestUriParts[1])) { + $hasQuery = true; + $uri = $uri->withQuery($requestUriParts[1]); + } + } + + if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) { + $uri = $uri->withQuery($_SERVER['QUERY_STRING']); + } + + return $uri; + } + + public function getServerParams(): array + { + return $this->serverParams; + } + + public function getUploadedFiles(): array + { + return $this->uploadedFiles; + } + + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface + { + $new = clone $this; + $new->uploadedFiles = $uploadedFiles; + + return $new; + } + + public function getCookieParams(): array + { + return $this->cookieParams; + } + + public function withCookieParams(array $cookies): ServerRequestInterface + { + $new = clone $this; + $new->cookieParams = $cookies; + + return $new; + } + + public function getQueryParams(): array + { + return $this->queryParams; + } + + public function withQueryParams(array $query): ServerRequestInterface + { + $new = clone $this; + $new->queryParams = $query; + + return $new; + } + + /** + * {@inheritdoc} + * + * @return array|object|null + */ + public function getParsedBody() + { + return $this->parsedBody; + } + + public function withParsedBody($data): ServerRequestInterface + { + $new = clone $this; + $new->parsedBody = $data; + + return $new; + } + + public function getAttributes(): array + { + return $this->attributes; + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getAttribute($attribute, $default = null) + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $default; + } + + return $this->attributes[$attribute]; + } + + public function withAttribute($attribute, $value): ServerRequestInterface + { + $new = clone $this; + $new->attributes[$attribute] = $value; + + return $new; + } + + public function withoutAttribute($attribute): ServerRequestInterface + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $this; + } + + $new = clone $this; + unset($new->attributes[$attribute]); + + return $new; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Stream.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Stream.php new file mode 100644 index 0000000..ecd3186 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Stream.php @@ -0,0 +1,282 @@ +size = $options['size']; + } + + $this->customMetadata = $options['metadata'] ?? []; + $this->stream = $stream; + $meta = stream_get_meta_data($this->stream); + $this->seekable = $meta['seekable']; + $this->readable = (bool)preg_match(self::READABLE_MODES, $meta['mode']); + $this->writable = (bool)preg_match(self::WRITABLE_MODES, $meta['mode']); + $this->uri = $this->getMetadata('uri'); + } + + /** + * Closes the stream when the destructed + */ + public function __destruct() + { + $this->close(); + } + + public function __toString(): string + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function getContents(): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + + return Utils::tryGetContents($this->stream); + } + + public function close(): void + { + if (isset($this->stream)) { + if (is_resource($this->stream)) { + fclose($this->stream); + } + $this->detach(); + } + } + + public function detach() + { + if (!isset($this->stream)) { + return null; + } + + $result = $this->stream; + unset($this->stream); + $this->size = $this->uri = null; + $this->readable = $this->writable = $this->seekable = false; + + return $result; + } + + public function getSize(): ?int + { + if ($this->size !== null) { + return $this->size; + } + + if (!isset($this->stream)) { + return null; + } + + // Clear the stat cache if the stream has a URI + if ($this->uri) { + clearstatcache(true, $this->uri); + } + + $stats = fstat($this->stream); + if (is_array($stats) && isset($stats['size'])) { + $this->size = $stats['size']; + return $this->size; + } + + return null; + } + + public function isReadable(): bool + { + return $this->readable; + } + + public function isWritable(): bool + { + return $this->writable; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function eof(): bool + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + return feof($this->stream); + } + + public function tell(): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + $result = ftell($this->stream); + + if ($result === false) { + throw new \RuntimeException('Unable to determine stream position'); + } + + return $result; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + $whence = (int) $whence; + + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->seekable) { + throw new \RuntimeException('Stream is not seekable'); + } + if (fseek($this->stream, $offset, $whence) === -1) { + throw new \RuntimeException('Unable to seek to stream position ' + . $offset . ' with whence ' . var_export($whence, true)); + } + } + + public function read($length): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if (0 === $length) { + return ''; + } + + try { + $string = fread($this->stream, $length); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to read from stream', 0, $e); + } + + if (false === $string) { + throw new \RuntimeException('Unable to read from stream'); + } + + return $string; + } + + public function write($string): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->writable) { + throw new \RuntimeException('Cannot write to a non-writable stream'); + } + + // We can't know the size after writing anything + $this->size = null; + $result = fwrite($this->stream, $string); + + if ($result === false) { + throw new \RuntimeException('Unable to write to stream'); + } + + return $result; + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + if (!isset($this->stream)) { + return $key ? null : []; + } elseif (!$key) { + return $this->customMetadata + stream_get_meta_data($this->stream); + } elseif (isset($this->customMetadata[$key])) { + return $this->customMetadata[$key]; + } + + $meta = stream_get_meta_data($this->stream); + + return $meta[$key] ?? null; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php new file mode 100644 index 0000000..56d4104 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php @@ -0,0 +1,155 @@ +stream = $stream; + } + + /** + * Magic method used to create a new stream if streams are not added in + * the constructor of a decorator (e.g., LazyOpenStream). + * + * @return StreamInterface + */ + public function __get(string $name) + { + if ($name === 'stream') { + $this->stream = $this->createStream(); + return $this->stream; + } + + throw new \UnexpectedValueException("$name not found on class"); + } + + public function __toString(): string + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Allow decorators to implement custom methods + * + * @return mixed + */ + public function __call(string $method, array $args) + { + /** @var callable $callable */ + $callable = [$this->stream, $method]; + $result = call_user_func_array($callable, $args); + + // Always return the wrapped object if the result is a return $this + return $result === $this->stream ? $this : $result; + } + + public function close(): void + { + $this->stream->close(); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + return $this->stream->getMetadata($key); + } + + public function detach() + { + return $this->stream->detach(); + } + + public function getSize(): ?int + { + return $this->stream->getSize(); + } + + public function eof(): bool + { + return $this->stream->eof(); + } + + public function tell(): int + { + return $this->stream->tell(); + } + + public function isReadable(): bool + { + return $this->stream->isReadable(); + } + + public function isWritable(): bool + { + return $this->stream->isWritable(); + } + + public function isSeekable(): bool + { + return $this->stream->isSeekable(); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + $this->stream->seek($offset, $whence); + } + + public function read($length): string + { + return $this->stream->read($length); + } + + public function write($string): int + { + return $this->stream->write($string); + } + + /** + * Implement in subclasses to dynamically create streams when requested. + * + * @throws \BadMethodCallException + */ + protected function createStream(): StreamInterface + { + throw new \BadMethodCallException('Not implemented'); + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/StreamWrapper.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/StreamWrapper.php new file mode 100644 index 0000000..2a93464 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/StreamWrapper.php @@ -0,0 +1,175 @@ +isReadable()) { + $mode = $stream->isWritable() ? 'r+' : 'r'; + } elseif ($stream->isWritable()) { + $mode = 'w'; + } else { + throw new \InvalidArgumentException('The stream must be readable, ' + . 'writable, or both.'); + } + + return fopen('guzzle://stream', $mode, false, self::createStreamContext($stream)); + } + + /** + * Creates a stream context that can be used to open a stream as a php stream resource. + * + * @return resource + */ + public static function createStreamContext(StreamInterface $stream) + { + return stream_context_create([ + 'guzzle' => ['stream' => $stream] + ]); + } + + /** + * Registers the stream wrapper if needed + */ + public static function register(): void + { + if (!in_array('guzzle', stream_get_wrappers())) { + stream_wrapper_register('guzzle', __CLASS__); + } + } + + public function stream_open(string $path, string $mode, int $options, string &$opened_path = null): bool + { + $options = stream_context_get_options($this->context); + + if (!isset($options['guzzle']['stream'])) { + return false; + } + + $this->mode = $mode; + $this->stream = $options['guzzle']['stream']; + + return true; + } + + public function stream_read(int $count): string + { + return $this->stream->read($count); + } + + public function stream_write(string $data): int + { + return $this->stream->write($data); + } + + public function stream_tell(): int + { + return $this->stream->tell(); + } + + public function stream_eof(): bool + { + return $this->stream->eof(); + } + + public function stream_seek(int $offset, int $whence): bool + { + $this->stream->seek($offset, $whence); + + return true; + } + + /** + * @return resource|false + */ + public function stream_cast(int $cast_as) + { + $stream = clone($this->stream); + $resource = $stream->detach(); + + return $resource ?? false; + } + + /** + * @return array + */ + public function stream_stat(): array + { + static $modeMap = [ + 'r' => 33060, + 'rb' => 33060, + 'r+' => 33206, + 'w' => 33188, + 'wb' => 33188 + ]; + + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => $modeMap[$this->mode], + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => $this->stream->getSize() ?: 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0 + ]; + } + + /** + * @return array + */ + public function url_stat(string $path, int $flags): array + { + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => 0, + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0 + ]; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UploadedFile.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UploadedFile.php new file mode 100644 index 0000000..b1521bc --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UploadedFile.php @@ -0,0 +1,211 @@ +setError($errorStatus); + $this->size = $size; + $this->clientFilename = $clientFilename; + $this->clientMediaType = $clientMediaType; + + if ($this->isOk()) { + $this->setStreamOrFile($streamOrFile); + } + } + + /** + * Depending on the value set file or stream variable + * + * @param StreamInterface|string|resource $streamOrFile + * + * @throws InvalidArgumentException + */ + private function setStreamOrFile($streamOrFile): void + { + if (is_string($streamOrFile)) { + $this->file = $streamOrFile; + } elseif (is_resource($streamOrFile)) { + $this->stream = new Stream($streamOrFile); + } elseif ($streamOrFile instanceof StreamInterface) { + $this->stream = $streamOrFile; + } else { + throw new InvalidArgumentException( + 'Invalid stream or file provided for UploadedFile' + ); + } + } + + /** + * @throws InvalidArgumentException + */ + private function setError(int $error): void + { + if (false === in_array($error, UploadedFile::ERRORS, true)) { + throw new InvalidArgumentException( + 'Invalid error status for UploadedFile' + ); + } + + $this->error = $error; + } + + private function isStringNotEmpty($param): bool + { + return is_string($param) && false === empty($param); + } + + /** + * Return true if there is no upload error + */ + private function isOk(): bool + { + return $this->error === UPLOAD_ERR_OK; + } + + public function isMoved(): bool + { + return $this->moved; + } + + /** + * @throws RuntimeException if is moved or not ok + */ + private function validateActive(): void + { + if (false === $this->isOk()) { + throw new RuntimeException('Cannot retrieve stream due to upload error'); + } + + if ($this->isMoved()) { + throw new RuntimeException('Cannot retrieve stream after it has already been moved'); + } + } + + public function getStream(): StreamInterface + { + $this->validateActive(); + + if ($this->stream instanceof StreamInterface) { + return $this->stream; + } + + /** @var string $file */ + $file = $this->file; + + return new LazyOpenStream($file, 'r+'); + } + + public function moveTo($targetPath): void + { + $this->validateActive(); + + if (false === $this->isStringNotEmpty($targetPath)) { + throw new InvalidArgumentException( + 'Invalid path provided for move operation; must be a non-empty string' + ); + } + + if ($this->file) { + $this->moved = PHP_SAPI === 'cli' + ? rename($this->file, $targetPath) + : move_uploaded_file($this->file, $targetPath); + } else { + Utils::copyToStream( + $this->getStream(), + new LazyOpenStream($targetPath, 'w') + ); + + $this->moved = true; + } + + if (false === $this->moved) { + throw new RuntimeException( + sprintf('Uploaded file could not be moved to %s', $targetPath) + ); + } + } + + public function getSize(): ?int + { + return $this->size; + } + + public function getError(): int + { + return $this->error; + } + + public function getClientFilename(): ?string + { + return $this->clientFilename; + } + + public function getClientMediaType(): ?string + { + return $this->clientMediaType; + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Uri.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Uri.php new file mode 100644 index 0000000..09e878d --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Uri.php @@ -0,0 +1,740 @@ + 80, + 'https' => 443, + 'ftp' => 21, + 'gopher' => 70, + 'nntp' => 119, + 'news' => 119, + 'telnet' => 23, + 'tn3270' => 23, + 'imap' => 143, + 'pop' => 110, + 'ldap' => 389, + ]; + + /** + * Unreserved characters for use in a regex. + * + * @link https://tools.ietf.org/html/rfc3986#section-2.3 + */ + private const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~'; + + /** + * Sub-delims for use in a regex. + * + * @link https://tools.ietf.org/html/rfc3986#section-2.2 + */ + private const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;='; + private const QUERY_SEPARATORS_REPLACEMENT = ['=' => '%3D', '&' => '%26']; + + /** @var string Uri scheme. */ + private $scheme = ''; + + /** @var string Uri user info. */ + private $userInfo = ''; + + /** @var string Uri host. */ + private $host = ''; + + /** @var int|null Uri port. */ + private $port; + + /** @var string Uri path. */ + private $path = ''; + + /** @var string Uri query string. */ + private $query = ''; + + /** @var string Uri fragment. */ + private $fragment = ''; + + /** @var string|null String representation */ + private $composedComponents; + + public function __construct(string $uri = '') + { + if ($uri !== '') { + $parts = self::parse($uri); + if ($parts === false) { + throw new MalformedUriException("Unable to parse URI: $uri"); + } + $this->applyParts($parts); + } + } + /** + * UTF-8 aware \parse_url() replacement. + * + * The internal function produces broken output for non ASCII domain names + * (IDN) when used with locales other than "C". + * + * On the other hand, cURL understands IDN correctly only when UTF-8 locale + * is configured ("C.UTF-8", "en_US.UTF-8", etc.). + * + * @see https://bugs.php.net/bug.php?id=52923 + * @see https://www.php.net/manual/en/function.parse-url.php#114817 + * @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING + * + * @return array|false + */ + private static function parse(string $url) + { + // If IPv6 + $prefix = ''; + if (preg_match('%^(.*://\[[0-9:a-f]+\])(.*?)$%', $url, $matches)) { + /** @var array{0:string, 1:string, 2:string} $matches */ + $prefix = $matches[1]; + $url = $matches[2]; + } + + /** @var string */ + $encodedUrl = preg_replace_callback( + '%[^:/@?&=#]+%usD', + static function ($matches) { + return urlencode($matches[0]); + }, + $url + ); + + $result = parse_url($prefix . $encodedUrl); + + if ($result === false) { + return false; + } + + return array_map('urldecode', $result); + } + + public function __toString(): string + { + if ($this->composedComponents === null) { + $this->composedComponents = self::composeComponents( + $this->scheme, + $this->getAuthority(), + $this->path, + $this->query, + $this->fragment + ); + } + + return $this->composedComponents; + } + + /** + * Composes a URI reference string from its various components. + * + * Usually this method does not need to be called manually but instead is used indirectly via + * `Psr\Http\Message\UriInterface::__toString`. + * + * PSR-7 UriInterface treats an empty component the same as a missing component as + * getQuery(), getFragment() etc. always return a string. This explains the slight + * difference to RFC 3986 Section 5.3. + * + * Another adjustment is that the authority separator is added even when the authority is missing/empty + * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with + * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But + * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to + * that format). + * + * @link https://tools.ietf.org/html/rfc3986#section-5.3 + */ + public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string + { + $uri = ''; + + // weak type checks to also accept null until we can add scalar type hints + if ($scheme != '') { + $uri .= $scheme . ':'; + } + + if ($authority != '' || $scheme === 'file') { + $uri .= '//' . $authority; + } + + if ($authority != '' && $path != '' && $path[0] != '/') { + $path = '/' . $path; + } + + $uri .= $path; + + if ($query != '') { + $uri .= '?' . $query; + } + + if ($fragment != '') { + $uri .= '#' . $fragment; + } + + return $uri; + } + + /** + * Whether the URI has the default port of the current scheme. + * + * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used + * independently of the implementation. + */ + public static function isDefaultPort(UriInterface $uri): bool + { + return $uri->getPort() === null + || (isset(self::DEFAULT_PORTS[$uri->getScheme()]) && $uri->getPort() === self::DEFAULT_PORTS[$uri->getScheme()]); + } + + /** + * Whether the URI is absolute, i.e. it has a scheme. + * + * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true + * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative + * to another URI, the base URI. Relative references can be divided into several forms: + * - network-path references, e.g. '//example.com/path' + * - absolute-path references, e.g. '/path' + * - relative-path references, e.g. 'subpath' + * + * @see Uri::isNetworkPathReference + * @see Uri::isAbsolutePathReference + * @see Uri::isRelativePathReference + * @link https://tools.ietf.org/html/rfc3986#section-4 + */ + public static function isAbsolute(UriInterface $uri): bool + { + return $uri->getScheme() !== ''; + } + + /** + * Whether the URI is a network-path reference. + * + * A relative reference that begins with two slash characters is termed an network-path reference. + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isNetworkPathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' && $uri->getAuthority() !== ''; + } + + /** + * Whether the URI is a absolute-path reference. + * + * A relative reference that begins with a single slash character is termed an absolute-path reference. + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isAbsolutePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && isset($uri->getPath()[0]) + && $uri->getPath()[0] === '/'; + } + + /** + * Whether the URI is a relative-path reference. + * + * A relative reference that does not begin with a slash character is termed a relative-path reference. + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isRelativePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); + } + + /** + * Whether the URI is a same-document reference. + * + * A same-document reference refers to a URI that is, aside from its fragment + * component, identical to the base URI. When no base URI is given, only an empty + * URI reference (apart from its fragment) is considered a same-document reference. + * + * @param UriInterface $uri The URI to check + * @param UriInterface|null $base An optional base URI to compare against + * + * @link https://tools.ietf.org/html/rfc3986#section-4.4 + */ + public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool + { + if ($base !== null) { + $uri = UriResolver::resolve($base, $uri); + + return ($uri->getScheme() === $base->getScheme()) + && ($uri->getAuthority() === $base->getAuthority()) + && ($uri->getPath() === $base->getPath()) + && ($uri->getQuery() === $base->getQuery()); + } + + return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; + } + + /** + * Creates a new URI with a specific query string value removed. + * + * Any existing query string values that exactly match the provided key are + * removed. + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Query string key to remove. + */ + public static function withoutQueryValue(UriInterface $uri, string $key): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with a specific query string value. + * + * Any existing query string values that exactly match the provided key are + * removed and replaced with the given key value pair. + * + * A value of null will set the query string key without a value, e.g. "key" + * instead of "key=value". + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Key to set. + * @param string|null $value Value to set + */ + public static function withQueryValue(UriInterface $uri, string $key, ?string $value): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + $result[] = self::generateQueryString($key, $value); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with multiple specific query string values. + * + * It has the same behavior as withQueryValue() but for an associative array of key => value. + * + * @param UriInterface $uri URI to use as a base. + * @param array $keyValueArray Associative array of key and values + */ + public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface + { + $result = self::getFilteredQueryString($uri, array_keys($keyValueArray)); + + foreach ($keyValueArray as $key => $value) { + $result[] = self::generateQueryString((string) $key, $value !== null ? (string) $value : null); + } + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a URI from a hash of `parse_url` components. + * + * @link http://php.net/manual/en/function.parse-url.php + * + * @throws MalformedUriException If the components do not form a valid URI. + */ + public static function fromParts(array $parts): UriInterface + { + $uri = new self(); + $uri->applyParts($parts); + $uri->validateState(); + + return $uri; + } + + public function getScheme(): string + { + return $this->scheme; + } + + public function getAuthority(): string + { + $authority = $this->host; + if ($this->userInfo !== '') { + $authority = $this->userInfo . '@' . $authority; + } + + if ($this->port !== null) { + $authority .= ':' . $this->port; + } + + return $authority; + } + + public function getUserInfo(): string + { + return $this->userInfo; + } + + public function getHost(): string + { + return $this->host; + } + + public function getPort(): ?int + { + return $this->port; + } + + public function getPath(): string + { + return $this->path; + } + + public function getQuery(): string + { + return $this->query; + } + + public function getFragment(): string + { + return $this->fragment; + } + + public function withScheme($scheme): UriInterface + { + $scheme = $this->filterScheme($scheme); + + if ($this->scheme === $scheme) { + return $this; + } + + $new = clone $this; + $new->scheme = $scheme; + $new->composedComponents = null; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withUserInfo($user, $password = null): UriInterface + { + $info = $this->filterUserInfoComponent($user); + if ($password !== null) { + $info .= ':' . $this->filterUserInfoComponent($password); + } + + if ($this->userInfo === $info) { + return $this; + } + + $new = clone $this; + $new->userInfo = $info; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withHost($host): UriInterface + { + $host = $this->filterHost($host); + + if ($this->host === $host) { + return $this; + } + + $new = clone $this; + $new->host = $host; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withPort($port): UriInterface + { + $port = $this->filterPort($port); + + if ($this->port === $port) { + return $this; + } + + $new = clone $this; + $new->port = $port; + $new->composedComponents = null; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withPath($path): UriInterface + { + $path = $this->filterPath($path); + + if ($this->path === $path) { + return $this; + } + + $new = clone $this; + $new->path = $path; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withQuery($query): UriInterface + { + $query = $this->filterQueryAndFragment($query); + + if ($this->query === $query) { + return $this; + } + + $new = clone $this; + $new->query = $query; + $new->composedComponents = null; + + return $new; + } + + public function withFragment($fragment): UriInterface + { + $fragment = $this->filterQueryAndFragment($fragment); + + if ($this->fragment === $fragment) { + return $this; + } + + $new = clone $this; + $new->fragment = $fragment; + $new->composedComponents = null; + + return $new; + } + + public function jsonSerialize(): string + { + return $this->__toString(); + } + + /** + * Apply parse_url parts to a URI. + * + * @param array $parts Array of parse_url parts to apply. + */ + private function applyParts(array $parts): void + { + $this->scheme = isset($parts['scheme']) + ? $this->filterScheme($parts['scheme']) + : ''; + $this->userInfo = isset($parts['user']) + ? $this->filterUserInfoComponent($parts['user']) + : ''; + $this->host = isset($parts['host']) + ? $this->filterHost($parts['host']) + : ''; + $this->port = isset($parts['port']) + ? $this->filterPort($parts['port']) + : null; + $this->path = isset($parts['path']) + ? $this->filterPath($parts['path']) + : ''; + $this->query = isset($parts['query']) + ? $this->filterQueryAndFragment($parts['query']) + : ''; + $this->fragment = isset($parts['fragment']) + ? $this->filterQueryAndFragment($parts['fragment']) + : ''; + if (isset($parts['pass'])) { + $this->userInfo .= ':' . $this->filterUserInfoComponent($parts['pass']); + } + + $this->removeDefaultPort(); + } + + /** + * @param mixed $scheme + * + * @throws \InvalidArgumentException If the scheme is invalid. + */ + private function filterScheme($scheme): string + { + if (!is_string($scheme)) { + throw new \InvalidArgumentException('Scheme must be a string'); + } + + return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param mixed $component + * + * @throws \InvalidArgumentException If the user info is invalid. + */ + private function filterUserInfoComponent($component): string + { + if (!is_string($component)) { + throw new \InvalidArgumentException('User info must be a string'); + } + + return preg_replace_callback( + '/(?:[^%' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . ']+|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $component + ); + } + + /** + * @param mixed $host + * + * @throws \InvalidArgumentException If the host is invalid. + */ + private function filterHost($host): string + { + if (!is_string($host)) { + throw new \InvalidArgumentException('Host must be a string'); + } + + return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param mixed $port + * + * @throws \InvalidArgumentException If the port is invalid. + */ + private function filterPort($port): ?int + { + if ($port === null) { + return null; + } + + $port = (int) $port; + if (0 > $port || 0xffff < $port) { + throw new \InvalidArgumentException( + sprintf('Invalid port: %d. Must be between 0 and 65535', $port) + ); + } + + return $port; + } + + /** + * @param string[] $keys + * + * @return string[] + */ + private static function getFilteredQueryString(UriInterface $uri, array $keys): array + { + $current = $uri->getQuery(); + + if ($current === '') { + return []; + } + + $decodedKeys = array_map('rawurldecode', $keys); + + return array_filter(explode('&', $current), function ($part) use ($decodedKeys) { + return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true); + }); + } + + private static function generateQueryString(string $key, ?string $value): string + { + // Query string separators ("=", "&") within the key or value need to be encoded + // (while preventing double-encoding) before setting the query string. All other + // chars that need percent-encoding will be encoded by withQuery(). + $queryString = strtr($key, self::QUERY_SEPARATORS_REPLACEMENT); + + if ($value !== null) { + $queryString .= '=' . strtr($value, self::QUERY_SEPARATORS_REPLACEMENT); + } + + return $queryString; + } + + private function removeDefaultPort(): void + { + if ($this->port !== null && self::isDefaultPort($this)) { + $this->port = null; + } + } + + /** + * Filters the path of a URI + * + * @param mixed $path + * + * @throws \InvalidArgumentException If the path is invalid. + */ + private function filterPath($path): string + { + if (!is_string($path)) { + throw new \InvalidArgumentException('Path must be a string'); + } + + return preg_replace_callback( + '/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $path + ); + } + + /** + * Filters the query string or fragment of a URI. + * + * @param mixed $str + * + * @throws \InvalidArgumentException If the query or fragment is invalid. + */ + private function filterQueryAndFragment($str): string + { + if (!is_string($str)) { + throw new \InvalidArgumentException('Query and fragment must be a string'); + } + + return preg_replace_callback( + '/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $str + ); + } + + private function rawurlencodeMatchZero(array $match): string + { + return rawurlencode($match[0]); + } + + private function validateState(): void + { + if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { + $this->host = self::HTTP_DEFAULT_HOST; + } + + if ($this->getAuthority() === '') { + if (0 === strpos($this->path, '//')) { + throw new MalformedUriException('The path of a URI without an authority must not start with two slashes "//"'); + } + if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { + throw new MalformedUriException('A relative URI must not have a path beginning with a segment containing a colon'); + } + } + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriComparator.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriComparator.php new file mode 100644 index 0000000..70c582a --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriComparator.php @@ -0,0 +1,52 @@ +getHost(), $modified->getHost()) !== 0) { + return true; + } + + if ($original->getScheme() !== $modified->getScheme()) { + return true; + } + + if (self::computePort($original) !== self::computePort($modified)) { + return true; + } + + return false; + } + + private static function computePort(UriInterface $uri): int + { + $port = $uri->getPort(); + + if (null !== $port) { + return $port; + } + + return 'https' === $uri->getScheme() ? 443 : 80; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriNormalizer.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriNormalizer.php new file mode 100644 index 0000000..e12971e --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriNormalizer.php @@ -0,0 +1,220 @@ +getPath() === '' && + ($uri->getScheme() === 'http' || $uri->getScheme() === 'https') + ) { + $uri = $uri->withPath('/'); + } + + if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') { + $uri = $uri->withHost(''); + } + + if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) { + $uri = $uri->withPort(null); + } + + if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) { + $uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath())); + } + + if ($flags & self::REMOVE_DUPLICATE_SLASHES) { + $uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath())); + } + + if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') { + $queryKeyValues = explode('&', $uri->getQuery()); + sort($queryKeyValues); + $uri = $uri->withQuery(implode('&', $queryKeyValues)); + } + + return $uri; + } + + /** + * Whether two URIs can be considered equivalent. + * + * Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also + * accepts relative URI references and returns true when they are equivalent. This of course assumes they will be + * resolved against the same base URI. If this is not the case, determination of equivalence or difference of + * relative references does not mean anything. + * + * @param UriInterface $uri1 An URI to compare + * @param UriInterface $uri2 An URI to compare + * @param int $normalizations A bitmask of normalizations to apply, see constants + * + * @link https://tools.ietf.org/html/rfc3986#section-6.1 + */ + public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, int $normalizations = self::PRESERVING_NORMALIZATIONS): bool + { + return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations); + } + + private static function capitalizePercentEncoding(UriInterface $uri): UriInterface + { + $regex = '/(?:%[A-Fa-f0-9]{2})++/'; + + $callback = function (array $match) { + return strtoupper($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private static function decodeUnreservedCharacters(UriInterface $uri): UriInterface + { + $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i'; + + $callback = function (array $match) { + return rawurldecode($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriResolver.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriResolver.php new file mode 100644 index 0000000..426e5c9 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/UriResolver.php @@ -0,0 +1,211 @@ +getScheme() != '') { + return $rel->withPath(self::removeDotSegments($rel->getPath())); + } + + if ($rel->getAuthority() != '') { + $targetAuthority = $rel->getAuthority(); + $targetPath = self::removeDotSegments($rel->getPath()); + $targetQuery = $rel->getQuery(); + } else { + $targetAuthority = $base->getAuthority(); + if ($rel->getPath() === '') { + $targetPath = $base->getPath(); + $targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery(); + } else { + if ($rel->getPath()[0] === '/') { + $targetPath = $rel->getPath(); + } else { + if ($targetAuthority != '' && $base->getPath() === '') { + $targetPath = '/' . $rel->getPath(); + } else { + $lastSlashPos = strrpos($base->getPath(), '/'); + if ($lastSlashPos === false) { + $targetPath = $rel->getPath(); + } else { + $targetPath = substr($base->getPath(), 0, $lastSlashPos + 1) . $rel->getPath(); + } + } + } + $targetPath = self::removeDotSegments($targetPath); + $targetQuery = $rel->getQuery(); + } + } + + return new Uri(Uri::composeComponents( + $base->getScheme(), + $targetAuthority, + $targetPath, + $targetQuery, + $rel->getFragment() + )); + } + + /** + * Returns the target URI as a relative reference from the base URI. + * + * This method is the counterpart to resolve(): + * + * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) + * + * One use-case is to use the current request URI as base URI and then generate relative links in your documents + * to reduce the document size or offer self-contained downloadable document archives. + * + * $base = new Uri('http://example.com/a/b/'); + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. + * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. + * + * This method also accepts a target that is already relative and will try to relativize it further. Only a + * relative-path reference will be returned as-is. + * + * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well + */ + public static function relativize(UriInterface $base, UriInterface $target): UriInterface + { + if ($target->getScheme() !== '' && + ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '') + ) { + return $target; + } + + if (Uri::isRelativePathReference($target)) { + // As the target is already highly relative we return it as-is. It would be possible to resolve + // the target with `$target = self::resolve($base, $target);` and then try make it more relative + // by removing a duplicate query. But let's not do that automatically. + return $target; + } + + if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) { + return $target->withScheme(''); + } + + // We must remove the path before removing the authority because if the path starts with two slashes, the URI + // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also + // invalid. + $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost(''); + + if ($base->getPath() !== $target->getPath()) { + return $emptyPathUri->withPath(self::getRelativePath($base, $target)); + } + + if ($base->getQuery() === $target->getQuery()) { + // Only the target fragment is left. And it must be returned even if base and target fragment are the same. + return $emptyPathUri->withQuery(''); + } + + // If the base URI has a query but the target has none, we cannot return an empty path reference as it would + // inherit the base query component when resolving. + if ($target->getQuery() === '') { + $segments = explode('/', $target->getPath()); + /** @var string $lastSegment */ + $lastSegment = end($segments); + + return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment); + } + + return $emptyPathUri; + } + + private static function getRelativePath(UriInterface $base, UriInterface $target): string + { + $sourceSegments = explode('/', $base->getPath()); + $targetSegments = explode('/', $target->getPath()); + array_pop($sourceSegments); + $targetLastSegment = array_pop($targetSegments); + foreach ($sourceSegments as $i => $segment) { + if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) { + unset($sourceSegments[$i], $targetSegments[$i]); + } else { + break; + } + } + $targetSegments[] = $targetLastSegment; + $relativePath = str_repeat('../', count($sourceSegments)) . implode('/', $targetSegments); + + // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./". + // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used + // as the first segment of a relative-path reference, as it would be mistaken for a scheme name. + if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) { + $relativePath = "./$relativePath"; + } elseif ('/' === $relativePath[0]) { + if ($base->getAuthority() != '' && $base->getPath() === '') { + // In this case an extra slash is added by resolve() automatically. So we must not add one here. + $relativePath = ".$relativePath"; + } else { + $relativePath = "./$relativePath"; + } + } + + return $relativePath; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Utils.php b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Utils.php new file mode 100644 index 0000000..3a4cf39 --- /dev/null +++ b/plugins/login-oauth2/vendor/guzzlehttp/psr7/src/Utils.php @@ -0,0 +1,459 @@ + $v) { + if (!is_string($k) || !in_array(strtolower($k), $keys)) { + $result[$k] = $v; + } + } + + return $result; + } + + /** + * Copy the contents of a stream into another stream until the given number + * of bytes have been read. + * + * @param StreamInterface $source Stream to read from + * @param StreamInterface $dest Stream to write to + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void + { + $bufferSize = 8192; + + if ($maxLen === -1) { + while (!$source->eof()) { + if (!$dest->write($source->read($bufferSize))) { + break; + } + } + } else { + $remaining = $maxLen; + while ($remaining > 0 && !$source->eof()) { + $buf = $source->read(min($bufferSize, $remaining)); + $len = strlen($buf); + if (!$len) { + break; + } + $remaining -= $len; + $dest->write($buf); + } + } + } + + /** + * Copy the contents of a stream into a string until the given number of + * bytes have been read. + * + * @param StreamInterface $stream Stream to read + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToString(StreamInterface $stream, int $maxLen = -1): string + { + $buffer = ''; + + if ($maxLen === -1) { + while (!$stream->eof()) { + $buf = $stream->read(1048576); + if ($buf === '') { + break; + } + $buffer .= $buf; + } + return $buffer; + } + + $len = 0; + while (!$stream->eof() && $len < $maxLen) { + $buf = $stream->read($maxLen - $len); + if ($buf === '') { + break; + } + $buffer .= $buf; + $len = strlen($buffer); + } + + return $buffer; + } + + /** + * Calculate a hash of a stream. + * + * This method reads the entire stream to calculate a rolling hash, based + * on PHP's `hash_init` functions. + * + * @param StreamInterface $stream Stream to calculate the hash for + * @param string $algo Hash algorithm (e.g. md5, crc32, etc) + * @param bool $rawOutput Whether or not to use raw output + * + * @throws \RuntimeException on error. + */ + public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string + { + $pos = $stream->tell(); + + if ($pos > 0) { + $stream->rewind(); + } + + $ctx = hash_init($algo); + while (!$stream->eof()) { + hash_update($ctx, $stream->read(1048576)); + } + + $out = hash_final($ctx, $rawOutput); + $stream->seek($pos); + + return $out; + } + + /** + * Clone and modify a request with the given changes. + * + * This method is useful for reducing the number of clones needed to mutate + * a message. + * + * The changes can be one of: + * - method: (string) Changes the HTTP method. + * - set_headers: (array) Sets the given headers. + * - remove_headers: (array) Remove the given headers. + * - body: (mixed) Sets the given body. + * - uri: (UriInterface) Set the URI. + * - query: (string) Set the query string value of the URI. + * - version: (string) Set the protocol version. + * + * @param RequestInterface $request Request to clone and modify. + * @param array $changes Changes to apply. + */ + public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface + { + if (!$changes) { + return $request; + } + + $headers = $request->getHeaders(); + + if (!isset($changes['uri'])) { + $uri = $request->getUri(); + } else { + // Remove the host header if one is on the URI + if ($host = $changes['uri']->getHost()) { + $changes['set_headers']['Host'] = $host; + + if ($port = $changes['uri']->getPort()) { + $standardPorts = ['http' => 80, 'https' => 443]; + $scheme = $changes['uri']->getScheme(); + if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { + $changes['set_headers']['Host'] .= ':' . $port; + } + } + } + $uri = $changes['uri']; + } + + if (!empty($changes['remove_headers'])) { + $headers = self::caselessRemove($changes['remove_headers'], $headers); + } + + if (!empty($changes['set_headers'])) { + $headers = self::caselessRemove(array_keys($changes['set_headers']), $headers); + $headers = $changes['set_headers'] + $headers; + } + + if (isset($changes['query'])) { + $uri = $uri->withQuery($changes['query']); + } + + if ($request instanceof ServerRequestInterface) { + $new = (new ServerRequest( + $changes['method'] ?? $request->getMethod(), + $uri, + $headers, + $changes['body'] ?? $request->getBody(), + $changes['version'] ?? $request->getProtocolVersion(), + $request->getServerParams() + )) + ->withParsedBody($request->getParsedBody()) + ->withQueryParams($request->getQueryParams()) + ->withCookieParams($request->getCookieParams()) + ->withUploadedFiles($request->getUploadedFiles()); + + foreach ($request->getAttributes() as $key => $value) { + $new = $new->withAttribute($key, $value); + } + + return $new; + } + + return new Request( + $changes['method'] ?? $request->getMethod(), + $uri, + $headers, + $changes['body'] ?? $request->getBody(), + $changes['version'] ?? $request->getProtocolVersion() + ); + } + + /** + * Read a line from the stream up to the maximum allowed buffer length. + * + * @param StreamInterface $stream Stream to read from + * @param int|null $maxLength Maximum buffer length + */ + public static function readLine(StreamInterface $stream, ?int $maxLength = null): string + { + $buffer = ''; + $size = 0; + + while (!$stream->eof()) { + if ('' === ($byte = $stream->read(1))) { + return $buffer; + } + $buffer .= $byte; + // Break when a new line is found or the max length - 1 is reached + if ($byte === "\n" || ++$size === $maxLength - 1) { + break; + } + } + + return $buffer; + } + + /** + * Create a new stream based on the input type. + * + * Options is an associative array that can contain the following keys: + * - metadata: Array of custom metadata. + * - size: Size of the stream. + * + * This method accepts the following `$resource` types: + * - `Psr\Http\Message\StreamInterface`: Returns the value as-is. + * - `string`: Creates a stream object that uses the given string as the contents. + * - `resource`: Creates a stream object that wraps the given PHP stream resource. + * - `Iterator`: If the provided value implements `Iterator`, then a read-only + * stream object will be created that wraps the given iterable. Each time the + * stream is read from, data from the iterator will fill a buffer and will be + * continuously called until the buffer is equal to the requested read size. + * Subsequent read calls will first read from the buffer and then call `next` + * on the underlying iterator until it is exhausted. + * - `object` with `__toString()`: If the object has the `__toString()` method, + * the object will be cast to a string and then a stream will be returned that + * uses the string value. + * - `NULL`: When `null` is passed, an empty stream object is returned. + * - `callable` When a callable is passed, a read-only stream object will be + * created that invokes the given callable. The callable is invoked with the + * number of suggested bytes to read. The callable can return any number of + * bytes, but MUST return `false` when there is no more data to return. The + * stream object that wraps the callable will invoke the callable until the + * number of requested bytes are available. Any additional bytes will be + * buffered and used in subsequent reads. + * + * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data + * @param array{size?: int, metadata?: array} $options Additional options + * + * @throws \InvalidArgumentException if the $resource arg is not valid. + */ + public static function streamFor($resource = '', array $options = []): StreamInterface + { + if (is_scalar($resource)) { + $stream = self::tryFopen('php://temp', 'r+'); + if ($resource !== '') { + fwrite($stream, (string) $resource); + fseek($stream, 0); + } + return new Stream($stream, $options); + } + + switch (gettype($resource)) { + case 'resource': + /* + * The 'php://input' is a special stream with quirks and inconsistencies. + * We avoid using that stream by reading it into php://temp + */ + + /** @var resource $resource */ + if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') { + $stream = self::tryFopen('php://temp', 'w+'); + stream_copy_to_stream($resource, $stream); + fseek($stream, 0); + $resource = $stream; + } + return new Stream($resource, $options); + case 'object': + /** @var object $resource */ + if ($resource instanceof StreamInterface) { + return $resource; + } elseif ($resource instanceof \Iterator) { + return new PumpStream(function () use ($resource) { + if (!$resource->valid()) { + return false; + } + $result = $resource->current(); + $resource->next(); + return $result; + }, $options); + } elseif (method_exists($resource, '__toString')) { + return self::streamFor((string) $resource, $options); + } + break; + case 'NULL': + return new Stream(self::tryFopen('php://temp', 'r+'), $options); + } + + if (is_callable($resource)) { + return new PumpStream($resource, $options); + } + + throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource)); + } + + /** + * Safely opens a PHP stream resource using a filename. + * + * When fopen fails, PHP normally raises a warning. This function adds an + * error handler that checks for errors and throws an exception instead. + * + * @param string $filename File to open + * @param string $mode Mode used to open the file + * + * @return resource + * + * @throws \RuntimeException if the file cannot be opened + */ + public static function tryFopen(string $filename, string $mode) + { + $ex = null; + set_error_handler(static function (int $errno, string $errstr) use ($filename, $mode, &$ex): bool { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $errstr + )); + + return true; + }); + + try { + /** @var resource $handle */ + $handle = fopen($filename, $mode); + } catch (\Throwable $e) { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $e->getMessage() + ), 0, $e); + } + + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $handle; + } + + /** + * Safely gets the contents of a given stream. + * + * When stream_get_contents fails, PHP normally raises a warning. This + * function adds an error handler that checks for errors and throws an + * exception instead. + * + * @param resource $stream + * + * @throws \RuntimeException if the stream cannot be read + */ + public static function tryGetContents($stream): string + { + $ex = null; + set_error_handler(static function (int $errno, string $errstr) use (&$ex): bool { + $ex = new \RuntimeException(sprintf( + 'Unable to read stream contents: %s', + $errstr + )); + + return true; + }); + + try { + /** @var string|false $contents */ + $contents = stream_get_contents($stream); + + if ($contents === false) { + $ex = new \RuntimeException('Unable to read stream contents'); + } + } catch (\Throwable $e) { + $ex = new \RuntimeException(sprintf( + 'Unable to read stream contents: %s', + $e->getMessage() + ), 0, $e); + } + + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $contents; + } + + /** + * Returns a UriInterface for the given value. + * + * This function accepts a string or UriInterface and returns a + * UriInterface for the given value. If the value is already a + * UriInterface, it is returned as-is. + * + * @param string|UriInterface $uri + * + * @throws \InvalidArgumentException + */ + public static function uriFor($uri): UriInterface + { + if ($uri instanceof UriInterface) { + return $uri; + } + + if (is_string($uri)) { + return new Uri($uri); + } + + throw new \InvalidArgumentException('URI must be a string or UriInterface'); + } +} diff --git a/plugins/login-oauth2/vendor/jakeasmith/http_build_url/.gitignore b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/.gitignore new file mode 100644 index 0000000..245ce84 --- /dev/null +++ b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/.gitignore @@ -0,0 +1,5 @@ +.DS_Store +.idea +build +composer.lock +vendor \ No newline at end of file diff --git a/plugins/login-oauth2/vendor/jakeasmith/http_build_url/.travis.yml b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/.travis.yml new file mode 100644 index 0000000..dea4bf1 --- /dev/null +++ b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/.travis.yml @@ -0,0 +1,13 @@ +sudo: false + +language: php +php: + - 5.3 + - 5.4 + - 5.5 + - 5.6 + - 7.0 + - 7.1 + - hhvm + +script: phpunit --coverage-text diff --git a/plugins/login-oauth2/vendor/jakeasmith/http_build_url/LICENSE b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/LICENSE new file mode 100644 index 0000000..341109b --- /dev/null +++ b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jake A. Smith + +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/plugins/login-oauth2/vendor/jakeasmith/http_build_url/composer.json b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/composer.json new file mode 100644 index 0000000..a5d83de --- /dev/null +++ b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/composer.json @@ -0,0 +1,18 @@ +{ + "name": "jakeasmith/http_build_url", + "description": "Provides functionality for http_build_url() to environments without pecl_http.", + "license": "MIT", + "authors": [ + { + "name": "Jake A. Smith", + "email": "theman@jakeasmith.com" + } + ], + "support": { + "issues": "https://github.com/jakeasmith/http_build_url/issues", + "source": "https://github.com/jakeasmith/http_build_url" + }, + "autoload": { + "files": ["src/http_build_url.php"] + } +} diff --git a/plugins/login-oauth2/vendor/jakeasmith/http_build_url/phpunit.xml.dist b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/phpunit.xml.dist new file mode 100644 index 0000000..62dfd81 --- /dev/null +++ b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/phpunit.xml.dist @@ -0,0 +1,21 @@ + + + + + ./tests + + + + + ./src + + + + + + + + \ No newline at end of file diff --git a/plugins/login-oauth2/vendor/jakeasmith/http_build_url/readme.md b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/readme.md new file mode 100644 index 0000000..cdf10f4 --- /dev/null +++ b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/readme.md @@ -0,0 +1,20 @@ +# http_build_url() for PHP + +[![Build Status](https://travis-ci.org/jakeasmith/http_build_url.png)](https://travis-ci.org/jakeasmith/http_build_url) +[![Code Climate](https://codeclimate.com/github/jakeasmith/http_build_url/badges/gpa.svg)](https://codeclimate.com/github/jakeasmith/http_build_url) +[![Latest Stable Version](https://poser.pugx.org/jakeasmith/http_build_url/v/stable.png)](https://packagist.org/packages/jakeasmith/http_build_url) +[![Total Downloads](https://poser.pugx.org/jakeasmith/http_build_url/downloads.png)](https://packagist.org/packages/jakeasmith/http_build_url) + +This simple library provides functionality for [`http_build_url()`](http://us2.php.net/manual/en/function.http-build-url.php) to environments without pecl_http. It aims to mimic the functionality of the pecl function in every way and ships with a full suite of tests that have been run against both the original function and the one in this package. + +## Installation + +The easiest way to install this library is to use [Composer](https://getcomposer.org/) from the command line. + +``` +$ composer require jakeasmith/http_build_url ^1 +``` + +## License + +This project is licensed under the MIT License - see the LICENSE file for details. diff --git a/plugins/login-oauth2/vendor/jakeasmith/http_build_url/src/http_build_url.php b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/src/http_build_url.php new file mode 100644 index 0000000..0dfdbba --- /dev/null +++ b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/src/http_build_url.php @@ -0,0 +1,174 @@ + "ftp", + "host" => "ftp.example.com", + "path" => "files/current/", + "query" => "a=c" + ), + HTTP_URL_STRIP_AUTH | HTTP_URL_JOIN_PATH | HTTP_URL_JOIN_QUERY | HTTP_URL_STRIP_FRAGMENT + ); + + $this->assertSame($expected, $actual); + } + + public function trailingSlashProvider() + { + return array( + array( + 'http://example.com', + array( + 'scheme' => 'http', + 'host' => 'example.com' + ) + ), + array( + 'http://example.com', + array( + 'scheme' => 'http', + 'host' => 'example.com', + 'path' => '' + ) + ), + array( + 'http://example.com/', + array( + 'scheme' => 'http', + 'host' => 'example.com', + 'path' => '/' + ) + ), + array( + 'http://example.com/yes', + array( + 'scheme' => 'http', + 'host' => 'example.com', + 'path' => 'yes' + ) + ), + array( + 'http://example.com/yes', + array( + 'scheme' => 'http', + 'host' => 'example.com', + 'path' => '/yes' + ) + ), + array( + 'http://example.com:81?a=b', + array( + 'scheme' => 'http', + 'host' => 'example.com', + 'query' => 'a=b', + 'port' => 81 + ) + ) + ); + } + + /** + * @dataProvider trailingSlashProvider + */ + public function testTrailingSlash($expected, $config) + { + $this->assertEquals($expected, http_build_url($config)); + } + + public function testUrlQueryArrayIsIgnored() + { + $expected = 'http://user:pass@www.example.com:8080/pub/index.php#files'; + $url = parse_url($this->full_url); + parse_str($url['query'], $url['query']); + $actual = http_build_url($url); + + $this->assertSame($expected, $actual); + } + + public function testPartsQueryArrayIsIgnored() + { + $expected = $this->full_url; + $actual = http_build_url($this->full_url, array('query' => array('foo' => 'bar'))); + + $this->assertSame($expected, $actual); + } + + public function testAcceptStrings() + { + $expected = 'http://user:pass@foobar.com:8080/pub/index.php?a=b#files'; + $actual = http_build_url($this->full_url, 'http://foobar.com:8080'); + + $this->assertSame($expected, $actual); + } + + public function testAcceptArrays() + { + $expected = 'http://user:pass@foobar.com:8080/pub/index.php?a=b#files'; + $actual = http_build_url(parse_url($this->full_url), parse_url('http://foobar.com:8080')); + + $this->assertSame($expected, $actual); + } + + public function testDefaults() + { + $expected = $this->full_url; + $actual = http_build_url($this->full_url); + + $this->assertSame($expected, $actual); + } + + public function testNewUrl() + { + $expected = parse_url($this->full_url); + http_build_url($this->full_url, null, null, $actual); + + $this->assertEquals($expected, $actual); + } + + /** + * @dataProvider queryProvider + */ + public function testJoinQuery($query, $expected) + { + $actual = http_build_url($this->full_url, array('query' => $query), HTTP_URL_JOIN_QUERY); + + $this->assertSame($expected, $actual); + } + + /** + * @dataProvider pathProvider + */ + public function testJoinPath($path, $expected) + { + $actual = http_build_url($this->full_url, array('path' => $path), HTTP_URL_JOIN_PATH); + + $this->assertSame($expected, $actual); + } + + public function testJoinPathTwo() + { + $expected = "http://site.testing.com/preview/testing/09-2013/p04/image/15.jpg"; + $actual = http_build_url( + "http://site.testing.com/preview/testing/09-2013/p04/?code=asdfghjkl", + array('path' => 'image/15.jpg'), + HTTP_URL_JOIN_PATH | HTTP_URL_STRIP_FRAGMENT | HTTP_URL_STRIP_QUERY + ); + + $this->assertSame($expected, $actual); + } + + /** + * @dataProvider bitmaskProvider + */ + public function testBitmasks($constant, $expected) + { + $actual = http_build_url($this->full_url, array(), constant($constant)); + + $this->assertSame($expected, $actual); + } + + public function pathProvider() + { + return array( + array('/donuts/brownies', 'http://user:pass@www.example.com:8080/donuts/brownies?a=b#files'), + array('chicken/wings', 'http://user:pass@www.example.com:8080/pub/chicken/wings?a=b#files'), + array('sausage/bacon/', 'http://user:pass@www.example.com:8080/pub/sausage/bacon/?a=b#files') + ); + } + + public function queryProvider() + { + return array( + array('a=c', 'http://user:pass@www.example.com:8080/pub/index.php?a=c#files'), + array('d=a', 'http://user:pass@www.example.com:8080/pub/index.php?a=b&d=a#files') + ); + } + + public function bitmaskProvider() + { + return array( + array('HTTP_URL_REPLACE', 'http://user:pass@www.example.com:8080/pub/index.php?a=b#files'), + array('HTTP_URL_JOIN_PATH', 'http://user:pass@www.example.com:8080/pub/index.php?a=b#files'), + array('HTTP_URL_JOIN_QUERY', 'http://user:pass@www.example.com:8080/pub/index.php?a=b#files'), + array('HTTP_URL_STRIP_USER', 'http://www.example.com:8080/pub/index.php?a=b#files'), + array('HTTP_URL_STRIP_PASS', 'http://user@www.example.com:8080/pub/index.php?a=b#files'), + array('HTTP_URL_STRIP_AUTH', 'http://www.example.com:8080/pub/index.php?a=b#files'), + array('HTTP_URL_STRIP_PORT', 'http://user:pass@www.example.com/pub/index.php?a=b#files'), + array('HTTP_URL_STRIP_PATH', 'http://user:pass@www.example.com:8080?a=b#files'), + array('HTTP_URL_STRIP_QUERY', 'http://user:pass@www.example.com:8080/pub/index.php#files'), + array('HTTP_URL_STRIP_FRAGMENT', 'http://user:pass@www.example.com:8080/pub/index.php?a=b'), + array('HTTP_URL_STRIP_ALL', 'http://www.example.com'), + ); + } +} diff --git a/plugins/login-oauth2/vendor/jakeasmith/http_build_url/tests/bootstrap.php b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/tests/bootstrap.php new file mode 100644 index 0000000..cf8b03e --- /dev/null +++ b/plugins/login-oauth2/vendor/jakeasmith/http_build_url/tests/bootstrap.php @@ -0,0 +1,13 @@ +=' ) ) { + class_alias( 'PHPUnit\Framework\Assert', 'PHPUnit_Framework_Assert' ); + class_alias( 'PHPUnit\Framework\TestCase', 'PHPUnit_Framework_TestCase' ); + class_alias( 'PHPUnit\Framework\Error\Error', 'PHPUnit_Framework_Error' ); + class_alias( 'PHPUnit\Framework\Error\Notice', 'PHPUnit_Framework_Error_Notice' ); + class_alias( 'PHPUnit\Framework\Error\Warning', 'PHPUnit_Framework_Error_Warning' ); +} + +// Past this point, tests will start diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/LICENSE b/plugins/login-oauth2/vendor/league/oauth2-client/LICENSE new file mode 100644 index 0000000..7dfa39b --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2020 Alex Bilbie + +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/plugins/login-oauth2/vendor/league/oauth2-client/README.md b/plugins/login-oauth2/vendor/league/oauth2-client/README.md new file mode 100644 index 0000000..f35d53e --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/README.md @@ -0,0 +1,58 @@ +# OAuth 2.0 Client + +This package provides a base for integrating with [OAuth 2.0](http://oauth.net/2/) service providers. + +[![Gitter Chat](https://img.shields.io/badge/gitter-join_chat-brightgreen.svg?style=flat-square)](https://gitter.im/thephpleague/oauth2-client) +[![Source Code](https://img.shields.io/badge/source-thephpleague/oauth2--client-blue.svg?style=flat-square)](https://github.com/thephpleague/oauth2-client) +[![Latest Version](https://img.shields.io/github/release/thephpleague/oauth2-client.svg?style=flat-square)](https://github.com/thephpleague/oauth2-client/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](https://github.com/thephpleague/oauth2-client/blob/master/LICENSE) +[![Build Status](https://img.shields.io/github/workflow/status/thephpleague/oauth2-client/CI?label=CI&logo=github&style=flat-square)](https://github.com/thephpleague/oauth2-client/actions?query=workflow%3ACI) +[![Codecov Code Coverage](https://img.shields.io/codecov/c/gh/thephpleague/oauth2-client?label=codecov&logo=codecov&style=flat-square)](https://codecov.io/gh/thephpleague/oauth2-client) +[![Total Downloads](https://img.shields.io/packagist/dt/league/oauth2-client.svg?style=flat-square)](https://packagist.org/packages/league/oauth2-client) + +--- + +The OAuth 2.0 login flow, seen commonly around the web in the form of "Connect with Facebook/Google/etc." buttons, is a common integration added to web applications, but it can be tricky and tedious to do right. To help, we've created the `league/oauth2-client` package, which provides a base for integrating with various OAuth 2.0 providers, without overburdening your application with the concerns of [RFC 6749](http://tools.ietf.org/html/rfc6749). + +This OAuth 2.0 client library will work with any OAuth 2.0 provider that conforms to the OAuth 2.0 Authorization Framework. Out-of-the-box, we provide a `GenericProvider` class to connect to any service provider that uses [Bearer tokens](http://tools.ietf.org/html/rfc6750). See our [basic usage guide](https://oauth2-client.thephpleague.com/usage/) for examples using `GenericProvider`. + +Many service providers provide additional functionality above and beyond the OAuth 2.0 specification. For this reason, you may extend and wrap this library to support additional behavior. There are already many [official](https://oauth2-client.thephpleague.com/providers/league/) and [third-party](https://oauth2-client.thephpleague.com/providers/thirdparty/) provider clients available (e.g., Facebook, GitHub, Google, Instagram, LinkedIn, etc.). If your provider isn't in the list, feel free to add it. + +This package is compliant with [PSR-1][], [PSR-2][], [PSR-4][], and [PSR-7][]. If you notice compliance oversights, please send a patch via pull request. If you're interested in contributing to this library, please take a look at our [contributing guidelines](https://github.com/thephpleague/oauth2-client/blob/master/CONTRIBUTING.md). + +## Requirements + +We support the following versions of PHP: + +* PHP 8.1 +* PHP 8.0 +* PHP 7.4 +* PHP 7.3 +* PHP 7.2 +* PHP 7.1 +* PHP 7.0 +* PHP 5.6 + +## Provider Clients + +We provide a list of [official PHP League provider clients](https://oauth2-client.thephpleague.com/providers/league/), as well as [third-party provider clients](https://oauth2-client.thephpleague.com/providers/thirdparty/). + +To build your own provider client, please refer to "[Implementing a Provider Client](https://oauth2-client.thephpleague.com/providers/implementing/)." + +## Usage + +For usage and code examples, check out our [basic usage guide](https://oauth2-client.thephpleague.com/usage/). + +## Contributing + +Please see [our contributing guidelines](https://github.com/thephpleague/oauth2-client/blob/master/CONTRIBUTING.md) for details. + +## License + +The MIT License (MIT). Please see [LICENSE](https://github.com/thephpleague/oauth2-client/blob/master/LICENSE) for more information. + + +[PSR-1]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md +[PSR-2]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md +[PSR-4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md +[PSR-7]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-7-http-message.md diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/composer.json b/plugins/login-oauth2/vendor/league/oauth2-client/composer.json new file mode 100644 index 0000000..59201f4 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/composer.json @@ -0,0 +1,58 @@ +{ + "name": "league/oauth2-client", + "description": "OAuth 2.0 Client Library", + "license": "MIT", + "config": { + "sort-packages": true + }, + "require": { + "php": "^5.6 || ^7.0 || ^8.0", + "guzzlehttp/guzzle": "^6.0 || ^7.0", + "paragonie/random_compat": "^1 || ^2 || ^9.99" + }, + "require-dev": { + "mockery/mockery": "^1.3.5", + "php-parallel-lint/php-parallel-lint": "^1.3.1", + "phpunit/phpunit": "^5.7 || ^6.0 || ^9.5", + "squizlabs/php_codesniffer": "^2.3 || ^3.0" + }, + "keywords": [ + "oauth", + "oauth2", + "authorization", + "authentication", + "idp", + "identity", + "sso", + "single sign on" + ], + "authors": [ + { + "name": "Alex Bilbie", + "email": "hello@alexbilbie.com", + "homepage": "http://www.alexbilbie.com", + "role": "Developer" + }, + { + "name": "Woody Gilk", + "homepage": "https://github.com/shadowhand", + "role": "Contributor" + } + + ], + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "League\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "extra": { + "branch-alias": { + "dev-2.x": "2.0.x-dev" + } + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/AbstractGrant.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/AbstractGrant.php new file mode 100644 index 0000000..2c0244b --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/AbstractGrant.php @@ -0,0 +1,80 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +use League\OAuth2\Client\Tool\RequiredParameterTrait; + +/** + * Represents a type of authorization grant. + * + * An authorization grant is a credential representing the resource + * owner's authorization (to access its protected resources) used by the + * client to obtain an access token. OAuth 2.0 defines four + * grant types -- authorization code, implicit, resource owner password + * credentials, and client credentials -- as well as an extensibility + * mechanism for defining additional types. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3 Authorization Grant (RFC 6749, §1.3) + */ +abstract class AbstractGrant +{ + use RequiredParameterTrait; + + /** + * Returns the name of this grant, eg. 'grant_name', which is used as the + * grant type when encoding URL query parameters. + * + * @return string + */ + abstract protected function getName(); + + /** + * Returns a list of all required request parameters. + * + * @return array + */ + abstract protected function getRequiredRequestParameters(); + + /** + * Returns this grant's name as its string representation. This allows for + * string interpolation when building URL query parameters. + * + * @return string + */ + public function __toString() + { + return $this->getName(); + } + + /** + * Prepares an access token request's parameters by checking that all + * required parameters are set, then merging with any given defaults. + * + * @param array $defaults + * @param array $options + * @return array + */ + public function prepareRequestParameters(array $defaults, array $options) + { + $defaults['grant_type'] = $this->getName(); + + $required = $this->getRequiredRequestParameters(); + $provided = array_merge($defaults, $options); + + $this->checkRequiredParameters($required, $provided); + + return $provided; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/AuthorizationCode.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/AuthorizationCode.php new file mode 100644 index 0000000..c49460c --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/AuthorizationCode.php @@ -0,0 +1,41 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents an authorization code grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3.1 Authorization Code (RFC 6749, §1.3.1) + */ +class AuthorizationCode extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'authorization_code'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return [ + 'code', + ]; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/ClientCredentials.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/ClientCredentials.php new file mode 100644 index 0000000..dc78c4f --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/ClientCredentials.php @@ -0,0 +1,39 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents a client credentials grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3.4 Client Credentials (RFC 6749, §1.3.4) + */ +class ClientCredentials extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'client_credentials'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return []; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/Exception/InvalidGrantException.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/Exception/InvalidGrantException.php new file mode 100644 index 0000000..c3c4e67 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/Exception/InvalidGrantException.php @@ -0,0 +1,26 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant\Exception; + +use InvalidArgumentException; + +/** + * Exception thrown if the grant does not extend from AbstractGrant. + * + * @see League\OAuth2\Client\Grant\AbstractGrant + */ +class InvalidGrantException extends InvalidArgumentException +{ +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/GrantFactory.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/GrantFactory.php new file mode 100644 index 0000000..71990e8 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/GrantFactory.php @@ -0,0 +1,104 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +use League\OAuth2\Client\Grant\Exception\InvalidGrantException; + +/** + * Represents a factory used when retrieving an authorization grant type. + */ +class GrantFactory +{ + /** + * @var array + */ + protected $registry = []; + + /** + * Defines a grant singleton in the registry. + * + * @param string $name + * @param AbstractGrant $grant + * @return self + */ + public function setGrant($name, AbstractGrant $grant) + { + $this->registry[$name] = $grant; + + return $this; + } + + /** + * Returns a grant singleton by name. + * + * If the grant has not be registered, a default grant will be loaded. + * + * @param string $name + * @return AbstractGrant + */ + public function getGrant($name) + { + if (empty($this->registry[$name])) { + $this->registerDefaultGrant($name); + } + + return $this->registry[$name]; + } + + /** + * Registers a default grant singleton by name. + * + * @param string $name + * @return self + */ + protected function registerDefaultGrant($name) + { + // PascalCase the grant. E.g: 'authorization_code' becomes 'AuthorizationCode' + $class = str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $name))); + $class = 'League\\OAuth2\\Client\\Grant\\' . $class; + + $this->checkGrant($class); + + return $this->setGrant($name, new $class); + } + + /** + * Determines if a variable is a valid grant. + * + * @param mixed $class + * @return boolean + */ + public function isGrant($class) + { + return is_subclass_of($class, AbstractGrant::class); + } + + /** + * Checks if a variable is a valid grant. + * + * @throws InvalidGrantException + * @param mixed $class + * @return void + */ + public function checkGrant($class) + { + if (!$this->isGrant($class)) { + throw new InvalidGrantException(sprintf( + 'Grant "%s" must extend AbstractGrant', + is_object($class) ? get_class($class) : $class + )); + } + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/Password.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/Password.php new file mode 100644 index 0000000..6543b2e --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/Password.php @@ -0,0 +1,42 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents a resource owner password credentials grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.3.3 Resource Owner Password Credentials (RFC 6749, §1.3.3) + */ +class Password extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'password'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return [ + 'username', + 'password', + ]; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/RefreshToken.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/RefreshToken.php new file mode 100644 index 0000000..8192182 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Grant/RefreshToken.php @@ -0,0 +1,41 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Grant; + +/** + * Represents a refresh token grant. + * + * @link http://tools.ietf.org/html/rfc6749#section-6 Refreshing an Access Token (RFC 6749, §6) + */ +class RefreshToken extends AbstractGrant +{ + /** + * @inheritdoc + */ + protected function getName() + { + return 'refresh_token'; + } + + /** + * @inheritdoc + */ + protected function getRequiredRequestParameters() + { + return [ + 'refresh_token', + ]; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/HttpBasicAuthOptionProvider.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/HttpBasicAuthOptionProvider.php new file mode 100644 index 0000000..3da4065 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/HttpBasicAuthOptionProvider.php @@ -0,0 +1,42 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\OptionProvider; + +use InvalidArgumentException; + +/** + * Add http basic auth into access token request options + * @link https://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +class HttpBasicAuthOptionProvider extends PostAuthOptionProvider +{ + /** + * @inheritdoc + */ + public function getAccessTokenOptions($method, array $params) + { + if (empty($params['client_id']) || empty($params['client_secret'])) { + throw new InvalidArgumentException('clientId and clientSecret are required for http basic auth'); + } + + $encodedCredentials = base64_encode(sprintf('%s:%s', $params['client_id'], $params['client_secret'])); + unset($params['client_id'], $params['client_secret']); + + $options = parent::getAccessTokenOptions($method, $params); + $options['headers']['Authorization'] = 'Basic ' . $encodedCredentials; + + return $options; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/OptionProviderInterface.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/OptionProviderInterface.php new file mode 100644 index 0000000..1126d25 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/OptionProviderInterface.php @@ -0,0 +1,30 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\OptionProvider; + +/** + * Interface for access token options provider + */ +interface OptionProviderInterface +{ + /** + * Builds request options used for requesting an access token. + * + * @param string $method + * @param array $params + * @return array + */ + public function getAccessTokenOptions($method, array $params); +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/PostAuthOptionProvider.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/PostAuthOptionProvider.php new file mode 100644 index 0000000..12d920e --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/OptionProvider/PostAuthOptionProvider.php @@ -0,0 +1,51 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\OptionProvider; + +use League\OAuth2\Client\Provider\AbstractProvider; +use League\OAuth2\Client\Tool\QueryBuilderTrait; + +/** + * Provide options for access token + */ +class PostAuthOptionProvider implements OptionProviderInterface +{ + use QueryBuilderTrait; + + /** + * @inheritdoc + */ + public function getAccessTokenOptions($method, array $params) + { + $options = ['headers' => ['content-type' => 'application/x-www-form-urlencoded']]; + + if ($method === AbstractProvider::METHOD_POST) { + $options['body'] = $this->getAccessTokenBody($params); + } + + return $options; + } + + /** + * Returns the request body for requesting an access token. + * + * @param array $params + * @return string + */ + protected function getAccessTokenBody(array $params) + { + return $this->buildQueryString($params); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/AbstractProvider.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/AbstractProvider.php new file mode 100644 index 0000000..d167999 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/AbstractProvider.php @@ -0,0 +1,843 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +use GuzzleHttp\Client as HttpClient; +use GuzzleHttp\ClientInterface as HttpClientInterface; +use GuzzleHttp\Exception\BadResponseException; +use League\OAuth2\Client\Grant\AbstractGrant; +use League\OAuth2\Client\Grant\GrantFactory; +use League\OAuth2\Client\OptionProvider\OptionProviderInterface; +use League\OAuth2\Client\OptionProvider\PostAuthOptionProvider; +use League\OAuth2\Client\Provider\Exception\IdentityProviderException; +use League\OAuth2\Client\Token\AccessToken; +use League\OAuth2\Client\Token\AccessTokenInterface; +use League\OAuth2\Client\Tool\ArrayAccessorTrait; +use League\OAuth2\Client\Tool\GuardedPropertyTrait; +use League\OAuth2\Client\Tool\QueryBuilderTrait; +use League\OAuth2\Client\Tool\RequestFactory; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; +use UnexpectedValueException; + +/** + * Represents a service provider (authorization server). + * + * @link http://tools.ietf.org/html/rfc6749#section-1.1 Roles (RFC 6749, §1.1) + */ +abstract class AbstractProvider +{ + use ArrayAccessorTrait; + use GuardedPropertyTrait; + use QueryBuilderTrait; + + /** + * @var string Key used in a token response to identify the resource owner. + */ + const ACCESS_TOKEN_RESOURCE_OWNER_ID = null; + + /** + * @var string HTTP method used to fetch access tokens. + */ + const METHOD_GET = 'GET'; + + /** + * @var string HTTP method used to fetch access tokens. + */ + const METHOD_POST = 'POST'; + + /** + * @var string + */ + protected $clientId; + + /** + * @var string + */ + protected $clientSecret; + + /** + * @var string + */ + protected $redirectUri; + + /** + * @var string + */ + protected $state; + + /** + * @var GrantFactory + */ + protected $grantFactory; + + /** + * @var RequestFactory + */ + protected $requestFactory; + + /** + * @var HttpClientInterface + */ + protected $httpClient; + + /** + * @var OptionProviderInterface + */ + protected $optionProvider; + + /** + * Constructs an OAuth 2.0 service provider. + * + * @param array $options An array of options to set on this provider. + * Options include `clientId`, `clientSecret`, `redirectUri`, and `state`. + * Individual providers may introduce more options, as needed. + * @param array $collaborators An array of collaborators that may be used to + * override this provider's default behavior. Collaborators include + * `grantFactory`, `requestFactory`, and `httpClient`. + * Individual providers may introduce more collaborators, as needed. + */ + public function __construct(array $options = [], array $collaborators = []) + { + // We'll let the GuardedPropertyTrait handle mass assignment of incoming + // options, skipping any blacklisted properties defined in the provider + $this->fillProperties($options); + + if (empty($collaborators['grantFactory'])) { + $collaborators['grantFactory'] = new GrantFactory(); + } + $this->setGrantFactory($collaborators['grantFactory']); + + if (empty($collaborators['requestFactory'])) { + $collaborators['requestFactory'] = new RequestFactory(); + } + $this->setRequestFactory($collaborators['requestFactory']); + + if (empty($collaborators['httpClient'])) { + $client_options = $this->getAllowedClientOptions($options); + + $collaborators['httpClient'] = new HttpClient( + array_intersect_key($options, array_flip($client_options)) + ); + } + $this->setHttpClient($collaborators['httpClient']); + + if (empty($collaborators['optionProvider'])) { + $collaborators['optionProvider'] = new PostAuthOptionProvider(); + } + $this->setOptionProvider($collaborators['optionProvider']); + } + + /** + * Returns the list of options that can be passed to the HttpClient + * + * @param array $options An array of options to set on this provider. + * Options include `clientId`, `clientSecret`, `redirectUri`, and `state`. + * Individual providers may introduce more options, as needed. + * @return array The options to pass to the HttpClient constructor + */ + protected function getAllowedClientOptions(array $options) + { + $client_options = ['timeout', 'proxy']; + + // Only allow turning off ssl verification if it's for a proxy + if (!empty($options['proxy'])) { + $client_options[] = 'verify'; + } + + return $client_options; + } + + /** + * Sets the grant factory instance. + * + * @param GrantFactory $factory + * @return self + */ + public function setGrantFactory(GrantFactory $factory) + { + $this->grantFactory = $factory; + + return $this; + } + + /** + * Returns the current grant factory instance. + * + * @return GrantFactory + */ + public function getGrantFactory() + { + return $this->grantFactory; + } + + /** + * Sets the request factory instance. + * + * @param RequestFactory $factory + * @return self + */ + public function setRequestFactory(RequestFactory $factory) + { + $this->requestFactory = $factory; + + return $this; + } + + /** + * Returns the request factory instance. + * + * @return RequestFactory + */ + public function getRequestFactory() + { + return $this->requestFactory; + } + + /** + * Sets the HTTP client instance. + * + * @param HttpClientInterface $client + * @return self + */ + public function setHttpClient(HttpClientInterface $client) + { + $this->httpClient = $client; + + return $this; + } + + /** + * Returns the HTTP client instance. + * + * @return HttpClientInterface + */ + public function getHttpClient() + { + return $this->httpClient; + } + + /** + * Sets the option provider instance. + * + * @param OptionProviderInterface $provider + * @return self + */ + public function setOptionProvider(OptionProviderInterface $provider) + { + $this->optionProvider = $provider; + + return $this; + } + + /** + * Returns the option provider instance. + * + * @return OptionProviderInterface + */ + public function getOptionProvider() + { + return $this->optionProvider; + } + + /** + * Returns the current value of the state parameter. + * + * This can be accessed by the redirect handler during authorization. + * + * @return string + */ + public function getState() + { + return $this->state; + } + + /** + * Returns the base URL for authorizing a client. + * + * Eg. https://oauth.service.com/authorize + * + * @return string + */ + abstract public function getBaseAuthorizationUrl(); + + /** + * Returns the base URL for requesting an access token. + * + * Eg. https://oauth.service.com/token + * + * @param array $params + * @return string + */ + abstract public function getBaseAccessTokenUrl(array $params); + + /** + * Returns the URL for requesting the resource owner's details. + * + * @param AccessToken $token + * @return string + */ + abstract public function getResourceOwnerDetailsUrl(AccessToken $token); + + /** + * Returns a new random string to use as the state parameter in an + * authorization flow. + * + * @param int $length Length of the random string to be generated. + * @return string + */ + protected function getRandomState($length = 32) + { + // Converting bytes to hex will always double length. Hence, we can reduce + // the amount of bytes by half to produce the correct length. + return bin2hex(random_bytes($length / 2)); + } + + /** + * Returns the default scopes used by this provider. + * + * This should only be the scopes that are required to request the details + * of the resource owner, rather than all the available scopes. + * + * @return array + */ + abstract protected function getDefaultScopes(); + + /** + * Returns the string that should be used to separate scopes when building + * the URL for requesting an access token. + * + * @return string Scope separator, defaults to ',' + */ + protected function getScopeSeparator() + { + return ','; + } + + /** + * Returns authorization parameters based on provided options. + * + * @param array $options + * @return array Authorization parameters + */ + protected function getAuthorizationParameters(array $options) + { + if (empty($options['state'])) { + $options['state'] = $this->getRandomState(); + } + + if (empty($options['scope'])) { + $options['scope'] = $this->getDefaultScopes(); + } + + $options += [ + 'response_type' => 'code', + 'approval_prompt' => 'auto' + ]; + + if (is_array($options['scope'])) { + $separator = $this->getScopeSeparator(); + $options['scope'] = implode($separator, $options['scope']); + } + + // Store the state as it may need to be accessed later on. + $this->state = $options['state']; + + // Business code layer might set a different redirect_uri parameter + // depending on the context, leave it as-is + if (!isset($options['redirect_uri'])) { + $options['redirect_uri'] = $this->redirectUri; + } + + $options['client_id'] = $this->clientId; + + return $options; + } + + /** + * Builds the authorization URL's query string. + * + * @param array $params Query parameters + * @return string Query string + */ + protected function getAuthorizationQuery(array $params) + { + return $this->buildQueryString($params); + } + + /** + * Builds the authorization URL. + * + * @param array $options + * @return string Authorization URL + */ + public function getAuthorizationUrl(array $options = []) + { + $base = $this->getBaseAuthorizationUrl(); + $params = $this->getAuthorizationParameters($options); + $query = $this->getAuthorizationQuery($params); + + return $this->appendQuery($base, $query); + } + + /** + * Redirects the client for authorization. + * + * @param array $options + * @param callable|null $redirectHandler + * @return mixed + */ + public function authorize( + array $options = [], + callable $redirectHandler = null + ) { + $url = $this->getAuthorizationUrl($options); + if ($redirectHandler) { + return $redirectHandler($url, $this); + } + + // @codeCoverageIgnoreStart + header('Location: ' . $url); + exit; + // @codeCoverageIgnoreEnd + } + + /** + * Appends a query string to a URL. + * + * @param string $url The URL to append the query to + * @param string $query The HTTP query string + * @return string The resulting URL + */ + protected function appendQuery($url, $query) + { + $query = trim($query, '?&'); + + if ($query) { + $glue = strstr($url, '?') === false ? '?' : '&'; + return $url . $glue . $query; + } + + return $url; + } + + /** + * Returns the method to use when requesting an access token. + * + * @return string HTTP method + */ + protected function getAccessTokenMethod() + { + return self::METHOD_POST; + } + + /** + * Returns the key used in the access token response to identify the resource owner. + * + * @return string|null Resource owner identifier key + */ + protected function getAccessTokenResourceOwnerId() + { + return static::ACCESS_TOKEN_RESOURCE_OWNER_ID; + } + + /** + * Builds the access token URL's query string. + * + * @param array $params Query parameters + * @return string Query string + */ + protected function getAccessTokenQuery(array $params) + { + return $this->buildQueryString($params); + } + + /** + * Checks that a provided grant is valid, or attempts to produce one if the + * provided grant is a string. + * + * @param AbstractGrant|string $grant + * @return AbstractGrant + */ + protected function verifyGrant($grant) + { + if (is_string($grant)) { + return $this->grantFactory->getGrant($grant); + } + + $this->grantFactory->checkGrant($grant); + return $grant; + } + + /** + * Returns the full URL to use when requesting an access token. + * + * @param array $params Query parameters + * @return string + */ + protected function getAccessTokenUrl(array $params) + { + $url = $this->getBaseAccessTokenUrl($params); + + if ($this->getAccessTokenMethod() === self::METHOD_GET) { + $query = $this->getAccessTokenQuery($params); + return $this->appendQuery($url, $query); + } + + return $url; + } + + /** + * Returns a prepared request for requesting an access token. + * + * @param array $params Query string parameters + * @return RequestInterface + */ + protected function getAccessTokenRequest(array $params) + { + $method = $this->getAccessTokenMethod(); + $url = $this->getAccessTokenUrl($params); + $options = $this->optionProvider->getAccessTokenOptions($this->getAccessTokenMethod(), $params); + + return $this->getRequest($method, $url, $options); + } + + /** + * Requests an access token using a specified grant and option set. + * + * @param mixed $grant + * @param array $options + * @throws IdentityProviderException + * @return AccessTokenInterface + */ + public function getAccessToken($grant, array $options = []) + { + $grant = $this->verifyGrant($grant); + + $params = [ + 'client_id' => $this->clientId, + 'client_secret' => $this->clientSecret, + 'redirect_uri' => $this->redirectUri, + ]; + + $params = $grant->prepareRequestParameters($params, $options); + $request = $this->getAccessTokenRequest($params); + $response = $this->getParsedResponse($request); + if (false === is_array($response)) { + throw new UnexpectedValueException( + 'Invalid response received from Authorization Server. Expected JSON.' + ); + } + $prepared = $this->prepareAccessTokenResponse($response); + $token = $this->createAccessToken($prepared, $grant); + + return $token; + } + + /** + * Returns a PSR-7 request instance that is not authenticated. + * + * @param string $method + * @param string $url + * @param array $options + * @return RequestInterface + */ + public function getRequest($method, $url, array $options = []) + { + return $this->createRequest($method, $url, null, $options); + } + + /** + * Returns an authenticated PSR-7 request instance. + * + * @param string $method + * @param string $url + * @param AccessTokenInterface|string $token + * @param array $options Any of "headers", "body", and "protocolVersion". + * @return RequestInterface + */ + public function getAuthenticatedRequest($method, $url, $token, array $options = []) + { + return $this->createRequest($method, $url, $token, $options); + } + + /** + * Creates a PSR-7 request instance. + * + * @param string $method + * @param string $url + * @param AccessTokenInterface|string|null $token + * @param array $options + * @return RequestInterface + */ + protected function createRequest($method, $url, $token, array $options) + { + $defaults = [ + 'headers' => $this->getHeaders($token), + ]; + + $options = array_merge_recursive($defaults, $options); + $factory = $this->getRequestFactory(); + + return $factory->getRequestWithOptions($method, $url, $options); + } + + /** + * Sends a request instance and returns a response instance. + * + * WARNING: This method does not attempt to catch exceptions caused by HTTP + * errors! It is recommended to wrap this method in a try/catch block. + * + * @param RequestInterface $request + * @return ResponseInterface + */ + public function getResponse(RequestInterface $request) + { + return $this->getHttpClient()->send($request); + } + + /** + * Sends a request and returns the parsed response. + * + * @param RequestInterface $request + * @throws IdentityProviderException + * @return mixed + */ + public function getParsedResponse(RequestInterface $request) + { + try { + $response = $this->getResponse($request); + } catch (BadResponseException $e) { + $response = $e->getResponse(); + } + + $parsed = $this->parseResponse($response); + + $this->checkResponse($response, $parsed); + + return $parsed; + } + + /** + * Attempts to parse a JSON response. + * + * @param string $content JSON content from response body + * @return array Parsed JSON data + * @throws UnexpectedValueException if the content could not be parsed + */ + protected function parseJson($content) + { + $content = json_decode($content, true); + + if (json_last_error() !== JSON_ERROR_NONE) { + throw new UnexpectedValueException(sprintf( + "Failed to parse JSON response: %s", + json_last_error_msg() + )); + } + + return $content; + } + + /** + * Returns the content type header of a response. + * + * @param ResponseInterface $response + * @return string Semi-colon separated join of content-type headers. + */ + protected function getContentType(ResponseInterface $response) + { + return join(';', (array) $response->getHeader('content-type')); + } + + /** + * Parses the response according to its content-type header. + * + * @throws UnexpectedValueException + * @param ResponseInterface $response + * @return array + */ + protected function parseResponse(ResponseInterface $response) + { + $content = (string) $response->getBody(); + $type = $this->getContentType($response); + + if (strpos($type, 'urlencoded') !== false) { + parse_str($content, $parsed); + return $parsed; + } + + // Attempt to parse the string as JSON regardless of content type, + // since some providers use non-standard content types. Only throw an + // exception if the JSON could not be parsed when it was expected to. + try { + return $this->parseJson($content); + } catch (UnexpectedValueException $e) { + if (strpos($type, 'json') !== false) { + throw $e; + } + + if ($response->getStatusCode() == 500) { + throw new UnexpectedValueException( + 'An OAuth server error was encountered that did not contain a JSON body', + 0, + $e + ); + } + + return $content; + } + } + + /** + * Checks a provider response for errors. + * + * @throws IdentityProviderException + * @param ResponseInterface $response + * @param array|string $data Parsed response data + * @return void + */ + abstract protected function checkResponse(ResponseInterface $response, $data); + + /** + * Prepares an parsed access token response for a grant. + * + * Custom mapping of expiration, etc should be done here. Always call the + * parent method when overloading this method. + * + * @param mixed $result + * @return array + */ + protected function prepareAccessTokenResponse(array $result) + { + if ($this->getAccessTokenResourceOwnerId() !== null) { + $result['resource_owner_id'] = $this->getValueByKey( + $result, + $this->getAccessTokenResourceOwnerId() + ); + } + return $result; + } + + /** + * Creates an access token from a response. + * + * The grant that was used to fetch the response can be used to provide + * additional context. + * + * @param array $response + * @param AbstractGrant $grant + * @return AccessTokenInterface + */ + protected function createAccessToken(array $response, AbstractGrant $grant) + { + return new AccessToken($response); + } + + /** + * Generates a resource owner object from a successful resource owner + * details request. + * + * @param array $response + * @param AccessToken $token + * @return ResourceOwnerInterface + */ + abstract protected function createResourceOwner(array $response, AccessToken $token); + + /** + * Requests and returns the resource owner of given access token. + * + * @param AccessToken $token + * @return ResourceOwnerInterface + */ + public function getResourceOwner(AccessToken $token) + { + $response = $this->fetchResourceOwnerDetails($token); + + return $this->createResourceOwner($response, $token); + } + + /** + * Requests resource owner details. + * + * @param AccessToken $token + * @return mixed + */ + protected function fetchResourceOwnerDetails(AccessToken $token) + { + $url = $this->getResourceOwnerDetailsUrl($token); + + $request = $this->getAuthenticatedRequest(self::METHOD_GET, $url, $token); + + $response = $this->getParsedResponse($request); + + if (false === is_array($response)) { + throw new UnexpectedValueException( + 'Invalid response received from Authorization Server. Expected JSON.' + ); + } + + return $response; + } + + /** + * Returns the default headers used by this provider. + * + * Typically this is used to set 'Accept' or 'Content-Type' headers. + * + * @return array + */ + protected function getDefaultHeaders() + { + return []; + } + + /** + * Returns the authorization headers used by this provider. + * + * Typically this is "Bearer" or "MAC". For more information see: + * http://tools.ietf.org/html/rfc6749#section-7.1 + * + * No default is provided, providers must overload this method to activate + * authorization headers. + * + * @param mixed|null $token Either a string or an access token instance + * @return array + */ + protected function getAuthorizationHeaders($token = null) + { + return []; + } + + /** + * Returns all headers used by this provider for a request. + * + * The request will be authenticated if an access token is provided. + * + * @param mixed|null $token object or string + * @return array + */ + public function getHeaders($token = null) + { + if ($token) { + return array_merge( + $this->getDefaultHeaders(), + $this->getAuthorizationHeaders($token) + ); + } + + return $this->getDefaultHeaders(); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/Exception/IdentityProviderException.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/Exception/IdentityProviderException.php new file mode 100644 index 0000000..52b7e03 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/Exception/IdentityProviderException.php @@ -0,0 +1,48 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider\Exception; + +/** + * Exception thrown if the provider response contains errors. + */ +class IdentityProviderException extends \Exception +{ + /** + * @var mixed + */ + protected $response; + + /** + * @param string $message + * @param int $code + * @param array|string $response The response body + */ + public function __construct($message, $code, $response) + { + $this->response = $response; + + parent::__construct($message, $code); + } + + /** + * Returns the exception's response body. + * + * @return array|string + */ + public function getResponseBody() + { + return $this->response; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/GenericProvider.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/GenericProvider.php new file mode 100644 index 0000000..74393ff --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/GenericProvider.php @@ -0,0 +1,233 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +use InvalidArgumentException; +use League\OAuth2\Client\Provider\Exception\IdentityProviderException; +use League\OAuth2\Client\Token\AccessToken; +use League\OAuth2\Client\Tool\BearerAuthorizationTrait; +use Psr\Http\Message\ResponseInterface; + +/** + * Represents a generic service provider that may be used to interact with any + * OAuth 2.0 service provider, using Bearer token authentication. + */ +class GenericProvider extends AbstractProvider +{ + use BearerAuthorizationTrait; + + /** + * @var string + */ + private $urlAuthorize; + + /** + * @var string + */ + private $urlAccessToken; + + /** + * @var string + */ + private $urlResourceOwnerDetails; + + /** + * @var string + */ + private $accessTokenMethod; + + /** + * @var string + */ + private $accessTokenResourceOwnerId; + + /** + * @var array|null + */ + private $scopes = null; + + /** + * @var string + */ + private $scopeSeparator; + + /** + * @var string + */ + private $responseError = 'error'; + + /** + * @var string + */ + private $responseCode; + + /** + * @var string + */ + private $responseResourceOwnerId = 'id'; + + /** + * @param array $options + * @param array $collaborators + */ + public function __construct(array $options = [], array $collaborators = []) + { + $this->assertRequiredOptions($options); + + $possible = $this->getConfigurableOptions(); + $configured = array_intersect_key($options, array_flip($possible)); + + foreach ($configured as $key => $value) { + $this->$key = $value; + } + + // Remove all options that are only used locally + $options = array_diff_key($options, $configured); + + parent::__construct($options, $collaborators); + } + + /** + * Returns all options that can be configured. + * + * @return array + */ + protected function getConfigurableOptions() + { + return array_merge($this->getRequiredOptions(), [ + 'accessTokenMethod', + 'accessTokenResourceOwnerId', + 'scopeSeparator', + 'responseError', + 'responseCode', + 'responseResourceOwnerId', + 'scopes', + ]); + } + + /** + * Returns all options that are required. + * + * @return array + */ + protected function getRequiredOptions() + { + return [ + 'urlAuthorize', + 'urlAccessToken', + 'urlResourceOwnerDetails', + ]; + } + + /** + * Verifies that all required options have been passed. + * + * @param array $options + * @return void + * @throws InvalidArgumentException + */ + private function assertRequiredOptions(array $options) + { + $missing = array_diff_key(array_flip($this->getRequiredOptions()), $options); + + if (!empty($missing)) { + throw new InvalidArgumentException( + 'Required options not defined: ' . implode(', ', array_keys($missing)) + ); + } + } + + /** + * @inheritdoc + */ + public function getBaseAuthorizationUrl() + { + return $this->urlAuthorize; + } + + /** + * @inheritdoc + */ + public function getBaseAccessTokenUrl(array $params) + { + return $this->urlAccessToken; + } + + /** + * @inheritdoc + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + return $this->urlResourceOwnerDetails; + } + + /** + * @inheritdoc + */ + public function getDefaultScopes() + { + return $this->scopes; + } + + /** + * @inheritdoc + */ + protected function getAccessTokenMethod() + { + return $this->accessTokenMethod ?: parent::getAccessTokenMethod(); + } + + /** + * @inheritdoc + */ + protected function getAccessTokenResourceOwnerId() + { + return $this->accessTokenResourceOwnerId ?: parent::getAccessTokenResourceOwnerId(); + } + + /** + * @inheritdoc + */ + protected function getScopeSeparator() + { + return $this->scopeSeparator ?: parent::getScopeSeparator(); + } + + /** + * @inheritdoc + */ + protected function checkResponse(ResponseInterface $response, $data) + { + if (!empty($data[$this->responseError])) { + $error = $data[$this->responseError]; + if (!is_string($error)) { + $error = var_export($error, true); + } + $code = $this->responseCode && !empty($data[$this->responseCode])? $data[$this->responseCode] : 0; + if (!is_int($code)) { + $code = intval($code); + } + throw new IdentityProviderException($error, $code, $data); + } + } + + /** + * @inheritdoc + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + return new GenericResourceOwner($response, $this->responseResourceOwnerId); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/GenericResourceOwner.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/GenericResourceOwner.php new file mode 100644 index 0000000..f876614 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/GenericResourceOwner.php @@ -0,0 +1,61 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +/** + * Represents a generic resource owner for use with the GenericProvider. + */ +class GenericResourceOwner implements ResourceOwnerInterface +{ + /** + * @var array + */ + protected $response; + + /** + * @var string + */ + protected $resourceOwnerId; + + /** + * @param array $response + * @param string $resourceOwnerId + */ + public function __construct(array $response, $resourceOwnerId) + { + $this->response = $response; + $this->resourceOwnerId = $resourceOwnerId; + } + + /** + * Returns the identifier of the authorized resource owner. + * + * @return mixed + */ + public function getId() + { + return $this->response[$this->resourceOwnerId]; + } + + /** + * Returns the raw resource owner response. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/ResourceOwnerInterface.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/ResourceOwnerInterface.php new file mode 100644 index 0000000..8284424 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Provider/ResourceOwnerInterface.php @@ -0,0 +1,36 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Provider; + +/** + * Classes implementing `ResourceOwnerInterface` may be used to represent + * the resource owner authenticated with a service provider. + */ +interface ResourceOwnerInterface +{ + /** + * Returns the identifier of the authorized resource owner. + * + * @return mixed + */ + public function getId(); + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray(); +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Token/AccessToken.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Token/AccessToken.php new file mode 100644 index 0000000..81533c3 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Token/AccessToken.php @@ -0,0 +1,243 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Token; + +use InvalidArgumentException; +use RuntimeException; + +/** + * Represents an access token. + * + * @link http://tools.ietf.org/html/rfc6749#section-1.4 Access Token (RFC 6749, §1.4) + */ +class AccessToken implements AccessTokenInterface, ResourceOwnerAccessTokenInterface +{ + /** + * @var string + */ + protected $accessToken; + + /** + * @var int + */ + protected $expires; + + /** + * @var string + */ + protected $refreshToken; + + /** + * @var string + */ + protected $resourceOwnerId; + + /** + * @var array + */ + protected $values = []; + + /** + * @var int + */ + private static $timeNow; + + /** + * Set the time now. This should only be used for testing purposes. + * + * @param int $timeNow the time in seconds since epoch + * @return void + */ + public static function setTimeNow($timeNow) + { + self::$timeNow = $timeNow; + } + + /** + * Reset the time now if it was set for test purposes. + * + * @return void + */ + public static function resetTimeNow() + { + self::$timeNow = null; + } + + /** + * @return int + */ + public function getTimeNow() + { + return self::$timeNow ? self::$timeNow : time(); + } + + /** + * Constructs an access token. + * + * @param array $options An array of options returned by the service provider + * in the access token request. The `access_token` option is required. + * @throws InvalidArgumentException if `access_token` is not provided in `$options`. + */ + public function __construct(array $options = []) + { + if (empty($options['access_token'])) { + throw new InvalidArgumentException('Required option not passed: "access_token"'); + } + + $this->accessToken = $options['access_token']; + + if (!empty($options['resource_owner_id'])) { + $this->resourceOwnerId = $options['resource_owner_id']; + } + + if (!empty($options['refresh_token'])) { + $this->refreshToken = $options['refresh_token']; + } + + // We need to know when the token expires. Show preference to + // 'expires_in' since it is defined in RFC6749 Section 5.1. + // Defer to 'expires' if it is provided instead. + if (isset($options['expires_in'])) { + if (!is_numeric($options['expires_in'])) { + throw new \InvalidArgumentException('expires_in value must be an integer'); + } + + $this->expires = $options['expires_in'] != 0 ? $this->getTimeNow() + $options['expires_in'] : 0; + } elseif (!empty($options['expires'])) { + // Some providers supply the seconds until expiration rather than + // the exact timestamp. Take a best guess at which we received. + $expires = $options['expires']; + + if (!$this->isExpirationTimestamp($expires)) { + $expires += $this->getTimeNow(); + } + + $this->expires = $expires; + } + + // Capture any additional values that might exist in the token but are + // not part of the standard response. Vendors will sometimes pass + // additional user data this way. + $this->values = array_diff_key($options, array_flip([ + 'access_token', + 'resource_owner_id', + 'refresh_token', + 'expires_in', + 'expires', + ])); + } + + /** + * Check if a value is an expiration timestamp or second value. + * + * @param integer $value + * @return bool + */ + protected function isExpirationTimestamp($value) + { + // If the given value is larger than the original OAuth 2 draft date, + // assume that it is meant to be a (possible expired) timestamp. + $oauth2InceptionDate = 1349067600; // 2012-10-01 + return ($value > $oauth2InceptionDate); + } + + /** + * @inheritdoc + */ + public function getToken() + { + return $this->accessToken; + } + + /** + * @inheritdoc + */ + public function getRefreshToken() + { + return $this->refreshToken; + } + + /** + * @inheritdoc + */ + public function getExpires() + { + return $this->expires; + } + + /** + * @inheritdoc + */ + public function getResourceOwnerId() + { + return $this->resourceOwnerId; + } + + /** + * @inheritdoc + */ + public function hasExpired() + { + $expires = $this->getExpires(); + + if (empty($expires)) { + throw new RuntimeException('"expires" is not set on the token'); + } + + return $expires < time(); + } + + /** + * @inheritdoc + */ + public function getValues() + { + return $this->values; + } + + /** + * @inheritdoc + */ + public function __toString() + { + return (string) $this->getToken(); + } + + /** + * @inheritdoc + */ + public function jsonSerialize() + { + $parameters = $this->values; + + if ($this->accessToken) { + $parameters['access_token'] = $this->accessToken; + } + + if ($this->refreshToken) { + $parameters['refresh_token'] = $this->refreshToken; + } + + if ($this->expires) { + $parameters['expires'] = $this->expires; + } + + if ($this->resourceOwnerId) { + $parameters['resource_owner_id'] = $this->resourceOwnerId; + } + + return $parameters; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Token/AccessTokenInterface.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Token/AccessTokenInterface.php new file mode 100644 index 0000000..5fd219f --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Token/AccessTokenInterface.php @@ -0,0 +1,74 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Token; + +use JsonSerializable; +use ReturnTypeWillChange; +use RuntimeException; + +interface AccessTokenInterface extends JsonSerializable +{ + /** + * Returns the access token string of this instance. + * + * @return string + */ + public function getToken(); + + /** + * Returns the refresh token, if defined. + * + * @return string|null + */ + public function getRefreshToken(); + + /** + * Returns the expiration timestamp in seconds, if defined. + * + * @return integer|null + */ + public function getExpires(); + + /** + * Checks if this token has expired. + * + * @return boolean true if the token has expired, false otherwise. + * @throws RuntimeException if 'expires' is not set on the token. + */ + public function hasExpired(); + + /** + * Returns additional vendor values stored in the token. + * + * @return array + */ + public function getValues(); + + /** + * Returns a string representation of the access token + * + * @return string + */ + public function __toString(); + + /** + * Returns an array of parameters to serialize when this is serialized with + * json_encode(). + * + * @return array + */ + #[ReturnTypeWillChange] + public function jsonSerialize(); +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Token/ResourceOwnerAccessTokenInterface.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Token/ResourceOwnerAccessTokenInterface.php new file mode 100644 index 0000000..51e4ce4 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Token/ResourceOwnerAccessTokenInterface.php @@ -0,0 +1,25 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Token; + +interface ResourceOwnerAccessTokenInterface extends AccessTokenInterface +{ + /** + * Returns the resource owner identifier, if defined. + * + * @return string|null + */ + public function getResourceOwnerId(); +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/ArrayAccessorTrait.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/ArrayAccessorTrait.php new file mode 100644 index 0000000..a18198c --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/ArrayAccessorTrait.php @@ -0,0 +1,52 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +/** + * Provides generic array navigation tools. + */ +trait ArrayAccessorTrait +{ + /** + * Returns a value by key using dot notation. + * + * @param array $data + * @param string $key + * @param mixed|null $default + * @return mixed + */ + private function getValueByKey(array $data, $key, $default = null) + { + if (!is_string($key) || empty($key) || !count($data)) { + return $default; + } + + if (strpos($key, '.') !== false) { + $keys = explode('.', $key); + + foreach ($keys as $innerKey) { + if (!is_array($data) || !array_key_exists($innerKey, $data)) { + return $default; + } + + $data = $data[$innerKey]; + } + + return $data; + } + + return array_key_exists($key, $data) ? $data[$key] : $default; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/BearerAuthorizationTrait.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/BearerAuthorizationTrait.php new file mode 100644 index 0000000..081c7c8 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/BearerAuthorizationTrait.php @@ -0,0 +1,36 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use League\OAuth2\Client\Token\AccessTokenInterface; + +/** + * Enables `Bearer` header authorization for providers. + * + * @link http://tools.ietf.org/html/rfc6750 Bearer Token Usage (RFC 6750) + */ +trait BearerAuthorizationTrait +{ + /** + * Returns authorization headers for the 'bearer' grant. + * + * @param AccessTokenInterface|string|null $token Either a string or an access token instance + * @return array + */ + protected function getAuthorizationHeaders($token = null) + { + return ['Authorization' => 'Bearer ' . $token]; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/GuardedPropertyTrait.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/GuardedPropertyTrait.php new file mode 100644 index 0000000..02c9ba5 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/GuardedPropertyTrait.php @@ -0,0 +1,70 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +/** + * Provides support for blacklisting explicit properties from the + * mass assignment behavior. + */ +trait GuardedPropertyTrait +{ + /** + * The properties that aren't mass assignable. + * + * @var array + */ + protected $guarded = []; + + /** + * Attempts to mass assign the given options to explicitly defined properties, + * skipping over any properties that are defined in the guarded array. + * + * @param array $options + * @return mixed + */ + protected function fillProperties(array $options = []) + { + if (isset($options['guarded'])) { + unset($options['guarded']); + } + + foreach ($options as $option => $value) { + if (property_exists($this, $option) && !$this->isGuarded($option)) { + $this->{$option} = $value; + } + } + } + + /** + * Returns current guarded properties. + * + * @return array + */ + public function getGuarded() + { + return $this->guarded; + } + + /** + * Determines if the given property is guarded. + * + * @param string $property + * @return bool + */ + public function isGuarded($property) + { + return in_array($property, $this->getGuarded()); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/MacAuthorizationTrait.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/MacAuthorizationTrait.php new file mode 100644 index 0000000..f8dcd77 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/MacAuthorizationTrait.php @@ -0,0 +1,83 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use League\OAuth2\Client\Token\AccessToken; +use League\OAuth2\Client\Token\AccessTokenInterface; + +/** + * Enables `MAC` header authorization for providers. + * + * @link http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05 Message Authentication Code (MAC) Tokens + */ +trait MacAuthorizationTrait +{ + /** + * Returns the id of this token for MAC generation. + * + * @param AccessToken $token + * @return string + */ + abstract protected function getTokenId(AccessToken $token); + + /** + * Returns the MAC signature for the current request. + * + * @param string $id + * @param integer $ts + * @param string $nonce + * @return string + */ + abstract protected function getMacSignature($id, $ts, $nonce); + + /** + * Returns a new random string to use as the state parameter in an + * authorization flow. + * + * @param int $length Length of the random string to be generated. + * @return string + */ + abstract protected function getRandomState($length = 32); + + /** + * Returns the authorization headers for the 'mac' grant. + * + * @param AccessTokenInterface|string|null $token Either a string or an access token instance + * @return array + * @codeCoverageIgnore + * + * @todo This is currently untested and provided only as an example. If you + * complete the implementation, please create a pull request for + * https://github.com/thephpleague/oauth2-client + */ + protected function getAuthorizationHeaders($token = null) + { + if ($token === null) { + return []; + } + + $ts = time(); + $id = $this->getTokenId($token); + $nonce = $this->getRandomState(16); + $mac = $this->getMacSignature($id, $ts, $nonce); + + $parts = []; + foreach (compact('id', 'ts', 'nonce', 'mac') as $key => $value) { + $parts[] = sprintf('%s="%s"', $key, $value); + } + + return ['Authorization' => 'MAC ' . implode(', ', $parts)]; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php new file mode 100644 index 0000000..f81b511 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/ProviderRedirectTrait.php @@ -0,0 +1,122 @@ +redirectLimit) { + $attempts++; + $response = $this->getHttpClient()->send($request, [ + 'allow_redirects' => false + ]); + + if ($this->isRedirect($response)) { + $redirectUrl = new Uri($response->getHeader('Location')[0]); + $request = $request->withUri($redirectUrl); + } else { + break; + } + } + + return $response; + } + + /** + * Returns the HTTP client instance. + * + * @return GuzzleHttp\ClientInterface + */ + abstract public function getHttpClient(); + + /** + * Retrieves current redirect limit. + * + * @return integer + */ + public function getRedirectLimit() + { + return $this->redirectLimit; + } + + /** + * Determines if a given response is a redirect. + * + * @param ResponseInterface $response + * + * @return boolean + */ + protected function isRedirect(ResponseInterface $response) + { + $statusCode = $response->getStatusCode(); + + return $statusCode > 300 && $statusCode < 400 && $response->hasHeader('Location'); + } + + /** + * Sends a request instance and returns a response instance. + * + * WARNING: This method does not attempt to catch exceptions caused by HTTP + * errors! It is recommended to wrap this method in a try/catch block. + * + * @param RequestInterface $request + * @return ResponseInterface + */ + public function getResponse(RequestInterface $request) + { + try { + $response = $this->followRequestRedirects($request); + } catch (BadResponseException $e) { + $response = $e->getResponse(); + } + + return $response; + } + + /** + * Updates the redirect limit. + * + * @param integer $limit + * @return League\OAuth2\Client\Provider\AbstractProvider + * @throws InvalidArgumentException + */ + public function setRedirectLimit($limit) + { + if (!is_int($limit)) { + throw new InvalidArgumentException('redirectLimit must be an integer.'); + } + + if ($limit < 1) { + throw new InvalidArgumentException('redirectLimit must be greater than or equal to one.'); + } + + $this->redirectLimit = $limit; + + return $this; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/QueryBuilderTrait.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/QueryBuilderTrait.php new file mode 100644 index 0000000..bdda3e7 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/QueryBuilderTrait.php @@ -0,0 +1,33 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +/** + * Provides a standard way to generate query strings. + */ +trait QueryBuilderTrait +{ + /** + * Build a query string from an array. + * + * @param array $params + * + * @return string + */ + protected function buildQueryString(array $params) + { + return http_build_query($params, '', '&', \PHP_QUERY_RFC3986); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/RequestFactory.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/RequestFactory.php new file mode 100644 index 0000000..1af4342 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/RequestFactory.php @@ -0,0 +1,87 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use GuzzleHttp\Psr7\Request; + +/** + * Used to produce PSR-7 Request instances. + * + * @link https://github.com/guzzle/guzzle/pull/1101 + */ +class RequestFactory +{ + /** + * Creates a PSR-7 Request instance. + * + * @param null|string $method HTTP method for the request. + * @param null|string $uri URI for the request. + * @param array $headers Headers for the message. + * @param string|resource|StreamInterface $body Message body. + * @param string $version HTTP protocol version. + * + * @return Request + */ + public function getRequest( + $method, + $uri, + array $headers = [], + $body = null, + $version = '1.1' + ) { + return new Request($method, $uri, $headers, $body, $version); + } + + /** + * Parses simplified options. + * + * @param array $options Simplified options. + * + * @return array Extended options for use with getRequest. + */ + protected function parseOptions(array $options) + { + // Should match default values for getRequest + $defaults = [ + 'headers' => [], + 'body' => null, + 'version' => '1.1', + ]; + + return array_merge($defaults, $options); + } + + /** + * Creates a request using a simplified array of options. + * + * @param null|string $method + * @param null|string $uri + * @param array $options + * + * @return Request + */ + public function getRequestWithOptions($method, $uri, array $options = []) + { + $options = $this->parseOptions($options); + + return $this->getRequest( + $method, + $uri, + $options['headers'], + $options['body'], + $options['version'] + ); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/RequiredParameterTrait.php b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/RequiredParameterTrait.php new file mode 100644 index 0000000..47da977 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-client/src/Tool/RequiredParameterTrait.php @@ -0,0 +1,56 @@ + + * @license http://opensource.org/licenses/MIT MIT + * @link http://thephpleague.com/oauth2-client/ Documentation + * @link https://packagist.org/packages/league/oauth2-client Packagist + * @link https://github.com/thephpleague/oauth2-client GitHub + */ + +namespace League\OAuth2\Client\Tool; + +use BadMethodCallException; + +/** + * Provides functionality to check for required parameters. + */ +trait RequiredParameterTrait +{ + /** + * Checks for a required parameter in a hash. + * + * @throws BadMethodCallException + * @param string $name + * @param array $params + * @return void + */ + private function checkRequiredParameter($name, array $params) + { + if (!isset($params[$name])) { + throw new BadMethodCallException(sprintf( + 'Required parameter not passed: "%s"', + $name + )); + } + } + + /** + * Checks for multiple required parameters in a hash. + * + * @throws InvalidArgumentException + * @param array $names + * @param array $params + * @return void + */ + private function checkRequiredParameters(array $names, array $params) + { + foreach ($names as $name) { + $this->checkRequiredParameter($name, $params); + } + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-facebook/.github/workflows/ci.yaml b/plugins/login-oauth2/vendor/league/oauth2-facebook/.github/workflows/ci.yaml new file mode 100644 index 0000000..9524f8f --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-facebook/.github/workflows/ci.yaml @@ -0,0 +1,56 @@ +name: CI + +on: + pull_request: + push: + branches: [ master ] + +jobs: + run: + runs-on: ubuntu-18.04 + strategy: + fail-fast: false + matrix: + php: + - '7.3' + - '7.4' + - '8.0' + coverage: ['none'] + include: + - description: 'Log Code Coverage' + php: '8.0' + coverage: 'xdebug' + + name: PHP ${{ matrix.php }} ${{ matrix.description }} + steps: + - name: Checkout + uses: actions/checkout@v2 + + - uses: actions/cache@v2 + with: + path: ~/.composer/cache/files + key: ${{ matrix.php }} + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: ${{ matrix.coverage }} + + - name: Install dependencies + run: composer install + + - name: Run PHPUnit tests + run: vendor/bin/phpunit + if: matrix.coverage == 'none' + + - name: PHPUnit tests and Log Code coverage + run: vendor/bin/phpunit --exclude-group proxy --coverage-clover=coverage.xml + if: matrix.coverage == 'xdebug' + + - name: Run codecov + uses: codecov/codecov-action@v1 + if: matrix.coverage == 'xdebug' + with: + file: './coverage.xml' + fail_ci_if_error: true diff --git a/plugins/login-oauth2/vendor/league/oauth2-facebook/.github/workflows/static-analysis.yaml b/plugins/login-oauth2/vendor/league/oauth2-facebook/.github/workflows/static-analysis.yaml new file mode 100644 index 0000000..a607877 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-facebook/.github/workflows/static-analysis.yaml @@ -0,0 +1,23 @@ +name: Code style + +on: + pull_request: + push: + branches: [ master ] + +jobs: + php-cs-fixer: + name: PHP-CodeSniffer + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + + - name: Install dependencies + run: composer install + + - name: Run script + run: ./vendor/bin/phpcs src --standard=psr12 -sp diff --git a/plugins/login-oauth2/vendor/league/oauth2-facebook/LICENSE b/plugins/login-oauth2/vendor/league/oauth2-facebook/LICENSE new file mode 100644 index 0000000..dd7005d --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-facebook/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Sammy Kaye Powers + +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/plugins/login-oauth2/vendor/league/oauth2-facebook/composer.json b/plugins/login-oauth2/vendor/league/oauth2-facebook/composer.json new file mode 100644 index 0000000..6bdf654 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-facebook/composer.json @@ -0,0 +1,40 @@ +{ + "name": "league/oauth2-facebook", + "description": "Facebook OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Sammy Kaye Powers", + "email": "me@sammyk.me", + "homepage": "http://www.sammyk.me" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authentication", + "facebook" + ], + "require": { + "php": ">=7.3", + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "ext-json": "*", + "phpunit/phpunit": "^9.4", + "mockery/mockery": "~1.3.0", + "squizlabs/php_codesniffer": "~3.0" + }, + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "League\\OAuth2\\Client\\Test\\": "tests/src/" + } + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-facebook/src/Grant/FbExchangeToken.php b/plugins/login-oauth2/vendor/league/oauth2-facebook/src/Grant/FbExchangeToken.php new file mode 100644 index 0000000..717ff11 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-facebook/src/Grant/FbExchangeToken.php @@ -0,0 +1,23 @@ +graphApiVersion = $options['graphApiVersion']; + + if (!empty($options['enableBetaTier']) && $options['enableBetaTier'] === true) { + $this->enableBetaMode = true; + } + + if (!empty($options['fields']) && is_array($options['fields'])) { + $this->fields = $options['fields']; + } else { + $this->fields = [ + 'id', 'name', 'first_name', 'last_name', + 'email', 'hometown', 'picture.type(large){url,is_silhouette}', + 'gender', 'age_range' + ]; + + // backwards compatibility less than 2.8 + if (version_compare(substr($this->graphApiVersion, 1), '2.8') < 0) { + $this->fields[] = 'bio'; + } + } + } + + public function getBaseAuthorizationUrl(): string + { + return $this->getBaseFacebookUrl() . $this->graphApiVersion . '/dialog/oauth'; + } + + public function getBaseAccessTokenUrl(array $params): string + { + return $this->getBaseGraphUrl() . $this->graphApiVersion . '/oauth/access_token'; + } + + public function getDefaultScopes(): array + { + return ['public_profile', 'email']; + } + + public function getResourceOwnerDetailsUrl(AccessToken $token): string + { + $appSecretProof = AppSecretProof::create($this->clientSecret, $token->getToken()); + + return $this->getBaseGraphUrl() + . $this->graphApiVersion + . '/me?fields=' . implode(',', $this->fields) + . '&access_token=' . $token . '&appsecret_proof=' . $appSecretProof; + } + + public function getAccessToken($grant = 'authorization_code', array $params = []): AccessTokenInterface + { + if (isset($params['refresh_token'])) { + throw new FacebookProviderException('Facebook does not support token refreshing.'); + } + + return parent::getAccessToken($grant, $params); + } + + /** + * Exchanges a short-lived access token with a long-lived access-token. + */ + public function getLongLivedAccessToken(string $accessToken): AccessTokenInterface + { + $params = [ + 'fb_exchange_token' => $accessToken, + ]; + + return $this->getAccessToken('fb_exchange_token', $params); + } + + protected function createResourceOwner(array $response, AccessToken $token): FacebookUser + { + return new FacebookUser($response); + } + + protected function checkResponse(ResponseInterface $response, $data): void + { + if (empty($data['error'])) { + return; + } + + $message = $data['error']['type'] . ': ' . $data['error']['message']; + throw new IdentityProviderException($message, $data['error']['code'], $data); + } + + /** + * @inheritdoc + */ + protected function getContentType(ResponseInterface $response): string + { + $type = parent::getContentType($response); + + // Fix for Facebook's pseudo-JSONP support + if (strpos($type, 'javascript') !== false) { + return 'application/json'; + } + + // Fix for Facebook's pseudo-urlencoded support + if (strpos($type, 'plain') !== false) { + return 'application/x-www-form-urlencoded'; + } + + return $type; + } + + /** + * Get the base Facebook URL. + */ + protected function getBaseFacebookUrl(): string + { + return $this->enableBetaMode ? static::BASE_FACEBOOK_URL_BETA : static::BASE_FACEBOOK_URL; + } + + /** + * Get the base Graph API URL. + */ + protected function getBaseGraphUrl(): string + { + return $this->enableBetaMode ? static::BASE_GRAPH_URL_BETA : static::BASE_GRAPH_URL; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-facebook/src/Provider/FacebookUser.php b/plugins/login-oauth2/vendor/league/oauth2-facebook/src/Provider/FacebookUser.php new file mode 100644 index 0000000..b49c4ea --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-facebook/src/Provider/FacebookUser.php @@ -0,0 +1,216 @@ +data = $response; + + if (!empty($response['picture']['data']['url'])) { + $this->data['picture_url'] = $response['picture']['data']['url']; + } + + if (isset($response['picture']['data']['is_silhouette'])) { + $this->data['is_silhouette'] = $response['picture']['data']['is_silhouette']; + } + + if (!empty($response['cover']['source'])) { + $this->data['cover_photo_url'] = $response['cover']['source']; + } + } + + /** + * Returns the ID for the user as a string if present. + * + * @return string|null + */ + public function getId(): ?string + { + return $this->getField('id'); + } + + /** + * Returns the name for the user as a string if present. + * + * @return string|null + */ + public function getName(): ?string + { + return $this->getField('name'); + } + + /** + * Returns the first name for the user as a string if present. + * + * @return string|null + */ + public function getFirstName(): ?string + { + return $this->getField('first_name'); + } + + /** + * Returns the last name for the user as a string if present. + * + * @return string|null + */ + public function getLastName(): ?string + { + return $this->getField('last_name'); + } + + /** + * Returns the email for the user as a string if present. + * + * @return string|null + */ + public function getEmail(): ?string + { + return $this->getField('email'); + } + + /** + * Returns the current location of the user as an array. + * + * @return array|null + */ + public function getHometown(): ?array + { + return $this->getField('hometown'); + } + + /** + * Returns the "about me" bio for the user as a string if present. + * + * @return string|null + * @deprecated The bio field was removed in Graph v2.8 + */ + public function getBio(): ?string + { + return $this->getField('bio'); + } + + /** + * Returns if user has not defined a specific avatar + * + * @return boolean + */ + + public function isDefaultPicture(): bool + { + return $this->getField('is_silhouette'); + } + + /** + * Returns the profile picture of the user as a string if present. + * + * @return string|null + */ + public function getPictureUrl(): ?string + { + return $this->getField('picture_url'); + } + + /** + * Returns the cover photo URL of the user as a string if present. + * + * @return string|null + * @deprecated + */ + public function getCoverPhotoUrl(): ?string + { + return $this->getField('cover_photo_url'); + } + + /** + * Returns the gender for the user as a string if present. + * + * @return string|null + */ + public function getGender(): ?string + { + return $this->getField('gender'); + } + + /** + * Returns the locale of the user as a string if available. + * + * @return string|null + * @deprecated + */ + public function getLocale(): ?string + { + return $this->getField('locale'); + } + + /** + * Returns the Facebook URL for the user as a string if available. + * + * @return string|null + */ + public function getLink(): ?string + { + return $this->getField('link'); + } + + /** + * Returns the current timezone offset from UTC (from -24 to 24) + * + * @return float|null + * @deprecated + */ + public function getTimezone(): ?float + { + return $this->getField('timezone'); + } + + /** + * Returns the lower bound of the user's age range + * + * @return integer|null + */ + public function getMinAge(): ?int + { + return $this->data['age_range']['min'] ?? null; + } + + /** + * Returns the upper bound of the user's age range + * + * @return integer|null + */ + public function getMaxAge(): ?int + { + return $this->data['age_range']['max'] ?? null; + } + + /** + * Returns all the data obtained about the user. + * + * @return array + */ + public function toArray(): array + { + return $this->data; + } + + /** + * Returns a field from the Graph node data. + * + * @return mixed|null + */ + private function getField(string $key) + { + return $this->data[$key] ?? null; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/.gitignore b/plugins/login-oauth2/vendor/league/oauth2-github/.gitignore new file mode 100644 index 0000000..9c9c8f2 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/.gitignore @@ -0,0 +1,5 @@ +/build +/vendor +composer.phar +composer.lock +.DS_Store diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/.scrutinizer.yml b/plugins/login-oauth2/vendor/league/oauth2-github/.scrutinizer.yml new file mode 100644 index 0000000..d585107 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/.scrutinizer.yml @@ -0,0 +1,35 @@ +filter: + excluded_paths: [test/*] +checks: + php: + code_rating: true + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true +tools: + external_code_coverage: + timeout: 600 + runs: 3 + php_analyzer: true + php_code_coverage: false + php_code_sniffer: + config: + standard: PSR2 + filter: + paths: ['src'] + php_loc: + enabled: true + excluded_dirs: [vendor, test] + php_cpd: + enabled: true + excluded_dirs: [vendor, test] diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/.travis.yml b/plugins/login-oauth2/vendor/league/oauth2-github/.travis.yml new file mode 100644 index 0000000..d99d282 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/.travis.yml @@ -0,0 +1,27 @@ +language: php + +sudo: false + +php: + - 5.6 + - 7.0 + - 7.1 + - hhvm + +matrix: + include: + - php: 5.6 + env: 'COMPOSER_FLAGS="--prefer-stable --prefer-lowest"' + +before_script: + - travis_retry composer self-update + - travis_retry composer install --no-interaction --prefer-source --dev + - travis_retry phpenv rehash + +script: + - ./vendor/bin/phpcs --standard=psr2 src/ + - ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover + +after_script: + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover coverage.clover diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/CHANGELOG.md b/plugins/login-oauth2/vendor/league/oauth2-github/CHANGELOG.md new file mode 100644 index 0000000..68ae784 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/CHANGELOG.md @@ -0,0 +1,92 @@ +# Changelog +All Notable changes to `oauth2-github` will be documented in this file + +## 2.0.0 - 2017-01-25 + +### Added +- PHP 7.1 Support + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- PHP 5.5 Support + +### Security +- Nothing + +## 1.0.0 - 2017-01-25 + +Bump for base package parity + +## 0.2.2 - 2016-11-21 + +### Added +- Update base package version from 1.0 to 1.4 +- Update GithubResourceOwner to utilize ArrayAccessorTrait from base package + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.2.1 - 2016-04-13 + +### Added +- Support OAuth exceptions from Github with non-standard status codes (https://developer.github.com/v3/oauth/#common-errors-for-the-access-token-request) + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.2.0 - 2015-08-20 + +### Added +- Upgrade to support version 1.0 release of core client + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.1.0 - 2015-04-13 + +### Added +- Initial release! + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/CONTRIBUTING.md b/plugins/login-oauth2/vendor/league/oauth2-github/CONTRIBUTING.md new file mode 100644 index 0000000..06745a0 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/thephpleague/oauth2-github). + + +## Pull Requests + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow SemVer. Randomly breaking public APIs is not an option. + +- **Create topic branches** - Don't ask us to pull from your master branch. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. + +- **Ensure tests pass!** - Please run the tests (see below) before submitting your pull request, and make sure they pass. We won't accept a patch until all tests pass. + +- **Ensure no coding standards violations** - Please run PHP Code Sniffer using the PSR-2 standard (see below) before submitting your pull request. A violation will cause the build to fail, so please make sure there are no violations. We can't accept a patch if the build fails. + + +## Running Tests + +``` bash +$ ./vendor/bin/phpunit +``` + + +## Running PHP Code Sniffer + +``` bash +$ ./vendor/bin/phpcs src --standard=psr2 -sp +``` + +**Happy coding**! diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/LICENSE b/plugins/login-oauth2/vendor/league/oauth2-github/LICENSE new file mode 100644 index 0000000..51455e2 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Steven Maguire + +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/plugins/login-oauth2/vendor/league/oauth2-github/README.md b/plugins/login-oauth2/vendor/league/oauth2-github/README.md new file mode 100644 index 0000000..2fc3a59 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/README.md @@ -0,0 +1,129 @@ +# Github Provider for OAuth 2.0 Client +[![Latest Version](https://img.shields.io/github/release/thephpleague/oauth2-github.svg?style=flat-square)](https://github.com/thephpleague/oauth2-github/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/thephpleague/oauth2-github/master.svg?style=flat-square)](https://travis-ci.org/thephpleague/oauth2-github) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/oauth2-github.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/oauth2-github/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/oauth2-github.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/oauth2-github) +[![Total Downloads](https://img.shields.io/packagist/dt/league/oauth2-github.svg?style=flat-square)](https://packagist.org/packages/league/oauth2-github) + +This package provides Github OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +## Installation + +To install, use composer: + +``` +composer require league/oauth2-github +``` + +## Usage + +Usage is the same as The League's OAuth client, using `\League\OAuth2\Client\Provider\Github` as the provider. + +### Authorization Code Flow + +```php +$provider = new League\OAuth2\Client\Provider\Github([ + 'clientId' => '{github-client-id}', + 'clientSecret' => '{github-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', +]); + +if (!isset($_GET['code'])) { + + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: '.$authUrl); + exit; + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + unset($_SESSION['oauth2state']); + exit('Invalid state'); + +} else { + + // Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the user's details + $user = $provider->getResourceOwner($token); + + // Use these details to create a new profile + printf('Hello %s!', $user->getNickname()); + + } catch (Exception $e) { + + // Failed to get user details + exit('Oh dear...'); + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); +} +``` + +### Managing Scopes + +When creating your Github authorization URL, you can specify the state and scopes your application may authorize. + +```php +$options = [ + 'state' => 'OPTIONAL_CUSTOM_CONFIGURED_STATE', + 'scope' => ['user','user:email','repo'] // array or string +]; + +$authorizationUrl = $provider->getAuthorizationUrl($options); +``` +If neither are defined, the provider will utilize internal defaults. + +At the time of authoring this documentation, the [following scopes are available](https://developer.github.com/v3/oauth/#scopes). + +- user +- user:email +- user:follow +- public_repo +- repo +- repo_deployment +- repo:status +- delete_repo +- notifications +- gist +- read:repo_hook +- write:repo_hook +- admin:repo_hook +- admin:org_hook +- read:org +- write:org +- admin:org +- read:public_key +- write:public_key +- admin:public_key + +## Testing + +``` bash +$ ./vendor/bin/phpunit +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/thephpleague/oauth2-github/blob/master/CONTRIBUTING.md) for details. + + +## Credits + +- [Steven Maguire](https://github.com/stevenmaguire) +- [All Contributors](https://github.com/thephpleague/oauth2-github/contributors) + + +## License + +The MIT License (MIT). Please see [License File](https://github.com/thephpleague/oauth2-github/blob/master/LICENSE) for more information. diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/composer.json b/plugins/login-oauth2/vendor/league/oauth2-github/composer.json new file mode 100644 index 0000000..f88f66b --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/composer.json @@ -0,0 +1,43 @@ +{ + "name": "league/oauth2-github", + "description": "Github OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authorisation", + "github" + ], + "require": { + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0", + "mockery/mockery": "~0.9", + "squizlabs/php_codesniffer": "~2.0" + }, + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "League\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/phpunit.xml b/plugins/login-oauth2/vendor/league/oauth2-github/phpunit.xml new file mode 100644 index 0000000..1819eb0 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/phpunit.xml @@ -0,0 +1,37 @@ + + + + + + + + + ./test/ + + + + + ./ + + ./vendor + ./test + + + + diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/Exception/GithubIdentityProviderException.php b/plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/Exception/GithubIdentityProviderException.php new file mode 100644 index 0000000..bb30ace --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/Exception/GithubIdentityProviderException.php @@ -0,0 +1,53 @@ +getReasonPhrase() + ); + } + + /** + * Creates oauth exception from response. + * + * @param ResponseInterface $response + * @param string $data Parsed response data + * + * @return IdentityProviderException + */ + public static function oauthException(ResponseInterface $response, $data) + { + return static::fromResponse( + $response, + isset($data['error']) ? $data['error'] : $response->getReasonPhrase() + ); + } + + /** + * Creates identity exception from response. + * + * @param ResponseInterface $response + * @param string $message + * + * @return IdentityProviderException + */ + protected static function fromResponse(ResponseInterface $response, $message = null) + { + return new static($message, $response->getStatusCode(), (string) $response->getBody()); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/Github.php b/plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/Github.php new file mode 100644 index 0000000..9946adf --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/Github.php @@ -0,0 +1,110 @@ +domain.'/login/oauth/authorize'; + } + + /** + * Get access token url to retrieve token + * + * @param array $params + * + * @return string + */ + public function getBaseAccessTokenUrl(array $params) + { + return $this->domain.'/login/oauth/access_token'; + } + + /** + * Get provider url to fetch user details + * + * @param AccessToken $token + * + * @return string + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + if ($this->domain === 'https://github.com') { + return $this->apiDomain.'/user'; + } + return $this->domain.'/api/v3/user'; + } + + /** + * Get the default scopes used by this provider. + * + * This should not be a complete list of all scopes, but the minimum + * required for the provider user interface! + * + * @return array + */ + protected function getDefaultScopes() + { + return []; + } + + /** + * Check a provider response for errors. + * + * @link https://developer.github.com/v3/#client-errors + * @link https://developer.github.com/v3/oauth/#common-errors-for-the-access-token-request + * @throws IdentityProviderException + * @param ResponseInterface $response + * @param string $data Parsed response data + * @return void + */ + protected function checkResponse(ResponseInterface $response, $data) + { + if ($response->getStatusCode() >= 400) { + throw GithubIdentityProviderException::clientException($response, $data); + } elseif (isset($data['error'])) { + throw GithubIdentityProviderException::oauthException($response, $data); + } + } + + /** + * Generate a user object from a successful user details request. + * + * @param array $response + * @param AccessToken $token + * @return League\OAuth2\Client\Provider\ResourceOwnerInterface + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + $user = new GithubResourceOwner($response); + + return $user->setDomain($this->domain); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/GithubResourceOwner.php b/plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/GithubResourceOwner.php new file mode 100644 index 0000000..712e496 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/src/Provider/GithubResourceOwner.php @@ -0,0 +1,108 @@ +response = $response; + } + + /** + * Get resource owner id + * + * @return string|null + */ + public function getId() + { + return $this->getValueByKey($this->response, 'id'); + } + + /** + * Get resource owner email + * + * @return string|null + */ + public function getEmail() + { + return $this->getValueByKey($this->response, 'email'); + } + + /** + * Get resource owner name + * + * @return string|null + */ + public function getName() + { + return $this->getValueByKey($this->response, 'name'); + } + + /** + * Get resource owner nickname + * + * @return string|null + */ + public function getNickname() + { + return $this->getValueByKey($this->response, 'login'); + } + + /** + * Get resource owner url + * + * @return string|null + */ + public function getUrl() + { + $urlParts = array_filter([$this->domain, $this->getNickname()]); + + return count($urlParts) ? implode('/', $urlParts) : null; + } + + /** + * Set resource owner domain + * + * @param string $domain + * + * @return ResourceOwner + */ + public function setDomain($domain) + { + $this->domain = $domain; + + return $this; + } + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/test/src/Provider/GithubResourceOwnerTest.php b/plugins/login-oauth2/vendor/league/oauth2-github/test/src/Provider/GithubResourceOwnerTest.php new file mode 100644 index 0000000..79568b4 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/test/src/Provider/GithubResourceOwnerTest.php @@ -0,0 +1,36 @@ +getUrl(); + + $this->assertNull($url); + } + + public function testUrlIsDomainWithoutNickname() + { + $domain = uniqid(); + $user = new \League\OAuth2\Client\Provider\GithubResourceOwner; + $user->setDomain($domain); + + $url = $user->getUrl(); + + $this->assertEquals($domain, $url); + } + + public function testUrlIsNicknameWithoutDomain() + { + $nickname = uniqid(); + $user = new \League\OAuth2\Client\Provider\GithubResourceOwner(['login' => $nickname]); + + $url = $user->getUrl(); + + $this->assertEquals($nickname, $url); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-github/test/src/Provider/GithubTest.php b/plugins/login-oauth2/vendor/league/oauth2-github/test/src/Provider/GithubTest.php new file mode 100644 index 0000000..fd01b68 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-github/test/src/Provider/GithubTest.php @@ -0,0 +1,215 @@ +provider = new \League\OAuth2\Client\Provider\Github([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none', + ]); + } + + public function tearDown() + { + m::close(); + parent::tearDown(); + } + + public function testAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + parse_str($uri['query'], $query); + + $this->assertArrayHasKey('client_id', $query); + $this->assertArrayHasKey('redirect_uri', $query); + $this->assertArrayHasKey('state', $query); + $this->assertArrayHasKey('scope', $query); + $this->assertArrayHasKey('response_type', $query); + $this->assertArrayHasKey('approval_prompt', $query); + $this->assertNotNull($this->provider->getState()); + } + + + public function testScopes() + { + $options = ['scope' => [uniqid(),uniqid()]]; + + $url = $this->provider->getAuthorizationUrl($options); + + $this->assertContains(urlencode(implode(',', $options['scope'])), $url); + } + + public function testGetAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + + $this->assertEquals('/login/oauth/authorize', $uri['path']); + } + + public function testGetBaseAccessTokenUrl() + { + $params = []; + + $url = $this->provider->getBaseAccessTokenUrl($params); + $uri = parse_url($url); + + $this->assertEquals('/login/oauth/access_token', $uri['path']); + } + + public function testGetAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token", "scope":"repo,gist", "token_type":"bearer"}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $response->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $this->assertEquals('mock_access_token', $token->getToken()); + $this->assertNull($token->getExpires()); + $this->assertNull($token->getRefreshToken()); + $this->assertNull($token->getResourceOwnerId()); + } + + public function testGithubEnterpriseDomainUrls() + { + $this->provider->domain = 'https://github.company.com'; + + + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->times(1)->andReturn('access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + $response->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $this->assertEquals($this->provider->domain.'/login/oauth/authorize', $this->provider->getBaseAuthorizationUrl()); + $this->assertEquals($this->provider->domain.'/login/oauth/access_token', $this->provider->getBaseAccessTokenUrl([])); + $this->assertEquals($this->provider->domain.'/api/v3/user', $this->provider->getResourceOwnerDetailsUrl($token)); + //$this->assertEquals($this->provider->domain.'/api/v3/user/emails', $this->provider->urlUserEmails($token)); + } + + public function testUserData() + { + $userId = rand(1000,9999); + $name = uniqid(); + $nickname = uniqid(); + $email = uniqid(); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn('{"id": '.$userId.', "login": "'.$nickname.'", "name": "'.$name.'", "email": "'.$email.'"}'); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals($userId, $user->getId()); + $this->assertEquals($userId, $user->toArray()['id']); + $this->assertEquals($name, $user->getName()); + $this->assertEquals($name, $user->toArray()['name']); + $this->assertEquals($nickname, $user->getNickname()); + $this->assertEquals($nickname, $user->toArray()['login']); + $this->assertEquals($email, $user->getEmail()); + $this->assertEquals($email, $user->toArray()['email']); + $this->assertContains($nickname, $user->getUrl()); + } + + public function testUserEmails() + { + /* + $userId = rand(1000,9999); + $name = uniqid(); + $nickname = uniqid(); + $email = uniqid(); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('access_token=mock_access_token&expires=3600&refresh_token=mock_refresh_token&otherKey={1234}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'application/x-www-form-urlencoded']); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn('[{"email":"mock_email_1","primary":false,"verified":true},{"email":"mock_email_2","primary":false,"verified":true},{"email":"mock_email_3","primary":true,"verified":true}]'); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $emails = $this->provider->getUserEmails($token); + + $this->assertEquals($userId, $user->getUserId()); + $this->assertEquals($name, $user->getName()); + $this->assertEquals($nickname, $user->getNickname()); + $this->assertEquals($email, $user->getEmail()); + $this->assertContains($nickname, $user->getUrl()); + */ + } + + /** + * @expectedException League\OAuth2\Client\Provider\Exception\IdentityProviderException + **/ + public function testExceptionThrownWhenErrorObjectReceived() + { + $status = rand(400,600); + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"message": "Validation Failed","errors": [{"resource": "Issue","field": "title","code": "missing_field"}]}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn($status); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } + + /** + * @expectedException League\OAuth2\Client\Provider\Exception\IdentityProviderException + **/ + public function testExceptionThrownWhenOAuthErrorReceived() + { + $status = 200; + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"error": "bad_verification_code","error_description": "The code passed is incorrect or expired.","error_uri": "https://developer.github.com/v3/oauth/#bad-verification-code"}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn($status); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-google/.github/workflows/ci.yaml b/plugins/login-oauth2/vendor/league/oauth2-google/.github/workflows/ci.yaml new file mode 100644 index 0000000..7876eee --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/.github/workflows/ci.yaml @@ -0,0 +1,65 @@ +name: CI + +on: + pull_request: + push: + branches: [ master ] + +jobs: + run: + runs-on: ubuntu-18.04 + strategy: + fail-fast: false + matrix: + php: + - '7.3' + - '7.4' + - '8.0' + minimum_versions: [false] + coverage: ['none'] + include: + - description: 'Minimum version' + php: '7.3' + minimum_versions: true + - description: 'Log Code Coverage' + php: '7.4' + coverage: 'xdebug' + + name: PHP ${{ matrix.php }} ${{ matrix.description }} + steps: + - name: Checkout + uses: actions/checkout@v2 + + - uses: actions/cache@v2 + with: + path: ~/.composer/cache/files + key: ${{ matrix.php }} + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: ${{ matrix.coverage }} + + - name: Install dependencies + run: composer install + if: matrix.minimum_versions == false + + - name: Install dependencies lower + run: composer update --no-interaction --prefer-lowest + if: matrix.minimum_versions == true + + - name: Run PHPUnit tests + run: vendor/bin/phpunit + if: matrix.coverage == 'none' + + - name: PHPUnit tests and Log Code coverage + run: ./vendor/bin/phpunit --exclude-group proxy --coverage-clover=coverage.xml + if: matrix.coverage == 'xdebug' + + - name: Run codecov + uses: codecov/codecov-action@v1 + if: matrix.coverage == 'xdebug' + with: + file: './coverage.xml' + fail_ci_if_error: true diff --git a/plugins/login-oauth2/vendor/league/oauth2-google/.github/workflows/static-analysis.yaml b/plugins/login-oauth2/vendor/league/oauth2-google/.github/workflows/static-analysis.yaml new file mode 100644 index 0000000..aab2d74 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/.github/workflows/static-analysis.yaml @@ -0,0 +1,25 @@ +name: Code style + +on: + pull_request: + push: + branches: [ master ] + +jobs: + php-cs-fixer: + name: PHP-CodeSniffer + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '7.4' + + - name: Install dependencies + run: composer install + + - name: Run script + run: composer run check diff --git a/plugins/login-oauth2/vendor/league/oauth2-google/CHANGELOG.md b/plugins/login-oauth2/vendor/league/oauth2-google/CHANGELOG.md new file mode 100644 index 0000000..35cf9b7 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/CHANGELOG.md @@ -0,0 +1,79 @@ +OAuth 2.0 Google Provider Changelog + +## 4.0.0 - 2022-03-04 + +### Changed + +- Add PHP 8.0 support, require PHP 7.3 or newer +- Add types where possible + +## 3.0.4 - 2021-01-27 + +### Fixed + +- Correct OAuth endpoint, #94 by @Slamdunk + +## 3.0.3 - 2020-07-24 + +### Fixed + +- Remove the `approval_prompt` from default parameters, #90 + +## 3.0.2 - 2019-11-16 + +### Fixed + +- Allow for `family_name` to be undefined in user information, #79 by @majkel89 + +## 3.0.1 - 2018-12-28 + +### Fixed + +- Correct conflict handling for prompt option, #69 by @mxdpeep + +## 3.0.0 - 2018-12-23 + +### Changed + +- Update to latest version of Google OAuth +- Use only OpenID Connect for user details + +### Fixed + +- Correct handling of selecting from multiple user accounts, #45 +- Prevent conflict when using prompt option, #42 + +### Added + +- Add "locale" to user details, #60 +- Support additional scopes at construction + +### Removed + +- Dropped support for Google+ user details, #34 and #63 + +## 2.2.0 - 2018-03-19 + +### Added + +- Hosted domain validation, #54 by @pradtke + +## 2.1.0 - 2018-03-09 + +### Added + +- OpenID Connect support, #48 by @pradtke + +## 2.0.0 - 2017-01-24 + +### Added + +- PHP 7.1 support + +### Removed + +- Dropped PHP 5.5 support + +## 1.0.0 - 2015-08-12 + +- Initial release diff --git a/plugins/login-oauth2/vendor/league/oauth2-google/CONTRIBUTING.md b/plugins/login-oauth2/vendor/league/oauth2-google/CONTRIBUTING.md new file mode 100644 index 0000000..8455455 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/thephpleague/oauth2-google). + + +## Pull Requests + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow SemVer. Randomly breaking public APIs is not an option. + +- **Create topic branches** - Don't ask us to pull from your master branch. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. + +- **Ensure tests pass!** - Please run the tests (see below) before submitting your pull request, and make sure they pass. We won't accept a patch until all tests pass. + +- **Ensure no coding standards violations** - Please run PHP Code Sniffer using the PSR-2 standard (see below) before submitting your pull request. A violation will cause the build to fail, so please make sure there are no violations. We can't accept a patch if the build fails. + + +## Running Tests + +```sh +composer test +``` + + +## Running PHP Code Sniffer + +```sh +composer check +``` + +**Happy coding**! diff --git a/plugins/login-oauth2/vendor/league/oauth2-google/LICENSE b/plugins/login-oauth2/vendor/league/oauth2-google/LICENSE new file mode 100644 index 0000000..6d45156 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Woody Gilk + +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/plugins/login-oauth2/vendor/league/oauth2-google/README.md b/plugins/login-oauth2/vendor/league/oauth2-google/README.md new file mode 100644 index 0000000..68351e8 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/README.md @@ -0,0 +1,241 @@ +# Google Provider for OAuth 2.0 Client + +[![Join the chat](https://img.shields.io/badge/gitter-join-1DCE73.svg)](https://gitter.im/thephpleague/oauth2-google) +[![Build Status](https://img.shields.io/travis/thephpleague/oauth2-google.svg)](https://travis-ci.org/thephpleague/oauth2-google) +[![Code Coverage](https://img.shields.io/coveralls/thephpleague/oauth2-google.svg)](https://coveralls.io/r/thephpleague/oauth2-google) +[![Code Quality](https://img.shields.io/scrutinizer/g/thephpleague/oauth2-google.svg)](https://scrutinizer-ci.com/g/thephpleague/oauth2-google/) +[![License](https://img.shields.io/packagist/l/league/oauth2-google.svg)](https://github.com/thephpleague/oauth2-google/blob/master/LICENSE) +[![Latest Stable Version](https://img.shields.io/packagist/v/league/oauth2-google.svg)](https://packagist.org/packages/league/oauth2-google) + +This package provides Google OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +This package is compliant with [PSR-1][], [PSR-2][] and [PSR-4][]. If you notice compliance oversights, please send +a patch via pull request. + +[PSR-1]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md +[PSR-2]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md +[PSR-4]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md + +## Requirements + +The following versions of PHP are supported. + +* PHP 7.2 +* PHP 7.3 +* PHP 7.4 +* PHP 8.0 + +This package uses [OpenID Connect][openid-connect] to authenticate users with +Google accounts. + +To use this package, it will be necessary to have a Google client ID and client +secret. These are referred to as `{google-client-id}` and `{google-client-secret}` +in the documentation. + +Please follow the [Google instructions][oauth-setup] to create the required credentials. + +[openid-connect]: https://developers.google.com/identity/protocols/OpenIDConnect +[oauth-setup]: https://developers.google.com/identity/protocols/OpenIDConnect#registeringyourapp + +## Installation + +To install, use composer: + +```sh +composer require league/oauth2-google +``` + +## Usage + +### Authorization Code Flow + +```php +require __DIR__ . '/vendor/autoload.php'; + +use League\OAuth2\Client\Provider\Google; + +session_start(); // Remove if session.auto_start=1 in php.ini + +$provider = new Google([ + 'clientId' => '{google-client-id}', + 'clientSecret' => '{google-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', + 'hostedDomain' => 'example.com', // optional; used to restrict access to users on your G Suite/Google Apps for Business accounts +]); + +if (!empty($_GET['error'])) { + + // Got an error, probably user denied access + exit('Got error: ' . htmlspecialchars($_GET['error'], ENT_QUOTES, 'UTF-8')); + +} elseif (empty($_GET['code'])) { + + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: ' . $authUrl); + exit; + +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + // State is invalid, possible CSRF attack in progress + unset($_SESSION['oauth2state']); + exit('Invalid state'); + +} else { + + // Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the owner details + $ownerDetails = $provider->getResourceOwner($token); + + // Use these details to create a new profile + printf('Hello %s!', $ownerDetails->getFirstName()); + + } catch (Exception $e) { + + // Failed to get user details + exit('Something went wrong: ' . $e->getMessage()); + + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); + + // Use this to get a new access token if the old one expires + echo $token->getRefreshToken(); + + // Unix timestamp at which the access token expires + echo $token->getExpires(); +} +``` + +#### Available Options + +The `Google` provider has the following [options][auth-params]: + +- `accessType` to use online or offline access +- `hostedDomain` to authenticate G Suite users +- `prompt` to modify the prompt that the user will see +- `scopes` to request access to additional user information + +[auth-params]: https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters + +#### Accessing Token JWT + +Google provides a [JSON Web Token][jwt] (JWT) with all access tokens. This token +[contains basic information][openid-jwt] about the authenticated user. The JWT +can be accessed from the `id_token` value of the access token: + +```php +/** @var League\OAuth2\Client\Token\AccessToken $token */ +$values = $token->getValues(); + +/** @var string */ +$jwt = $values['id_token']; +``` + +Parsing the JWT will require a [JWT parser][jwt-parsers]. Refer to parser +documentation for instructions. + +[jwt]: https://jwt.io/ +[openid-jwt]: https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo +[jwt-parsers]: https://packagist.org/search/?q=jwt + +### Refreshing a Token + +Refresh tokens are only provided to applications which request offline access. You can specify offline access by setting the `accessType` option in your provider: + +```php +use League\OAuth2\Client\Provider\Google; + +$provider = new Google([ + 'clientId' => '{google-client-id}', + 'clientSecret' => '{google-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', + 'accessType' => 'offline', +]); +``` + +It is important to note that the refresh token is only returned on the first request after this it will be `null`. You should securely store the refresh token when it is returned: + +```php +$token = $provider->getAccessToken('authorization_code', [ + 'code' => $code +]); + +// persist the token in a database +$refreshToken = $token->getRefreshToken(); +``` + +If you ever need to get a new refresh token you can request one by forcing the consent prompt: + +```php +$authUrl = $provider->getAuthorizationUrl(['prompt' => 'consent']); +``` + +Now you have everything you need to refresh an access token using a refresh token: + +```php +use League\OAuth2\Client\Provider\Google; +use League\OAuth2\Client\Grant\RefreshToken; + +$provider = new Google([ + 'clientId' => '{google-client-id}', + 'clientSecret' => '{google-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', +]); + +$grant = new RefreshToken(); +$token = $provider->getAccessToken($grant, ['refresh_token' => $refreshToken]); +``` + +## Scopes + +Additional [scopes][scopes] can be set by using the `scope` parameter when +generating the authorization URL: + +```php +$authorizationUrl = $provider->getAuthorizationUrl([ + 'scope' => [ + 'scope-url-here' + ], +]); +``` + +[scopes]: https://developers.google.com/identity/protocols/googlescopes + +## Testing + +Tests can be run with: + +```sh +composer test +``` + +Style checks can be run with: + +```sh +composer check +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/thephpleague/oauth2-google/blob/master/CONTRIBUTING.md) for details. + + +## Credits + +- [Woody Gilk](https://github.com/shadowhand) +- [All Contributors](https://github.com/thephpleague/oauth2-google/contributors) + + +## License + +The MIT License (MIT). Please see [License File](https://github.com/thephpleague/oauth2-google/blob/master/LICENSE) for more information. diff --git a/plugins/login-oauth2/vendor/league/oauth2-google/composer.json b/plugins/login-oauth2/vendor/league/oauth2-google/composer.json new file mode 100644 index 0000000..cabdfa0 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/composer.json @@ -0,0 +1,43 @@ +{ + "name": "league/oauth2-google", + "description": "Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Woody Gilk", + "email": "woody.gilk@gmail.com", + "homepage": "http://shadowhand.me" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authentication", + "google" + ], + "minimum-stability": "stable", + "require": { + "php": ">=7.3", + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "eloquent/phony-phpunit": "^6.0 || ^7.1", + "phpunit/phpunit": "^8.0 || ^9.0", + "squizlabs/php_codesniffer": "^3.0" + }, + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "League\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "scripts": { + "check": "phpcs src test --standard=PSR12 -sp" + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-google/examples/index.php b/plugins/login-oauth2/vendor/league/oauth2-google/examples/index.php new file mode 100644 index 0000000..9138437 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/examples/index.php @@ -0,0 +1,35 @@ +getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: ' . $authUrl); + exit; + +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + // State is invalid, possible CSRF attack in progress + unset($_SESSION['oauth2state']); + exit('Invalid state'); + +} else { + + // Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + + $_SESSION['token'] = serialize($token); + + // Optional: Now you have a token you can look up a users profile data + header('Location: /user.php'); +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-google/examples/provider.php b/plugins/login-oauth2/vendor/league/oauth2-google/examples/provider.php new file mode 100644 index 0000000..4001f68 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/examples/provider.php @@ -0,0 +1,24 @@ +getResourceOwner($token); + + // Use these details to create a new profile + printf('Hello %s!
', $userDetails->getFirstname()); +} catch (Exception $e) { + // Failed to get user details + exit('Something went wrong: ' . $e->getMessage()); +} + +// Use this to interact with an API on the users behalf +echo "Token is: ", $token->getToken(), "
"; + +// Use this to get a new access token if the old one expires +echo "Refresh token is: ", $token->getRefreshToken(), "
"; + +// Number of seconds until the access token will expire, and need refreshing +echo "Expires at ", date('r', $token->getExpires()), "
"; + +// Allow the user to logout +echo 'Logout
'; diff --git a/plugins/login-oauth2/vendor/league/oauth2-google/phpunit.xml.dist b/plugins/login-oauth2/vendor/league/oauth2-google/phpunit.xml.dist new file mode 100644 index 0000000..75a635d --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/phpunit.xml.dist @@ -0,0 +1,26 @@ + + + + + ./test + + + + + src/ + + + + + + diff --git a/plugins/login-oauth2/vendor/league/oauth2-google/src/Exception/HostedDomainException.php b/plugins/login-oauth2/vendor/league/oauth2-google/src/Exception/HostedDomainException.php new file mode 100644 index 0000000..7f82b53 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/src/Exception/HostedDomainException.php @@ -0,0 +1,19 @@ +hostedDomain) { + $options['hd'] = $this->hostedDomain; + } + + if (empty($options['access_type']) && $this->accessType) { + $options['access_type'] = $this->accessType; + } + + if (empty($options['prompt']) && $this->prompt) { + $options['prompt'] = $this->prompt; + } + + // Default scopes MUST be included for OpenID Connect. + // Additional scopes MAY be added by constructor or option. + $scopes = array_merge($this->getDefaultScopes(), $this->scopes); + + if (!empty($options['scope'])) { + $scopes = array_merge($scopes, $options['scope']); + } + + $options['scope'] = array_unique($scopes); + + $options = parent::getAuthorizationParameters($options); + + // The "approval_prompt" MUST be removed as it is not supported by Google, use "prompt" instead: + // https://developers.google.com/identity/protocols/oauth2/openid-connect#prompt + unset($options['approval_prompt']); + + return $options; + } + + protected function getDefaultScopes(): array + { + // "openid" MUST be the first scope in the list. + return [ + 'openid', + 'email', + 'profile', + ]; + } + + protected function getScopeSeparator(): string + { + return ' '; + } + + protected function checkResponse(ResponseInterface $response, $data): void + { + // @codeCoverageIgnoreStart + if (empty($data['error'])) { + return; + } + // @codeCoverageIgnoreEnd + + $code = 0; + $error = $data['error']; + + if (is_array($error)) { + $code = $error['code']; + $error = $error['message']; + } + + throw new IdentityProviderException($error, $code, $data); + } + + protected function createResourceOwner(array $response, AccessToken $token): GoogleUser + { + $user = new GoogleUser($response); + + $this->assertMatchingDomain($user->getHostedDomain()); + + return $user; + } + + /** + * @param string|null $hostedDomain + * + * @throws HostedDomainException If the domain does not match the configured domain. + */ + protected function assertMatchingDomain(?string $hostedDomain): void + { + if ($this->hostedDomain === null) { + // No hosted domain configured. + return; + } + + if ($this->hostedDomain === '*' && $hostedDomain) { + // Any hosted domain is allowed. + return; + } + + if ($this->hostedDomain === $hostedDomain) { + // Hosted domain is correct. + return; + } + + throw HostedDomainException::notMatchingDomain($this->hostedDomain); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-google/src/Provider/GoogleUser.php b/plugins/login-oauth2/vendor/league/oauth2-google/src/Provider/GoogleUser.php new file mode 100644 index 0000000..d004e3c --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-google/src/Provider/GoogleUser.php @@ -0,0 +1,109 @@ +response = $response; + } + + public function getId() + { + return $this->response['sub']; + } + + /** + * Get preferred display name. + * + * @return string + */ + public function getName(): string + { + return $this->response['name']; + } + + /** + * Get preferred first name. + * + * @return string|null + */ + public function getFirstName(): ?string + { + return $this->getResponseValue('given_name'); + } + + /** + * Get preferred last name. + * + * @return string|null + */ + public function getLastName(): ?string + { + return $this->getResponseValue('family_name'); + } + + /** + * Get locale. + * + * @return string|null + */ + public function getLocale(): ?string + { + return $this->getResponseValue('locale'); + } + + /** + * Get email address. + * + * @return string|null + */ + public function getEmail(): ?string + { + return $this->getResponseValue('email'); + } + + /** + * Get hosted domain. + * + * @return string|null + */ + public function getHostedDomain(): ?string + { + return $this->getResponseValue('hd'); + } + + /** + * Get avatar image URL. + * + * @return string|null + */ + public function getAvatar(): ?string + { + return $this->getResponseValue('picture'); + } + + /** + * Get user data as an array. + * + * @return array + */ + public function toArray(): array + { + return $this->response; + } + + private function getResponseValue($key) + { + return $this->response[$key] ?? null; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/.gitignore b/plugins/login-oauth2/vendor/league/oauth2-instagram/.gitignore new file mode 100644 index 0000000..d68b693 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/.gitignore @@ -0,0 +1,7 @@ +/build +/vendor +composer.phar +composer.lock +.DS_Store +.idea +.phpunit.result.cache diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/.scrutinizer.yml b/plugins/login-oauth2/vendor/league/oauth2-instagram/.scrutinizer.yml new file mode 100644 index 0000000..85a4ced --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/.scrutinizer.yml @@ -0,0 +1,35 @@ +filter: + excluded_paths: [test/*] +checks: + php: + code_rating: true + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true +tools: + external_code_coverage: + timeout: 600 + runs: 2 + php_analyzer: true + php_code_coverage: false + php_code_sniffer: + config: + standard: PSR2 + filter: + paths: ['src'] + php_loc: + enabled: true + excluded_dirs: [vendor, test] + php_cpd: + enabled: true + excluded_dirs: [vendor, test] diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/.travis.yml b/plugins/login-oauth2/vendor/league/oauth2-instagram/.travis.yml new file mode 100644 index 0000000..ed0ed4a --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/.travis.yml @@ -0,0 +1,34 @@ +dist: trusty +language: php + +php: + - 7.2 + - 7.3 + - 7.4 + - hhvm + +## Cache composer +cache: + directories: + - $HOME/.composer/cache + +matrix: + include: + - php: 7.2 + env: 'COMPOSER_FLAGS="--prefer-stable --prefer-lowest"' + allow_failures: + - php: hhvm + +before_script: + - travis_retry composer update ${COMPOSER_FLAGS} --no-interaction --prefer-dist + +script: + - vendor/bin/phpcs --standard=psr2 src/ + - vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover + +after_script: + - | + if [[ "$TRAVIS_PHP_VERSION" != 'hhvm' ]]; then + wget https://scrutinizer-ci.com/ocular.phar + php ocular.phar code-coverage:upload --format=php-clover coverage.clover + fi diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/CHANGELOG.md b/plugins/login-oauth2/vendor/league/oauth2-instagram/CHANGELOG.md new file mode 100644 index 0000000..79c4008 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/CHANGELOG.md @@ -0,0 +1,181 @@ +# Changelog +All Notable changes to `oauth2-instagram` will be documented in this file + +## 3.1.0 - 2022-02-09 + +### Added +- Support for Long-Lived Access Tokens + - Pass short-term token to `getLongLivedAccessToken` + - Pass long-term token to `getRefreshedAccessToken` to refresh + +### Deprecated +- Nothing + +### Fixed +- Fixes two annotations return types +- Fixes wrong Exception class (`IdentityProviderException` => `InstagramIdentityProviderException`) + +## 3.0.0 - 2020-02-25 + +### Added +- Support for Instagram Basic Display API + - get Resource Owner Details from https://graph.instagram.com/me + - changed default scopes to `['user_profile']` +- Custom host configuration for Graph API host + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Support for Instagram Legacy API (https://api.instagram.com/v1/...) +- Short-hand functions for now removed attributes + - `InstagramResourceOwner::getImageUrl()` + - `InstagramResourceOwner::getName()` + - `InstagramResourceOwner::getDescription()` + +### Security +- Nothing + +## 2.0.0 - 2017-01-25 + +### Added +- PHP 7.1 Support + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- PHP 5.5 Support + +### Security +- Nothing + +## 1.0.0 - 2017-01-25 + +Bump for base package parity + +## 0.2.3 - 2016-12-22 + +### Added +- Custom host configuration + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.2.2 - 2016-04-13 + +### Added +- Refactored exception handling + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.2.1 - 2015-11-23 + +### Added +- A properly functioning `getAuthenticatedRequest()` for Instagram.com +- Modification for data returned by InstagramResourceOwner::toArray + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.2.0 - 2015-08-20 + +### Added +- Upgrade to support version 1.0 release of core client + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.1.2 - 2015-06-17 + +### Added +- Using abstract provider scope separator to format scopes + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.1.1 - 2015-06-17 + +### Added +- Improved clarity to README around expectation of managing scopes + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.1.0 - 2015-04-08 + +### Added +- Initial release! + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/CONTRIBUTING.md b/plugins/login-oauth2/vendor/league/oauth2-instagram/CONTRIBUTING.md new file mode 100644 index 0000000..927dde0 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/thephpleague/oauth2-instagram). + + +## Pull Requests + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow SemVer. Randomly breaking public APIs is not an option. + +- **Create topic branches** - Don't ask us to pull from your master branch. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. + +- **Ensure tests pass!** - Please run the tests (see below) before submitting your pull request, and make sure they pass. We won't accept a patch until all tests pass. + +- **Ensure no coding standards violations** - Please run PHP Code Sniffer using the PSR-2 standard (see below) before submitting your pull request. A violation will cause the build to fail, so please make sure there are no violations. We can't accept a patch if the build fails. + + +## Running Tests + +``` bash +$ ./vendor/bin/phpunit +``` + + +## Running PHP Code Sniffer + +``` bash +$ ./vendor/bin/phpcs src --standard=psr2 -sp +``` + +**Happy coding**! diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/LICENSE b/plugins/login-oauth2/vendor/league/oauth2-instagram/LICENSE new file mode 100644 index 0000000..51455e2 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Steven Maguire + +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/plugins/login-oauth2/vendor/league/oauth2-instagram/README.md b/plugins/login-oauth2/vendor/league/oauth2-instagram/README.md new file mode 100644 index 0000000..257b0c5 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/README.md @@ -0,0 +1,134 @@ +# Instagram Provider for OAuth 2.0 Client +[![Latest Version](https://img.shields.io/github/release/thephpleague/oauth2-instagram.svg?style=flat-square)](https://github.com/thephpleague/oauth2-instagram/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/thephpleague/oauth2-instagram/master.svg?style=flat-square)](https://travis-ci.org/thephpleague/oauth2-instagram) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/oauth2-instagram.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/oauth2-instagram/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/oauth2-instagram.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/oauth2-instagram) +[![Total Downloads](https://img.shields.io/packagist/dt/league/oauth2-instagram.svg?style=flat-square)](https://packagist.org/packages/league/oauth2-instagram) + +This package provides Instagram OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +## Installation + +To install, use composer: + +``` +composer require league/oauth2-instagram +``` + +## Usage + +Usage is the same as The League's OAuth client, using `\League\OAuth2\Client\Provider\Instagram` as the provider. + +### Authorization Code Flow + +```php +$provider = new League\OAuth2\Client\Provider\Instagram([ + 'clientId' => '{instagram-client-id}', + 'clientSecret' => '{instagram-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', + 'host' => 'https://api.instagram.com', // Optional, defaults to https://api.instagram.com + 'graphHost' => 'https://graph.instagram.com' // Optional, defaults to https://graph.instagram.com +]); + +if (!isset($_GET['code'])) { + + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: '.$authUrl); + exit; + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + unset($_SESSION['oauth2state']); + exit('Invalid state'); + +} else { + + // Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the user's details + $user = $provider->getResourceOwner($token); + + // Use these details to create a new profile + printf('Hello %s!', $user->getNickname()); + + } catch (Exception $e) { + + // Failed to get user details + exit('Oh dear...'); + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); +} +``` + +### Requesting a long-lived access-token +```php +$token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] +]); + +$longLivedToken = $provider->getLongLivedAccessToken($token); +``` + +### Refreshing a long-lived access-token +```php +$token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] +]); + +// you need to fetch a long-lived token first! +$longLivedToken = $provider->getLongLivedAccessToken($token); + +$refreshedToken = $provider->getRefreshedAccessToken($longLivedToken); +``` + +### Managing Scopes + +When creating your Instagram authorization URL, you can specify the state and scopes your application may authorize. + +```php +$options = [ + 'state' => 'OPTIONAL_CUSTOM_CONFIGURED_STATE', + 'scope' => ['user_profile', 'user_media'] // array or string +]; + +$authorizationUrl = $provider->getAuthorizationUrl($options); +``` +If neither are defined, the provider will utilize internal defaults. + +At the time of authoring this documentation, the [following scopes are available](https://developers.facebook.com/docs/instagram-basic-display-api/overview#permissions). + +- user_profile +- user_media + +## Testing + +``` bash +$ ./vendor/bin/phpunit +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/thephpleague/oauth2-instagram/blob/master/CONTRIBUTING.md) for details. + + +## Credits + +- [Steven Maguire](https://github.com/stevenmaguire) +- [All Contributors](https://github.com/thephpleague/oauth2-instagram/contributors) + + +## License + +The MIT License (MIT). Please see [License File](https://github.com/thephpleague/oauth2-instagram/blob/master/LICENSE) for more information. diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/composer.json b/plugins/login-oauth2/vendor/league/oauth2-instagram/composer.json new file mode 100644 index 0000000..e479ec1 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/composer.json @@ -0,0 +1,44 @@ +{ + "name": "league/oauth2-instagram", + "description": "Instagram OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authorisation", + "instagram" + ], + "require": { + "league/oauth2-client": "^2.0", + "jakeasmith/http_build_url": "^1.0" + }, + "require-dev": { + "mockery/mockery": "~1.3.1", + "phpunit/phpunit" : ">=8.0", + "squizlabs/php_codesniffer": "^3.0" + }, + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "League\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/phpunit.xml b/plugins/login-oauth2/vendor/league/oauth2-instagram/phpunit.xml new file mode 100644 index 0000000..d6a6ed3 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/phpunit.xml @@ -0,0 +1,28 @@ + + + + + tests + + + + + src/ + + + + + + + + + diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/src/Grant/IgExchangeToken.php b/plugins/login-oauth2/vendor/league/oauth2-instagram/src/Grant/IgExchangeToken.php new file mode 100644 index 0000000..a130eb2 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/src/Grant/IgExchangeToken.php @@ -0,0 +1,32 @@ +getReasonPhrase(); + $code = $response->getStatusCode(); + $body = (string) $response->getBody(); + + if (isset($data['error'], $data['error']['message'])) { + $message = $data['error']['message']; + } + if (isset($data['error'], $data['error']['code'])) { + $code = $data['error']['code']; + } + + return new static($message, $code, $body); + } + + /** + * Creates oauth exception from response. + * + * @param ResponseInterface $response + * @param string $data Parsed response data + * + * @return IdentityProviderException + */ + public static function oauthException(ResponseInterface $response, $data) + { + $message = $response->getReasonPhrase(); + $code = $response->getStatusCode(); + $body = (string) $response->getBody(); + + if (isset($data['error_message'])) { + $message = $data['error_message']; + } + if (isset($data['code'])) { + $code = $data['code']; + } + + return new static($message, $code, $body); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/src/Provider/Instagram.php b/plugins/login-oauth2/vendor/league/oauth2-instagram/src/Provider/Instagram.php new file mode 100644 index 0000000..2e1b930 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/src/Provider/Instagram.php @@ -0,0 +1,301 @@ +host; + } + + /** + * Gets Graph API host. + * + * @return string + */ + public function getGraphHost() + { + return $this->graphHost; + } + + /** + * Get the string used to separate scopes. + * + * @return string + */ + protected function getScopeSeparator() + { + return ' '; + } + + /** + * Get authorization url to begin OAuth flow + * + * @return string + */ + public function getBaseAuthorizationUrl() + { + return $this->host.'/oauth/authorize'; + } + + /** + * Get access token url to retrieve token + * + * @param array $params + * + * @return string + */ + public function getBaseAccessTokenUrl(array $params) + { + return $this->host.'/oauth/access_token'; + } + + /** + * Get access token url to + * - exchange short-lived token for a long-lived token + * - refresh unexpired long-lived token + * + * @param array $params + * @param string $endPoint + * + * @return string + */ + public function getUpdateAccessTokenUrl(array $params, $endPoint) + { + return $this->graphHost.'/'.$endPoint; + } + + /** + * Get provider url to fetch user details + * + * @param AccessToken $token + * + * @return string + */ + public function getResourceOwnerDetailsUrl(AccessToken $token) + { + return $this->graphHost.'/me?fields=id,username&access_token='.$token; + } + + /** + * Returns an authenticated PSR-7 request instance. + * + * @param string $method + * @param string $url + * @param AccessToken|string $token + * @param array $options Any of "headers", "body", and "protocolVersion". + * + * @return \Psr\Http\Message\RequestInterface + */ + public function getAuthenticatedRequest($method, $url, $token, array $options = []) + { + $parsedUrl = parse_url($url); + $queryString = array(); + + if (isset($parsedUrl['query'])) { + parse_str($parsedUrl['query'], $queryString); + } + + if (!isset($queryString['access_token'])) { + $queryString['access_token'] = (string) $token; + } + + $url = http_build_url($url, [ + 'query' => http_build_query($queryString), + ]); + + return $this->createRequest($method, $url, null, $options); + } + + /** + * Get the default scopes used by this provider. + * + * This should not be a complete list of all scopes, but the minimum + * required for the provider user interface! + * + * @return array + */ + protected function getDefaultScopes() + { + return $this->defaultScopes; + } + + /** + * Check a provider response for errors. + * + * @throws InstagramIdentityProviderException + * @param ResponseInterface $response + * @param string $data Parsed response data + * @return void + */ + protected function checkResponse(ResponseInterface $response, $data) + { + // Standard error response format + if (!empty($data['error'])) { + throw InstagramIdentityProviderException::clientException($response, $data); + } + + // OAuthException error response format + if (!empty($data['error_type'])) { + throw InstagramIdentityProviderException::oauthException($response, $data); + } + } + + /** + * Exchanges a short-lived access token with a long-lived access-token. + * + * @param string|AccessTokenInterface $accessToken + * + * @return \League\OAuth2\Client\Token\AccessToken + * + * @throws InstagramIdentityProviderException + */ + public function getLongLivedAccessToken($accessToken) + { + $params = [ + 'client_secret' => $this->clientSecret + ]; + + return $this->getUpdatedAccessToken($accessToken, 'ig_exchange_token', $params); + } + + /** + * Refresh a long-lived token + * + * @param string|AccessTokenInterface $accessToken + * + * @return \League\OAuth2\Client\Token\AccessToken + * + * @throws InstagramIdentityProviderException + */ + public function getRefreshedAccessToken($accessToken) + { + return $this->getUpdatedAccessToken($accessToken, 'ig_refresh_token'); + } + + /** + * Update token based on grant type + * + * @param string|AccessTokenInterface $accessToken + * @param string $grant + * @param array $params + * + * @return \League\OAuth2\Client\Token\AccessToken + * + * @throws InstagramIdentityProviderException + */ + protected function getUpdatedAccessToken($accessToken, $grant, $params = []) + { + $verifiedGrant = $this->verifyGrant($grant); + + $params = array_merge([ + 'access_token' => (string) $accessToken, + ], $params); + + $params = $verifiedGrant->prepareRequestParameters($params, []); + + if ($grant === 'ig_exchange_token') { + $updateEndpoint = 'access_token'; + } elseif ($grant === 'ig_refresh_token') { + $updateEndpoint = 'refresh_access_token'; + } else { + throw new \UnexpectedValueException( + sprintf('Invalid grand type "%s". cannot generate update token url.', $grant) + ); + } + + $url = $this->getUpdateAccessTokenUrl($params, $updateEndpoint); + $query = $this->getAccessTokenQuery($params); + + $request = $this->getRequest(self::METHOD_GET, $this->appendQuery($url, $query)); + $response = $this->getParsedResponse($request); + + if (false === is_array($response)) { + throw new \UnexpectedValueException( + 'Invalid response received from Authorization Server. Expected JSON.' + ); + } + + $prepared = $this->prepareAccessTokenResponse($response); + + return $this->createAccessToken($prepared, $verifiedGrant); + } + + + /** + * Generate a user object from a successful user details request. + * + * @param array $response + * @param AccessToken $token + * @return ResourceOwnerInterface + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + return new InstagramResourceOwner($response); + } + + /** + * Sets host. + * + * @param string $host + * + * @return self + */ + public function setHost($host) + { + $this->host = $host; + + return $this; + } + + /** + * Sets Graph API host. + * + * @param string $host + * + * @return self + */ + public function setGraphHost($host) + { + $this->graphHost = $host; + + return $this; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/src/Provider/InstagramResourceOwner.php b/plugins/login-oauth2/vendor/league/oauth2-instagram/src/Provider/InstagramResourceOwner.php new file mode 100644 index 0000000..61615ac --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/src/Provider/InstagramResourceOwner.php @@ -0,0 +1,51 @@ +response = $response; + } + + /** + * Get resource owner id + * + * @return string|null + */ + public function getId() + { + return $this->response['id'] ?: null; + } + + /** + * Get user nickname + * + * @return string|null + */ + public function getNickname() + { + return $this->response['username'] ?: null; + } + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-instagram/tests/src/Provider/InstagramTest.php b/plugins/login-oauth2/vendor/league/oauth2-instagram/tests/src/Provider/InstagramTest.php new file mode 100644 index 0000000..7e62ff8 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-instagram/tests/src/Provider/InstagramTest.php @@ -0,0 +1,270 @@ +provider = new \League\OAuth2\Client\Provider\Instagram([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none', + ]); + } + + public function testAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + parse_str($uri['query'], $query); + + $this->assertArrayHasKey('client_id', $query); + $this->assertArrayHasKey('redirect_uri', $query); + $this->assertArrayHasKey('state', $query); + $this->assertArrayHasKey('scope', $query); + $this->assertArrayHasKey('response_type', $query); + $this->assertArrayHasKey('approval_prompt', $query); + $this->assertNotNull($this->provider->getState()); + } + + public function testSetHostInConfig() + { + $host = uniqid(); + + $provider = new \League\OAuth2\Client\Provider\Instagram([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none', + 'host' => $host + ]); + + $this->assertEquals($host, $provider->getHost()); + } + + public function testSetHostAfterConfig() + { + $host = uniqid(); + + $this->provider->setHost($host); + + $this->assertEquals($host, $this->provider->getHost()); + } + + public function testSetGraphHostInConfig() + { + $host = uniqid(); + + $provider = new \League\OAuth2\Client\Provider\Instagram([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none', + 'graphHost' => $host + ]); + + $this->assertEquals($host, $provider->getGraphHost()); + } + + public function testSetGraphHostAfterConfig() + { + $host = uniqid(); + + $this->provider->setGraphHost($host); + + $this->assertEquals($host, $this->provider->getGraphHost()); + } + + public function testScopes() + { + $scopeSeparator = ' '; + $options = ['scope' => [uniqid(), uniqid()]]; + $query = ['scope' => implode($scopeSeparator, $options['scope'])]; + $url = $this->provider->getAuthorizationUrl($options); + $encodedScope = $this->buildQueryString($query); + $this->assertStringContainsString($encodedScope, $url); + } + + public function testGetAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + + $this->assertEquals('/oauth/authorize', $uri['path']); + } + + public function testGetBaseAccessTokenUrl() + { + $params = []; + + $url = $this->provider->getBaseAccessTokenUrl($params); + $uri = parse_url($url); + + $this->assertEquals('/oauth/access_token', $uri['path']); + } + + public function testGetAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->andReturn('{"access_token":"mock_access_token","user_id": "123"}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $this->assertEquals('mock_access_token', $token->getToken()); + $this->assertNull($token->getExpires()); + $this->assertNull($token->getRefreshToken()); + $this->assertEquals('123', $token->getResourceOwnerId()); + } + + public function testUserData() + { + $userId = rand(1000,9999); + $nickname = uniqid(); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token","user_id": "1574083"}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn('{"id": "'.$userId.'", "username": "'.$nickname.'"}'); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals($userId, $user->getId()); + $this->assertEquals($userId, $user->toArray()['id']); + $this->assertEquals($nickname, $user->getNickname()); + $this->assertEquals($nickname, $user->toArray()['username']); + } + + public function testExceptionThrownWhenErrorObjectReceived() + { + $this->expectException('League\OAuth2\Client\Provider\Exception\InstagramIdentityProviderException'); + $message = uniqid(); + $status = rand(400,600); + $traceId = uniqid(); + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"error": {"type": "IGApiException","code": '.$status.',"message": "'.$message.'","fbtrace_id":"'.$traceId.'"}}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getReasonPhrase'); + $postResponse->shouldReceive('getStatusCode')->andReturn($status); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } + + public function testExceptionThrownWhenAuthErrorObjectReceived() + { + $this->expectException('League\OAuth2\Client\Provider\Exception\InstagramIdentityProviderException'); + $message = uniqid(); + $status = rand(400,600); + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"error_type": "OAuthException","code": '.$status.',"error_message": "'.$message.'"}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getReasonPhrase'); + $postResponse->shouldReceive('getStatusCode')->andReturn($status); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } + + public function testGetAuthenticatedRequest() + { + $method = 'GET'; + $url = 'https://graph.instagram.com/me'; + + $accessTokenResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $accessTokenResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token","user_id": "1574083"}'); + $accessTokenResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($accessTokenResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $authenticatedRequest = $this->provider->getAuthenticatedRequest($method, $url, $token); + + $this->assertInstanceOf('Psr\Http\Message\RequestInterface', $authenticatedRequest); + $this->assertEquals($method, $authenticatedRequest->getMethod()); + $this->assertStringContainsString('access_token=mock_access_token', $authenticatedRequest->getUri()->getQuery()); + } + + public function testGetUpdateAccessTokenUrlForRefresh() + { + $url = $this->provider->getUpdateAccessTokenUrl([], 'refresh_access_token'); + $uri = parse_url($url); + + $this->assertEquals('/refresh_access_token', $uri['path']); + } + + public function testGetUpdateAccessTokenUrlForExchange() + { + $url = $this->provider->getUpdateAccessTokenUrl([], 'access_token'); + $uri = parse_url($url); + + $this->assertEquals('/access_token', $uri['path']); + } + + public function testGetLongLivedAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->andReturn('{"access_token":"mock_long_lived_access_token","user_id": "123"}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getLongLivedAccessToken('authorization_code', ['code' => 'mock_access_token']); + + $this->assertEquals('mock_long_lived_access_token', $token->getToken()); + $this->assertNull($token->getExpires()); + $this->assertNull($token->getRefreshToken()); + $this->assertEquals('123', $token->getResourceOwnerId()); + } + + public function testGetRefreshedAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->andReturn('{"access_token":"mock_refreshed_long_lived_access_token","user_id": "123"}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getRefreshedAccessToken('authorization_code', ['code' => 'mock_long_lived_access_token']); + + $this->assertEquals('mock_refreshed_long_lived_access_token', $token->getToken()); + $this->assertNull($token->getExpires()); + $this->assertNull($token->getRefreshToken()); + $this->assertEquals('123', $token->getResourceOwnerId()); + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/.gitignore b/plugins/login-oauth2/vendor/league/oauth2-linkedin/.gitignore new file mode 100644 index 0000000..9c9c8f2 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/.gitignore @@ -0,0 +1,5 @@ +/build +/vendor +composer.phar +composer.lock +.DS_Store diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/.scrutinizer.yml b/plugins/login-oauth2/vendor/league/oauth2-linkedin/.scrutinizer.yml new file mode 100644 index 0000000..88c4be1 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/.scrutinizer.yml @@ -0,0 +1,35 @@ +filter: + excluded_paths: [test/*] +checks: + php: + code_rating: true + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true +tools: + external_code_coverage: + timeout: 600 + runs: 1 + php_analyzer: true + php_code_coverage: false + php_code_sniffer: + config: + standard: PSR2 + filter: + paths: ['src'] + php_loc: + enabled: true + excluded_dirs: [vendor, test] + php_cpd: + enabled: true + excluded_dirs: [vendor, test] diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/.travis.yml b/plugins/login-oauth2/vendor/league/oauth2-linkedin/.travis.yml new file mode 100644 index 0000000..d46a4b9 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/.travis.yml @@ -0,0 +1,50 @@ +language: php + +matrix: + include: + - php: 5.6 + - php: 7.0 + - php: 7.1 + - php: 7.2 + - php: nightly + - php: hhvm-3.6 + sudo: required + dist: trusty + group: edge + - php: hhvm-3.9 + sudo: required + dist: trusty + group: edge + - php: hhvm-3.12 + sudo: required + dist: trusty + group: edge + - php: hhvm-3.15 + sudo: required + dist: trusty + group: edge + - php: hhvm-nightly + sudo: required + dist: trusty + group: edge + fast_finish: true + allow_failures: + - php: nightly + - php: hhvm-3.6 + - php: hhvm-3.9 + - php: hhvm-3.12 + - php: hhvm-3.15 + - php: hhvm-nightly + +before_script: + - travis_retry composer self-update + - travis_retry composer install --no-interaction --prefer-source --dev + - travis_retry phpenv rehash + +script: + - ./vendor/bin/phpcs --standard=psr2 src/ + - ./vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover + +after_script: + - if [ "$TRAVIS_PHP_VERSION" == "7.1" ]; then wget https://scrutinizer-ci.com/ocular.phar; fi + - if [ "$TRAVIS_PHP_VERSION" == "7.1" ]; then php ocular.phar code-coverage:upload --format=php-clover coverage.clover; fi diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/CHANGELOG.md b/plugins/login-oauth2/vendor/league/oauth2-linkedin/CHANGELOG.md new file mode 100644 index 0000000..b442d05 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/CHANGELOG.md @@ -0,0 +1,324 @@ +# Changelog +All Notable changes to `oauth2-linkedin` will be documented in this file + +## 5.1.2 - 2020-04-20 + +### Added +- Getting resource owner data as an array now includes the email, if provided. - thanks @vyskocilpavel. + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 5.1.1 - 2019-11-11 + +### Added +- Improved null checking when checking error responses - thanks @Addvilz. + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 5.1.0 - 2019-05-22 + +### Added +- Support for attempting to obtain email address when fetching resource owner. - thanks @OJezu + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 5.0.1 - 2019-05-11 + +### Added +- Support for obtaining refresh tokens and their expiration timestamp. + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 5.0.0 - 2019-05-11 + +### Added +- Support for obtaining the resource owner email address via second method. - thanks @pajavyskocil and @OJezu + +### Deprecated +- Support for LinkedIn API Version 1 + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 4.1.1 - 2018-07-23 + +### Added +- Nothing + +### Deprecated +- Nothing + +### Fixed +- Resolved problem retrieving user detail fields from v1 API - thanks @pwweb and @Akimkin + +### Removed +- Nothing + +### Security +- Nothing + +## 4.1.0 - 2018-06-21 + +### Added +- Add configurable resource owner endpoint version. + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 4.0.0 - 2018-06-21 + +### Added +- Update resource owner url to use v2 of API. + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 3.1.0 - 2018-05-04 + +### Added +- Add a summary field from LinkedIn API - thanks @krainiuk-michael + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 3.0.0 - 2018-03-17 + +### Added +- Explicit support for resource owner fields definition +- Support for accessing resource owner details using dot notation + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Public access to $fields property on League\OAuth2\Client\Provider\LinkedIn instances + +### Security +- Nothing + +## 2.1.0 - 2017-09-11 + +### Added +- Updated authorization urls - thanks @iisisrael + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 2.0.0 - 2017-01-25 + +### Added +- PHP 7.1 Support + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- PHP 5.5 Support + +### Security +- Nothing + +## 1.0.0 - 2017-01-25 + +Bump for base package parity + +## 0.4.2 - 2016-11-09 + +### Added +- Nothing + +### Deprecated +- Nothing + +### Fixed +- Check if index is set in response during method call + +### Removed +- Nothing + +### Security +- Nothing + +## 0.4.1 - 2016-08-06 + +### Added +- Update name of resource owner methods to follow "convention". + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.4.0 - 2015-08-20 + +### Added +- Upgrade to support version 1.0 release of core client + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.3.0 - 2015-06-11 + +### Added +- Array defined scope definition + +### Deprecated +- Nothing + +### Fixed +- Using abstract provider scope separator to format scopes + +## 0.2.0 - 2015-05-26 + +### Added +- Depends on "league/oauth2-client": "0.10.*@dev" + +### Deprecated +- Default scopes in provider; now requires explicit declaration by consuming applications. + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing + +## 0.1.1 - 2015-03-23 + +### Added +- Nothing + +### Deprecated +- Nothing + +### Fixed +- Namespace issue + +### Removed +- Nothing + +### Security +- Nothing + +## 0.1.0 - 2015-03-21 + +### Added +- Initial release! + +### Deprecated +- Nothing + +### Fixed +- Nothing + +### Removed +- Nothing + +### Security +- Nothing diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/CONTRIBUTING.md b/plugins/login-oauth2/vendor/league/oauth2-linkedin/CONTRIBUTING.md new file mode 100644 index 0000000..1ba4ef5 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +We accept contributions via Pull Requests on [Github](https://github.com/thephpleague/oauth2-linkedin). + + +## Pull Requests + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the README and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow SemVer. Randomly breaking public APIs is not an option. + +- **Create topic branches** - Don't ask us to pull from your master branch. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. + +- **Ensure tests pass!** - Please run the tests (see below) before submitting your pull request, and make sure they pass. We won't accept a patch until all tests pass. + +- **Ensure no coding standards violations** - Please run PHP Code Sniffer using the PSR-2 standard (see below) before submitting your pull request. A violation will cause the build to fail, so please make sure there are no violations. We can't accept a patch if the build fails. + + +## Running Tests + +``` bash +$ ./vendor/bin/phpunit +``` + + +## Running PHP Code Sniffer + +``` bash +$ ./vendor/bin/phpcs src --standard=psr2 -sp +``` + +**Happy coding**! diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/LICENSE b/plugins/login-oauth2/vendor/league/oauth2-linkedin/LICENSE new file mode 100644 index 0000000..51455e2 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Steven Maguire + +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/plugins/login-oauth2/vendor/league/oauth2-linkedin/README.md b/plugins/login-oauth2/vendor/league/oauth2-linkedin/README.md new file mode 100644 index 0000000..087745d --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/README.md @@ -0,0 +1,194 @@ +# LinkedIn Provider for OAuth 2.0 Client +[![Latest Version](https://img.shields.io/github/release/thephpleague/oauth2-linkedin.svg?style=flat-square)](https://github.com/thephpleague/oauth2-linkedin/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) +[![Build Status](https://img.shields.io/travis/thephpleague/oauth2-linkedin/master.svg?style=flat-square)](https://travis-ci.org/thephpleague/oauth2-linkedin) +[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/oauth2-linkedin.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/oauth2-linkedin/code-structure) +[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/oauth2-linkedin.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/oauth2-linkedin) +[![Total Downloads](https://img.shields.io/packagist/dt/league/oauth2-linkedin.svg?style=flat-square)](https://packagist.org/packages/league/oauth2-linkedin) + +This package provides LinkedIn OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client). + +## Before You Begin + +> The LinkedIn API has been largely closed off and is only available to approved LinkedIn developers. You can request authorization here - [https://business.linkedin.com/marketing-solutions/marketing-partners/become-a-partner/marketing-developer-program](https://business.linkedin.com/marketing-solutions/marketing-partners/become-a-partner/marketing-developer-program) + +You may be able to successfully obtain Access Tokens using this package and still not be authorized to access some resources available in the API. + +If you encounter the following, or something similar, this policy is being enforced. + +``` +{ + "serviceErrorCode": 100, + "message": "Not enough permissions to access: GET /me", + "status": 403 +} +``` + +## Installation + +To install, use composer: + +``` +composer require league/oauth2-linkedin +``` + +## Usage + +Usage is the same as The League's OAuth client, using `\League\OAuth2\Client\Provider\LinkedIn` as the provider. + +### Authorization Code Flow + +```php +$provider = new League\OAuth2\Client\Provider\LinkedIn([ + 'clientId' => '{linkedin-client-id}', + 'clientSecret' => '{linkedin-client-secret}', + 'redirectUri' => 'https://example.com/callback-url', +]); + +if (!isset($_GET['code'])) { + + // If we don't have an authorization code then get one + $authUrl = $provider->getAuthorizationUrl(); + $_SESSION['oauth2state'] = $provider->getState(); + header('Location: '.$authUrl); + exit; + +// Check given state against previously stored one to mitigate CSRF attack +} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { + + unset($_SESSION['oauth2state']); + exit('Invalid state'); + +} else { + + // Try to get an access token (using the authorization code grant) + $token = $provider->getAccessToken('authorization_code', [ + 'code' => $_GET['code'] + ]); + + // Optional: Now you have a token you can look up a users profile data + try { + + // We got an access token, let's now get the user's details + $user = $provider->getResourceOwner($token); + + // Use these details to create a new profile + printf('Hello %s!', $user->getFirstName()); + + } catch (Exception $e) { + + // Failed to get user details + exit('Oh dear...'); + } + + // Use this to interact with an API on the users behalf + echo $token->getToken(); +} +``` + +### Managing Scopes + +When creating your LinkedIn authorization URL, you can specify the state and scopes your application may authorize. + +```php +$options = [ + 'state' => 'OPTIONAL_CUSTOM_CONFIGURED_STATE', + 'scope' => ['r_liteprofile','r_emailaddress'] // array or string +]; + +$authorizationUrl = $provider->getAuthorizationUrl($options); +``` +If neither are defined, the provider will utilize internal defaults. + +At the time of authoring this documentation, the following scopes are available. + +- r_liteprofile (requested by default) +- r_emailaddress (requested by default) +- r_fullprofile +- w_member_social +- rw_company_admin + +### Retrieving LinkedIn member information + +When fetching resource owner details, the provider allows for an explicit list of fields to be returned, so long as they are allowed by the scopes used to retrieve the access token. + +A default set of fields is provided. Overriding these defaults and defining a new set of fields is easy using the `withFields` method, which is a fluent method that returns the updated provider. + +You can find a complete list of fields on LinkedIn's Developer Documentation: + - [For r_liteprofile](https://docs.microsoft.com/en-us/linkedin/shared/references/v2/profile/basic-profile). + - [For r_fullprofile](https://docs.microsoft.com/en-us/linkedin/shared/references/v2/profile/full-profile). + +```php +$fields = [ + 'id', 'firstName', 'lastName', 'maidenName', + 'headline', 'vanityName', 'birthDate', 'educations' +]; + +$provider = $provider->withFields($fields); +$member = $provider->getResourceOwner($token); + +// or in one line... + +$member = $provider->withFields($fields)->getResourceOwner($token); +``` + +The `getResourceOwner` will return an instance of `League\OAuth2\Client\Provider\LinkedInResourceOwner` which has some helpful getter methods to access basic member details. + +For more customization and control, the `LinkedInResourceOwner` object also offers a `getAttribute` method which accepts a string to access specific attributes that may not have a getter method explicitly defined. + +```php +$firstName = $member->getFirstName(); +$birthDate = $member->getAttribute('birthDate'); +``` + +#### A note about obtaining the resource owner's email address + +> The email has to be fetched by the provider in a separate request, it is not one of the profile fields. + +When getting the resource owner a second request to fetch the email address will always be attempted. This request will fail silently (and `getEmail()` will return `null`) if the access token provided was not issued with the `r_emailaddress` scope. + +```php +$member = $provider->getResourceOwner($token); +$email = $member->getEmail(); +``` + +You can also attempt to fetch the email in a separate request. This request will fail and throw an exception if the access token provided was not issued with the `r_emailaddress` scope. + +```php +$emailAddress = $provider->getResourceOwnerEmail($token); + +``` + + + +### Refresh Tokens + +> LinkedIn has introduced Refresh Tokens with OAuth 2.0. This feature is currently available for a limited set of partners. It will be made GA in the near future. [Source](https://developer.linkedin.com/docs/Refresh-Tokens-with-OAuth-2) + +If your LinkedIn Client ID is associated with a partner that supports refresh tokens, this package will help you access and work with Refresh Tokens. + +``` +$refreshToken = $token->getRefreshToken(); +$refreshTokenExpiration = $token->getRefreshTokenExpires(); +``` + +## Testing + +``` bash +$ ./vendor/bin/phpunit +``` + +## Contributing + +Please see [CONTRIBUTING](https://github.com/thephpleague/oauth2-linkedin/blob/master/CONTRIBUTING.md) for details. + + +## Credits + +- [Steven Maguire](https://github.com/stevenmaguire) +- [All Contributors](https://github.com/thephpleague/oauth2-linkedin/contributors) + + +## License + +The MIT License (MIT). Please see [License File](https://github.com/thephpleague/oauth2-linkedin/blob/master/LICENSE) for more information. diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/composer.json b/plugins/login-oauth2/vendor/league/oauth2-linkedin/composer.json new file mode 100644 index 0000000..fa90127 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/composer.json @@ -0,0 +1,44 @@ +{ + "name": "league/oauth2-linkedin", + "description": "LinkedIn OAuth 2.0 Client Provider for The PHP League OAuth2-Client", + "license": "MIT", + "authors": [ + { + "name": "Steven Maguire", + "email": "stevenmaguire@gmail.com", + "homepage": "https://github.com/stevenmaguire" + } + ], + "keywords": [ + "oauth", + "oauth2", + "client", + "authorization", + "authorisation", + "linkedin" + ], + "require": { + "league/oauth2-client": "^2.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0", + "mockery/mockery": "~0.9", + "squizlabs/php_codesniffer": "~2.0", + "ext-json": "*" + }, + "autoload": { + "psr-4": { + "League\\OAuth2\\Client\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "League\\OAuth2\\Client\\Test\\": "test/src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/phpunit.xml b/plugins/login-oauth2/vendor/league/oauth2-linkedin/phpunit.xml new file mode 100644 index 0000000..1819eb0 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/phpunit.xml @@ -0,0 +1,37 @@ + + + + + + + + + ./test/ + + + + + ./ + + ./vendor + ./test + + + + diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Provider/Exception/LinkedInAccessDeniedException.php b/plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Provider/Exception/LinkedInAccessDeniedException.php new file mode 100644 index 0000000..c5fe406 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Provider/Exception/LinkedInAccessDeniedException.php @@ -0,0 +1,8 @@ + '(' . implode(',', $this->fields) . ')' + ]); + + return 'https://api.linkedin.com/v2/me?' . urldecode($query); + } + + /** + * Get provider url to fetch user details + * + * @param AccessToken $token + * + * @return string + */ + public function getResourceOwnerEmailUrl(AccessToken $token) + { + $query = http_build_query([ + 'q' => 'members', + 'projection' => '(elements*(state,primary,type,handle~))' + ]); + + return 'https://api.linkedin.com/v2/clientAwareMemberHandles?' . urldecode($query); + } + + /** + * Get the default scopes used by this provider. + * + * This should not be a complete list of all scopes, but the minimum + * required for the provider user interface! + * + * @return array + */ + protected function getDefaultScopes() + { + return $this->defaultScopes; + } + + /** + * Check a provider response for errors. + * + * @param ResponseInterface $response + * @param array $data Parsed response data + * @return void + * @throws IdentityProviderException + * @see https://developer.linkedin.com/docs/guide/v2/error-handling + */ + protected function checkResponse(ResponseInterface $response, $data) + { + $this->checkResponseUnauthorized($response, $data); + + if ($response->getStatusCode() >= 400) { + throw new IdentityProviderException( + isset($data['message']) ? $data['message'] : $response->getReasonPhrase(), + isset($data['status']) ? $data['status'] : $response->getStatusCode(), + $response + ); + } + } + + /** + * Check a provider response for unauthorized errors. + * + * @param ResponseInterface $response + * @param array $data Parsed response data + * @return void + * @throws LinkedInAccessDeniedException + * @see https://developer.linkedin.com/docs/guide/v2/error-handling + */ + protected function checkResponseUnauthorized(ResponseInterface $response, $data) + { + if (isset($data['status']) && $data['status'] === 403) { + throw new LinkedInAccessDeniedException( + isset($data['message']) ? $data['message'] : $response->getReasonPhrase(), + isset($data['status']) ? $data['status'] : $response->getStatusCode(), + $response + ); + } + } + + /** + * Generate a user object from a successful user details request. + * + * @param array $response + * @param AccessToken $token + * @return LinkedInResourceOwner + */ + protected function createResourceOwner(array $response, AccessToken $token) + { + // If current accessToken is not authorized with r_emailaddress scope, + // getResourceOwnerEmail will throw LinkedInAccessDeniedException, it will be caught here, + // and then the email will be set to null + // When email is not available due to chosen scopes, other providers simply set it to null, let's do the same. + try { + $email = $this->getResourceOwnerEmail($token); + } catch (LinkedInAccessDeniedException $exception) { + $email = null; + } + $response['email'] = $email; + return new LinkedInResourceOwner($response); + } + + /** + * Returns the requested fields in scope. + * + * @return array + */ + public function getFields() + { + return $this->fields; + } + + /** + * Attempts to fetch resource owner's email address via separate API request. + * + * @param AccessToken $token [description] + * @return string|null + * @throws IdentityProviderException + */ + public function getResourceOwnerEmail(AccessToken $token) + { + $emailUrl = $this->getResourceOwnerEmailUrl($token); + $emailRequest = $this->getAuthenticatedRequest(self::METHOD_GET, $emailUrl, $token); + $emailResponse = $this->getParsedResponse($emailRequest); + + return $this->extractEmailFromResponse($emailResponse); + } + + /** + * Updates the requested fields in scope. + * + * @param array $fields + * + * @return LinkedIn + */ + public function withFields(array $fields) + { + $this->fields = $fields; + + return $this; + } + + /** + * Attempts to extract the email address from a valid email api response. + * + * @param array $response + * @return string|null + */ + protected function extractEmailFromResponse($response = []) + { + try { + $confirmedEmails = array_filter($response['elements'], function ($element) { + return + strtoupper($element['type']) === 'EMAIL' + && strtoupper($element['state']) === 'CONFIRMED' + && $element['primary'] === true + && isset($element['handle~']['emailAddress']) + ; + }); + + return $confirmedEmails[0]['handle~']['emailAddress']; + } catch (Exception $e) { + return null; + } + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Provider/LinkedInResourceOwner.php b/plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Provider/LinkedInResourceOwner.php new file mode 100644 index 0000000..55bbb29 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Provider/LinkedInResourceOwner.php @@ -0,0 +1,207 @@ +response = $response; + $this->setSortedProfilePictures(); + } + + /** + * Gets resource owner attribute by key. The key supports dot notation. + * + * @return mixed + */ + public function getAttribute($key) + { + return $this->getValueByKey($this->response, (string) $key); + } + + /** + * Get user first name + * + * @return string|null + */ + public function getFirstName() + { + return $this->getAttribute('localizedFirstName'); + } + + /** + * Get user user id + * + * @return string|null + */ + public function getId() + { + return $this->getAttribute('id'); + } + + /** + * Get specific image by size + * + * @param integer $size + * @return array|null + */ + public function getImageBySize($size) + { + $pictures = array_filter($this->sortedProfilePictures, function ($picture) use ($size) { + return isset($picture['width']) && $picture['width'] == $size; + }); + + return count($pictures) ? $pictures[0] : null; + } + + /** + * Get available user image sizes + * + * @return array + */ + public function getImageSizes() + { + return array_map(function ($picture) { + return $this->getValueByKey($picture, 'width'); + }, $this->sortedProfilePictures); + } + + /** + * Get user image url + * + * @return string|null + */ + public function getImageUrl() + { + $pictures = $this->getSortedProfilePictures(); + $picture = array_pop($pictures); + + return $picture ? $this->getValueByKey($picture, 'url') : null; + } + + /** + * Get user last name + * + * @return string|null + */ + public function getLastName() + { + return $this->getAttribute('localizedLastName'); + } + + /** + * Returns the sorted collection of profile pictures. + * + * @return array + */ + public function getSortedProfilePictures() + { + return $this->sortedProfilePictures; + } + + /** + * Get user url + * + * @return string|null + */ + public function getUrl() + { + $vanityName = $this->getAttribute('vanityName'); + + return $vanityName ? sprintf('https://www.linkedin.com/in/%s', $vanityName) : null; + } + + /** + * Get user email, if available + * + * @return string|null + */ + public function getEmail() + { + return $this->getAttribute('email'); + } + + /** + * Attempts to sort the collection of profile pictures included in the profile + * before caching them in the resource owner instance. + * + * @return void + */ + private function setSortedProfilePictures() + { + $pictures = $this->getAttribute('profilePicture.displayImage~.elements'); + if (is_array($pictures)) { + $pictures = array_filter($pictures, function ($element) { + // filter to public images only + return + isset($element['data']['com.linkedin.digitalmedia.mediaartifact.StillImage']) + && strtoupper($element['authorizationMethod']) === 'PUBLIC' + && isset($element['identifiers'][0]['identifier']) + ; + }); + // order images by width, LinkedIn profile pictures are always squares, so that should be good enough + usort($pictures, function ($elementA, $elementB) { + $wA = $elementA['data']['com.linkedin.digitalmedia.mediaartifact.StillImage']['storageSize']['width']; + $wB = $elementB['data']['com.linkedin.digitalmedia.mediaartifact.StillImage']['storageSize']['width']; + return $wA - $wB; + }); + $pictures = array_map(function ($element) { + // this is an URL, no idea how many of identifiers there can be, so take the first one. + $url = $element['identifiers'][0]['identifier']; + $type = $element['identifiers'][0]['mediaType']; + $width = $element['data']['com.linkedin.digitalmedia.mediaartifact.StillImage']['storageSize']['width']; + return [ + 'width' => $width, + 'url' => $url, + 'contentType' => $type, + ]; + }, $pictures); + } else { + $pictures = []; + } + + $this->sortedProfilePictures = $pictures; + } + + /** + * Return all of the owner details available as an array. + * + * @return array + */ + public function toArray() + { + return $this->response; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Token/LinkedInAccessToken.php b/plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Token/LinkedInAccessToken.php new file mode 100644 index 0000000..c9dcb41 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/src/Token/LinkedInAccessToken.php @@ -0,0 +1,41 @@ +isExpirationTimestamp($expires)) { + $expires += time(); + } + $this->refreshTokenExpires = $expires; + } + } + + /** + * Returns the refresh token expiration timestamp, if defined. + * + * @return integer|null + */ + public function getRefreshTokenExpires() + { + return $this->refreshTokenExpires; + } +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/test/api_responses/email.json b/plugins/login-oauth2/vendor/league/oauth2-linkedin/test/api_responses/email.json new file mode 100644 index 0000000..7fd0bd2 --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/test/api_responses/email.json @@ -0,0 +1,13 @@ +{ + "elements": [ + { + "handle": "urn:li:emailAddress:", + "state": "CONFIRMED", + "type": "EMAIL", + "handle~": { + "emailAddress": "resource-owner@example.com" + }, + "primary": true + } + ] +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/test/api_responses/me.json b/plugins/login-oauth2/vendor/league/oauth2-linkedin/test/api_responses/me.json new file mode 100644 index 0000000..5d2ef3e --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/test/api_responses/me.json @@ -0,0 +1,186 @@ +{ + "localizedLastName": "Doe", + "profilePicture": { + "displayImage": "urn:li:digitalmediaAsset:", + "displayImage~": { + "elements": [ + { + "artifact": "urn:li:digitalmediaMediaArtifact:(urn:li:digitalmediaAsset:,urn:li:digitalmediaMediaArtifactClass:profile-displayphoto-shrink_100_100)", + "authorizationMethod": "PUBLIC", + "data": { + "com.linkedin.digitalmedia.mediaartifact.StillImage": { + "storageSize": { + "width": 100, + "height": 100 + }, + "storageAspectRatio": { + "widthAspect": 1.0, + "heightAspect": 1.0, + "formatted": "1.00:1.00" + }, + "mediaType": "image/jpeg", + "rawCodecSpec": { + "name": "jpeg", + "type": "image" + }, + "displaySize": { + "uom": "PX", + "width": 100.0, + "height": 100.0 + }, + "displayAspectRatio": { + "widthAspect": 1.0, + "heightAspect": 1.0, + "formatted": "1.00:1.00" + } + } + }, + "identifiers": [ + { + "identifier": "http://example.com/avatar_100_100.jpeg", + "file": "urn:li:digitalmediaFile:(urn:li:digitalmediaAsset:,urn:li:digitalmediaMediaArtifactClass:profile-displayphoto-shrink_100_100,0)", + "index": 0, + "mediaType": "image/jpeg", + "identifierType": "EXTERNAL_URL", + "identifierExpiresInSeconds": 1561593600 + } + ] + }, + { + "artifact": "urn:li:digitalmediaMediaArtifact:(urn:li:digitalmediaAsset:,urn:li:digitalmediaMediaArtifactClass:profile-displayphoto-shrink_200_200)", + "authorizationMethod": "PUBLIC", + "data": { + "com.linkedin.digitalmedia.mediaartifact.StillImage": { + "storageSize": { + "width": 200, + "height": 200 + }, + "storageAspectRatio": { + "widthAspect": 1.0, + "heightAspect": 1.0, + "formatted": "1.00:1.00" + }, + "mediaType": "image/jpeg", + "rawCodecSpec": { + "name": "jpeg", + "type": "image" + }, + "displaySize": { + "uom": "PX", + "width": 200.0, + "height": 200.0 + }, + "displayAspectRatio": { + "widthAspect": 1.0, + "heightAspect": 1.0, + "formatted": "1.00:1.00" + } + } + }, + "identifiers": [ + { + "identifier": "http://example.com/avatar_200_200.jpeg", + "file": "urn:li:digitalmediaFile:(urn:li:digitalmediaAsset:,urn:li:digitalmediaMediaArtifactClass:profile-displayphoto-shrink_200_200,0)", + "index": 0, + "mediaType": "image/jpeg", + "identifierType": "EXTERNAL_URL", + "identifierExpiresInSeconds": 1561593600 + } + ] + }, + { + "artifact": "urn:li:digitalmediaMediaArtifact:(urn:li:digitalmediaAsset:,urn:li:digitalmediaMediaArtifactClass:profile-displayphoto-shrink_400_400)", + "authorizationMethod": "PUBLIC", + "data": { + "com.linkedin.digitalmedia.mediaartifact.StillImage": { + "storageSize": { + "width": 400, + "height": 400 + }, + "storageAspectRatio": { + "widthAspect": 1.0, + "heightAspect": 1.0, + "formatted": "1.00:1.00" + }, + "mediaType": "image/jpeg", + "rawCodecSpec": { + "name": "jpeg", + "type": "image" + }, + "displaySize": { + "uom": "PX", + "width": 400.0, + "height": 400.0 + }, + "displayAspectRatio": { + "widthAspect": 1.0, + "heightAspect": 1.0, + "formatted": "1.00:1.00" + } + } + }, + "identifiers": [ + { + "identifier": "http://example.com/avatar_400_400.jpeg", + "file": "urn:li:digitalmediaFile:(urn:li:digitalmediaAsset:,urn:li:digitalmediaMediaArtifactClass:profile-displayphoto-shrink_400_400,0)", + "index": 0, + "mediaType": "image/jpeg", + "identifierType": "EXTERNAL_URL", + "identifierExpiresInSeconds": 1561593600 + } + ] + }, + { + "artifact": "urn:li:digitalmediaMediaArtifact:(urn:li:digitalmediaAsset:,urn:li:digitalmediaMediaArtifactClass:profile-displayphoto-shrink_800_800)", + "authorizationMethod": "PUBLIC", + "data": { + "com.linkedin.digitalmedia.mediaartifact.StillImage": { + "storageSize": { + "width": 800, + "height": 800 + }, + "storageAspectRatio": { + "widthAspect": 1.0, + "heightAspect": 1.0, + "formatted": "1.00:1.00" + }, + "mediaType": "image/jpeg", + "rawCodecSpec": { + "name": "jpeg", + "type": "image" + }, + "displaySize": { + "uom": "PX", + "width": 800.0, + "height": 800.0 + }, + "displayAspectRatio": { + "widthAspect": 1.0, + "heightAspect": 1.0, + "formatted": "1.00:1.00" + } + } + }, + "identifiers": [ + { + "identifier": "http://example.com/avatar_800_800.jpeg", + "file": "urn:li:digitalmediaFile:(urn:li:digitalmediaAsset:,urn:li:digitalmediaMediaArtifactClass:profile-displayphoto-shrink_800_800,0)", + "index": 0, + "mediaType": "image/jpeg", + "identifierType": "EXTERNAL_URL", + "identifierExpiresInSeconds": 1561593600 + } + ] + } + ], + "paging": { + "count": 10, + "start": 0, + "links": [] + } + } + }, + "id": "abcdef1234", + "localizedFirstName": "John", + "vanityName": "john-doe" +} diff --git a/plugins/login-oauth2/vendor/league/oauth2-linkedin/test/src/Provider/LinkedInTest.php b/plugins/login-oauth2/vendor/league/oauth2-linkedin/test/src/Provider/LinkedInTest.php new file mode 100644 index 0000000..b67f44d --- /dev/null +++ b/plugins/login-oauth2/vendor/league/oauth2-linkedin/test/src/Provider/LinkedInTest.php @@ -0,0 +1,431 @@ +provider = new \League\OAuth2\Client\Provider\LinkedIn([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none', + ]); + } + + public function tearDown() + { + m::close(); + parent::tearDown(); + } + + public function testAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + parse_str($uri['query'], $query); + + $this->assertArrayHasKey('client_id', $query); + $this->assertArrayHasKey('redirect_uri', $query); + $this->assertArrayHasKey('state', $query); + $this->assertArrayHasKey('scope', $query); + $this->assertArrayHasKey('response_type', $query); + $this->assertArrayHasKey('approval_prompt', $query); + $this->assertNotNull($this->provider->getState()); + } + + public function testResourceOwnerDetailsUrl() + { + $accessToken = m::mock('League\OAuth2\Client\Token\AccessToken'); + $expectedFields = $this->provider->getFields(); + $url = $this->provider->getResourceOwnerDetailsUrl($accessToken); + $uri = parse_url($url); + $path = $uri['path']; + $query = explode('=', $uri['query']); + $fields = $query[1]; + $actualFields = explode(',', preg_replace('/^\((.*)\)$/', '\1', $fields)); + $this->assertEquals('/v2/me', $path); + $this->assertEquals('projection', $query[0]); + $this->assertEquals($expectedFields, $actualFields); + } + + public function testResourceOwnerEmailUrl() + { + $accessToken = m::mock('League\OAuth2\Client\Token\AccessToken'); + $expectedFields = $this->provider->getFields(); + $url = $this->provider->getResourceOwnerEmailUrl($accessToken); + $uri = parse_url($url); + parse_str($uri['query'], $query); + $this->assertEquals('/v2/clientAwareMemberHandles', $uri['path']); + $this->assertEquals('(elements*(state,primary,type,handle~))', $query['projection']); + } + + public function testScopes() + { + $scopeSeparator = ' '; + $options = ['scope' => [uniqid(), uniqid()]]; + $query = ['scope' => implode($scopeSeparator, $options['scope'])]; + $url = $this->provider->getAuthorizationUrl($options); + $encodedScope = $this->buildQueryString($query); + $this->assertContains($encodedScope, $url); + } + + public function testFields() + { + $provider = new \League\OAuth2\Client\Provider\LinkedIn([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none' + ]); + + $currentFields = $provider->getFields(); + $customFields = [uniqid(), uniqid()]; + + $this->assertTrue(is_array($currentFields)); + $provider->withFields($customFields); + $this->assertEquals($customFields, $provider->getFields()); + } + + public function testNonArrayFieldsDuringInstantiationThrowsException() + { + $this->setExpectedException(InvalidArgumentException::class); + $provider = new \League\OAuth2\Client\Provider\LinkedIn([ + 'clientId' => 'mock_client_id', + 'clientSecret' => 'mock_secret', + 'redirectUri' => 'none', + 'fields' => 'foo' + ]); + } + + public function testGetAuthorizationUrl() + { + $url = $this->provider->getAuthorizationUrl(); + $uri = parse_url($url); + + $this->assertEquals('/oauth/v2/authorization', $uri['path']); + } + + public function testGetBaseAccessTokenUrl() + { + $params = []; + + $url = $this->provider->getBaseAccessTokenUrl($params); + $uri = parse_url($url); + + $this->assertEquals('/oauth/v2/accessToken', $uri['path']); + } + + public function testGetAccessToken() + { + $response = m::mock('Psr\Http\Message\ResponseInterface'); + $response->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token", "expires_in": 3600, "refresh_token": "mock_refresh_token", "refresh_token_expires_in": 7200}'); + $response->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $response->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send')->times(1)->andReturn($response); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $this->assertEquals('mock_access_token', $token->getToken()); + $this->assertLessThanOrEqual(time() + 3600, $token->getExpires()); + $this->assertGreaterThanOrEqual(time(), $token->getExpires()); + $this->assertEquals('mock_refresh_token', $token->getRefreshToken()); + $this->assertLessThanOrEqual(time() + 7200, $token->getRefreshTokenExpires()); + $this->assertGreaterThanOrEqual(time(), $token->getRefreshTokenExpires()); + $this->assertNull($token->getResourceOwnerId()); + } + + public function testUserData() + { + $apiProfileResponse = json_decode(file_get_contents(__DIR__.'/../../api_responses/me.json'), true); + $apiEmailResponse = json_decode(file_get_contents(__DIR__.'/../../api_responses/email.json'), true); + $somethingExtra = ['more' => uniqid()]; + $apiProfileResponse['somethingExtra'] = $somethingExtra; + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token", "expires_in": 3600}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn(json_encode($apiProfileResponse)); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $emailResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $emailResponse->shouldReceive('getBody')->andReturn(json_encode($apiEmailResponse)); + $emailResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $emailResponse->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(3) + ->andReturn($postResponse, $userResponse, $emailResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals('abcdef1234', $user->getId()); + $this->assertEquals('abcdef1234', $user->toArray()['id']); + $this->assertEquals('John', $user->getFirstName()); + $this->assertEquals('John', $user->toArray()['localizedFirstName']); + $this->assertEquals('Doe', $user->getLastName()); + $this->assertEquals('Doe', $user->toArray()['localizedLastName']); + $this->assertEquals('http://example.com/avatar_800_800.jpeg', $user->getImageUrl()); + $this->assertEquals('https://www.linkedin.com/in/john-doe', $user->getUrl()); + $this->assertEquals('resource-owner@example.com', $user->getEmail()); + $this->assertEquals($somethingExtra, $user->getAttribute('somethingExtra')); + $this->assertEquals($somethingExtra, $user->toArray()['somethingExtra']); + $this->assertEquals($somethingExtra['more'], $user->getAttribute('somethingExtra.more')); + $this->assertEquals([100, 200, 400, 800], $user->getImageSizes()); + $this->assertTrue(is_array($user->getImageBySize(100))); + $this->assertNull($user->getImageBySize(300)); + } + + public function testMissingUserData() + { + $userId = rand(1000,9999); + $firstName = uniqid(); + $lastName = uniqid(); + $apiProfileResponse = json_decode(file_get_contents(__DIR__.'/../../api_responses/me.json'), true); + $apiEmailResponse = json_decode(file_get_contents(__DIR__.'/../../api_responses/email.json'), true); + $apiProfileResponse['id'] = $userId; + $apiProfileResponse['localizedFirstName'] = $firstName; + $apiProfileResponse['localizedLastName'] = $lastName; + unset($apiProfileResponse['profilePicture']); + unset($apiProfileResponse['vanityName']); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token", "expires_in": 3600}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn(json_encode($apiProfileResponse)); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $emailResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $emailResponse->shouldReceive('getBody')->andReturn(json_encode($apiEmailResponse)); + $emailResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $emailResponse->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(3) + ->andReturn($postResponse, $userResponse, $emailResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $user = $this->provider->getResourceOwner($token); + + $this->assertEquals($userId, $user->getId()); + $this->assertEquals($userId, $user->toArray()['id']); + $this->assertEquals($firstName, $user->getFirstName()); + $this->assertEquals($firstName, $user->toArray()['localizedFirstName']); + $this->assertEquals($lastName, $user->GeTlAsTnAmE()); // https://github.com/thephpleague/oauth2-linkedin/issues/4 + $this->assertEquals($lastName, $user->toArray()['localizedLastName']); + $this->assertEquals(null, $user->getImageurl()); + $this->assertEquals(null, $user->getUrl()); + } + + public function testUserEmail() + { + $apiEmailResponse = json_decode(file_get_contents(__DIR__.'/../../api_responses/email.json'), true); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token", "expires_in": 3600}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn(json_encode($apiEmailResponse)); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $userResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $email = $this->provider->getResourceOwnerEmail($token); + + $this->assertEquals('resource-owner@example.com', $email); + } + + public function testUserEmailNullIfApiResponseInvalid() + { + foreach ([null, []] as $apiEmailResponse) { + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token", "expires_in": 3600}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $emailResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $emailResponse->shouldReceive('getBody')->andReturn(json_encode($apiEmailResponse)); + $emailResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $emailResponse->shouldReceive('getStatusCode')->andReturn(200); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $emailResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + $email = $this->provider->getResourceOwnerEmail($token); + + $this->assertNull($email); + } + } + + public function testResourceOwnerEmailNullWhenNotAuthorized() + { + $apiProfileResponse = json_decode(file_get_contents(__DIR__.'/../../api_responses/me.json'), true); + + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token", "expires_in": 3600}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $userResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $userResponse->shouldReceive('getBody')->andReturn(json_encode($apiProfileResponse)); + $userResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $userResponse->shouldReceive('getStatusCode')->andReturn(200); + + $emailResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $emailResponse->shouldReceive('getBody')->andReturn('{"message": "Not enough permissions to access: GET-members /clientAwareMemberHandles","status":403,"serviceErrorCode":100}'); + $emailResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $emailResponse->shouldReceive('getStatusCode')->andReturn(403); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(3) + ->andReturn($postResponse, $userResponse, $emailResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + $user = $this->provider->getResourceOwner($token); + + $this->assertNull($user->getEmail()); + + $this->assertEquals('abcdef1234', $user->getId()); + $this->assertEquals('John', $user->getFirstName()); + $this->assertEquals('Doe', $user->getLastName()); + $this->assertEquals('http://example.com/avatar_800_800.jpeg', $user->getImageUrl()); + $this->assertEquals('https://www.linkedin.com/in/john-doe', $user->getUrl()); + } + + public function testExceptionThrownWhenEmailIsNotAuthorizedButRequestedFromAdapter() + { + $errorMessage = 'Not enough permissions to access: GET-members /clientAwareMemberHandles'; + $errorStatus = 403; + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"access_token": "mock_access_token", "expires_in": 3600}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn(200); + + $emailResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $emailResponse->shouldReceive('getBody')->andReturn('{"message": "'.$errorMessage.'","status":'.$errorStatus.',"serviceErrorCode":100}'); + $emailResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $emailResponse->shouldReceive('getStatusCode')->andReturn(403); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(2) + ->andReturn($postResponse, $emailResponse); + $this->provider->setHttpClient($client); + + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + + try { + $this->provider->getResourceOwnerEmail($token); + } catch (\Exception $exception) { + $this->assertInstanceOf( + 'League\OAuth2\Client\Provider\Exception\LinkedInAccessDeniedException', + $exception, + 'An invalid exception was thrown: '.get_class($exception) + ); + $this->assertEquals($exception->getMessage(), $errorMessage); + $this->assertEquals($exception->getCode(), $errorStatus); + return; + } + $this->fail('No exception was thrown'); + } + + public function testExceptionThrownWhenErrorObjectReceived() + { + $errorMessage = uniqid(); + $errorStatus = rand(400,600); + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"message": "'.$errorMessage.'","status": '.$errorStatus.', "serviceErrorCode": 100}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn($errorStatus); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + + try { + $token = $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } catch (\Exception $exception) { + $this->assertInstanceOf( + 'League\OAuth2\Client\Provider\Exception\IdentityProviderException', + $exception, + 'An invalid exception was thrown: '.get_class($exception) + ); + $this->assertEquals($exception->getMessage(), $errorMessage); + $this->assertEquals($exception->getCode(), $errorStatus); + return; + } + $this->fail('No exception was thrown'); + } + + public function testProviderExceptionThrownWhenErrorObjectReceivedWithoutMessage() + { + $statusCode = rand(400,600); + $postResponse = m::mock('Psr\Http\Message\ResponseInterface'); + $postResponse->shouldReceive('getBody')->andReturn('{"serviceErrorCode": 100}'); + $postResponse->shouldReceive('getHeader')->andReturn(['content-type' => 'json']); + $postResponse->shouldReceive('getStatusCode')->andReturn($statusCode); + $postResponse->shouldReceive('getReasonPhrase')->andReturn('mock reason phrase'); + + $client = m::mock('GuzzleHttp\ClientInterface'); + $client->shouldReceive('send') + ->times(1) + ->andReturn($postResponse); + $this->provider->setHttpClient($client); + + try { + $this->provider->getAccessToken('authorization_code', ['code' => 'mock_authorization_code']); + } catch (\Exception $e) { + + $this->assertInstanceOf( + 'League\OAuth2\Client\Provider\Exception\IdentityProviderException', + $e, + 'Unexpected exception thrown' + ); + + $this->assertEquals($e->getMessage(), 'mock reason phrase'); + $this->assertEquals($e->getCode(), $statusCode); + + return; + } + + $this->fail('No exception was thrown'); + } +} diff --git a/plugins/login-oauth2/vendor/paragonie/random_compat/LICENSE b/plugins/login-oauth2/vendor/paragonie/random_compat/LICENSE new file mode 100644 index 0000000..45c7017 --- /dev/null +++ b/plugins/login-oauth2/vendor/paragonie/random_compat/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Paragon Initiative Enterprises + +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/plugins/login-oauth2/vendor/paragonie/random_compat/build-phar.sh b/plugins/login-oauth2/vendor/paragonie/random_compat/build-phar.sh new file mode 100644 index 0000000..b4a5ba3 --- /dev/null +++ b/plugins/login-oauth2/vendor/paragonie/random_compat/build-phar.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +basedir=$( dirname $( readlink -f ${BASH_SOURCE[0]} ) ) + +php -dphar.readonly=0 "$basedir/other/build_phar.php" $* \ No newline at end of file diff --git a/plugins/login-oauth2/vendor/paragonie/random_compat/composer.json b/plugins/login-oauth2/vendor/paragonie/random_compat/composer.json new file mode 100644 index 0000000..f2b9c4e --- /dev/null +++ b/plugins/login-oauth2/vendor/paragonie/random_compat/composer.json @@ -0,0 +1,34 @@ +{ + "name": "paragonie/random_compat", + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "random", + "polyfill", + "pseudorandom" + ], + "license": "MIT", + "type": "library", + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "support": { + "issues": "https://github.com/paragonie/random_compat/issues", + "email": "info@paragonie.com", + "source": "https://github.com/paragonie/random_compat" + }, + "require": { + "php": ">= 7" + }, + "require-dev": { + "vimeo/psalm": "^1", + "phpunit/phpunit": "4.*|5.*" + }, + "suggest": { + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + } +} diff --git a/plugins/login-oauth2/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey b/plugins/login-oauth2/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey new file mode 100644 index 0000000..eb50ebf --- /dev/null +++ b/plugins/login-oauth2/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey @@ -0,0 +1,5 @@ +-----BEGIN PUBLIC KEY----- +MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEEd+wCqJDrx5B4OldM0dQE0ZMX+lx1ZWm +pui0SUqD4G29L3NGsz9UhJ/0HjBdbnkhIK5xviT0X5vtjacF6ajgcCArbTB+ds+p ++h7Q084NuSuIpNb6YPfoUFgC/CL9kAoc +-----END PUBLIC KEY----- diff --git a/plugins/login-oauth2/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey.asc b/plugins/login-oauth2/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey.asc new file mode 100644 index 0000000..6a1d7f3 --- /dev/null +++ b/plugins/login-oauth2/vendor/paragonie/random_compat/dist/random_compat.phar.pubkey.asc @@ -0,0 +1,11 @@ +-----BEGIN PGP SIGNATURE----- +Version: GnuPG v2.0.22 (MingW32) + +iQEcBAABAgAGBQJWtW1hAAoJEGuXocKCZATaJf0H+wbZGgskK1dcRTsuVJl9IWip +QwGw/qIKI280SD6/ckoUMxKDCJiFuPR14zmqnS36k7N5UNPnpdTJTS8T11jttSpg +1LCmgpbEIpgaTah+cELDqFCav99fS+bEiAL5lWDAHBTE/XPjGVCqeehyPYref4IW +NDBIEsvnHPHPLsn6X5jq4+Yj5oUixgxaMPiR+bcO4Sh+RzOVB6i2D0upWfRXBFXA +NNnsg9/zjvoC7ZW73y9uSH+dPJTt/Vgfeiv52/v41XliyzbUyLalf02GNPY+9goV +JHG1ulEEBJOCiUD9cE1PUIJwHA/HqyhHIvV350YoEFiHl8iSwm7SiZu5kPjaq74= +=B6+8 +-----END PGP SIGNATURE----- diff --git a/plugins/login-oauth2/vendor/paragonie/random_compat/lib/random.php b/plugins/login-oauth2/vendor/paragonie/random_compat/lib/random.php new file mode 100644 index 0000000..c7731a5 --- /dev/null +++ b/plugins/login-oauth2/vendor/paragonie/random_compat/lib/random.php @@ -0,0 +1,32 @@ +buildFromDirectory(dirname(__DIR__).'/lib'); +rename( + dirname(__DIR__).'/lib/index.php', + dirname(__DIR__).'/lib/random.php' +); + +/** + * If we pass an (optional) path to a private key as a second argument, we will + * sign the Phar with OpenSSL. + * + * If you leave this out, it will produce an unsigned .phar! + */ +if ($argc > 1) { + if (!@is_readable($argv[1])) { + echo 'Could not read the private key file:', $argv[1], "\n"; + exit(255); + } + $pkeyFile = file_get_contents($argv[1]); + + $private = openssl_get_privatekey($pkeyFile); + if ($private !== false) { + $pkey = ''; + openssl_pkey_export($private, $pkey); + $phar->setSignatureAlgorithm(Phar::OPENSSL, $pkey); + + /** + * Save the corresponding public key to the file + */ + if (!@is_readable($dist.'/random_compat.phar.pubkey')) { + $details = openssl_pkey_get_details($private); + file_put_contents( + $dist.'/random_compat.phar.pubkey', + $details['key'] + ); + } + } else { + echo 'An error occurred reading the private key from OpenSSL.', "\n"; + exit(255); + } +} diff --git a/plugins/login-oauth2/vendor/paragonie/random_compat/psalm-autoload.php b/plugins/login-oauth2/vendor/paragonie/random_compat/psalm-autoload.php new file mode 100644 index 0000000..d71d1b8 --- /dev/null +++ b/plugins/login-oauth2/vendor/paragonie/random_compat/psalm-autoload.php @@ -0,0 +1,9 @@ + + + + + + + + + + + + + + + diff --git a/plugins/login-oauth2/vendor/psr/http-client/CHANGELOG.md b/plugins/login-oauth2/vendor/psr/http-client/CHANGELOG.md new file mode 100644 index 0000000..e2dc25f --- /dev/null +++ b/plugins/login-oauth2/vendor/psr/http-client/CHANGELOG.md @@ -0,0 +1,23 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.0.1 + +Allow installation with PHP 8. No code changes. + +## 1.0.0 + +First stable release. No changes since 0.3.0. + +## 0.3.0 + +Added Interface suffix on exceptions + +## 0.2.0 + +All exceptions are in `Psr\Http\Client` namespace + +## 0.1.0 + +First release diff --git a/plugins/login-oauth2/vendor/psr/http-client/LICENSE b/plugins/login-oauth2/vendor/psr/http-client/LICENSE new file mode 100644 index 0000000..cd5e002 --- /dev/null +++ b/plugins/login-oauth2/vendor/psr/http-client/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2017 PHP Framework Interoperability Group + +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/plugins/login-oauth2/vendor/psr/http-client/README.md b/plugins/login-oauth2/vendor/psr/http-client/README.md new file mode 100644 index 0000000..6876b84 --- /dev/null +++ b/plugins/login-oauth2/vendor/psr/http-client/README.md @@ -0,0 +1,12 @@ +HTTP Client +=========== + +This repository holds all the common code related to [PSR-18 (HTTP Client)][psr-url]. + +Note that this is not a HTTP Client implementation of its own. It is merely abstractions that describe the components of a HTTP Client. + +The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist. + +[psr-url]: http://www.php-fig.org/psr/psr-18 +[package-url]: https://packagist.org/packages/psr/http-client +[implementation-url]: https://packagist.org/providers/psr/http-client-implementation diff --git a/plugins/login-oauth2/vendor/psr/http-client/composer.json b/plugins/login-oauth2/vendor/psr/http-client/composer.json new file mode 100644 index 0000000..c195f8f --- /dev/null +++ b/plugins/login-oauth2/vendor/psr/http-client/composer.json @@ -0,0 +1,27 @@ +{ + "name": "psr/http-client", + "description": "Common interface for HTTP clients", + "keywords": ["psr", "psr-18", "http", "http-client"], + "homepage": "https://github.com/php-fig/http-client", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/plugins/login-oauth2/vendor/psr/http-client/src/ClientExceptionInterface.php b/plugins/login-oauth2/vendor/psr/http-client/src/ClientExceptionInterface.php new file mode 100644 index 0000000..aa0b9cf --- /dev/null +++ b/plugins/login-oauth2/vendor/psr/http-client/src/ClientExceptionInterface.php @@ -0,0 +1,10 @@ +=7.0.0", + "psr/http-message": "^1.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/plugins/login-oauth2/vendor/psr/http-factory/src/RequestFactoryInterface.php b/plugins/login-oauth2/vendor/psr/http-factory/src/RequestFactoryInterface.php new file mode 100644 index 0000000..cb39a08 --- /dev/null +++ b/plugins/login-oauth2/vendor/psr/http-factory/src/RequestFactoryInterface.php @@ -0,0 +1,18 @@ +=5.3.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/plugins/login-oauth2/vendor/psr/http-message/src/MessageInterface.php b/plugins/login-oauth2/vendor/psr/http-message/src/MessageInterface.php new file mode 100644 index 0000000..dd46e5e --- /dev/null +++ b/plugins/login-oauth2/vendor/psr/http-message/src/MessageInterface.php @@ -0,0 +1,187 @@ +getHeaders() as $name => $values) { + * echo $name . ": " . implode(", ", $values); + * } + * + * // Emit headers iteratively: + * foreach ($message->getHeaders() as $name => $values) { + * foreach ($values as $value) { + * header(sprintf('%s: %s', $name, $value), false); + * } + * } + * + * While header names are not case-sensitive, getHeaders() will preserve the + * exact case in which headers were originally specified. + * + * @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. + */ + public function getHeaders(); + + /** + * Checks if a header exists by the given case-insensitive name. + * + * @param string $name Case-insensitive header field name. + * @return bool Returns true if any header names match the given header + * name using a case-insensitive string comparison. Returns false if + * no matching header name is found in the message. + */ + public function hasHeader($name); + + /** + * Retrieves a message header value by the given case-insensitive name. + * + * This method returns an array of all the header values of the given + * case-insensitive header name. + * + * If the header does not appear in the message, this method MUST return an + * empty array. + * + * @param string $name Case-insensitive header field name. + * @return string[] An array of string values as provided for the given + * header. If the header does not appear in the message, this method MUST + * return an empty array. + */ + public function getHeader($name); + + /** + * Retrieves a comma-separated string of the values for a single header. + * + * This method returns all of the header values of the given + * case-insensitive header name as a string concatenated together using + * a comma. + * + * NOTE: Not all header values may be appropriately represented using + * comma concatenation. For such headers, use getHeader() instead + * and supply your own delimiter when concatenating. + * + * If the header does not appear in the message, this method MUST return + * an empty string. + * + * @param string $name Case-insensitive header field name. + * @return string A string of values as provided for the given header + * concatenated together using a comma. If the header does not appear in + * the message, this method MUST return an empty string. + */ + public function getHeaderLine($name); + + /** + * Return an instance with the provided value replacing the specified header. + * + * While header names are case-insensitive, the casing of the header will + * be preserved by this function, and returned from getHeaders(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new and/or updated header and value. + * + * @param string $name Case-insensitive header field name. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withHeader($name, $value); + + /** + * Return an instance with the specified header appended with the given value. + * + * Existing values for the specified header will be maintained. The new + * value(s) will be appended to the existing list. If the header did not + * exist previously, it will be added. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new header and/or value. + * + * @param string $name Case-insensitive header field name to add. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withAddedHeader($name, $value); + + /** + * Return an instance without the specified header. + * + * Header resolution MUST be done without case-sensitivity. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the named header. + * + * @param string $name Case-insensitive header field name to remove. + * @return static + */ + public function withoutHeader($name); + + /** + * Gets the body of the message. + * + * @return StreamInterface Returns the body as a stream. + */ + public function getBody(); + + /** + * Return an instance with the specified message body. + * + * The body MUST be a StreamInterface object. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return a new instance that has the + * new body stream. + * + * @param StreamInterface $body Body. + * @return static + * @throws \InvalidArgumentException When the body is not valid. + */ + public function withBody(StreamInterface $body); +} diff --git a/plugins/login-oauth2/vendor/psr/http-message/src/RequestInterface.php b/plugins/login-oauth2/vendor/psr/http-message/src/RequestInterface.php new file mode 100644 index 0000000..a96d4fd --- /dev/null +++ b/plugins/login-oauth2/vendor/psr/http-message/src/RequestInterface.php @@ -0,0 +1,129 @@ +getQuery()` + * or from the `QUERY_STRING` server param. + * + * @return array + */ + public function getQueryParams(); + + /** + * Return an instance with the specified query string arguments. + * + * These values SHOULD remain immutable over the course of the incoming + * request. They MAY be injected during instantiation, such as from PHP's + * $_GET superglobal, or MAY be derived from some other value such as the + * URI. In cases where the arguments are parsed from the URI, the data + * MUST be compatible with what PHP's parse_str() would return for + * purposes of how duplicate query parameters are handled, and how nested + * sets are handled. + * + * Setting query string arguments MUST NOT change the URI stored by the + * request, nor the values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated query string arguments. + * + * @param array $query Array of query string arguments, typically from + * $_GET. + * @return static + */ + public function withQueryParams(array $query); + + /** + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @return array An array tree of UploadedFileInterface instances; an empty + * array MUST be returned if no data is present. + */ + public function getUploadedFiles(); + + /** + * Create a new instance with the specified uploaded files. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array $uploadedFiles An array tree of UploadedFileInterface instances. + * @return static + * @throws \InvalidArgumentException if an invalid structure is provided. + */ + public function withUploadedFiles(array $uploadedFiles); + + /** + * Retrieve any parameters provided in the request body. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, this method MUST + * return the contents of $_POST. + * + * Otherwise, this method may return any results of deserializing + * the request body content; as parsing returns structured content, the + * potential types MUST be arrays or objects only. A null value indicates + * the absence of body content. + * + * @return null|array|object The deserialized body parameters, if any. + * These will typically be an array or object. + */ + public function getParsedBody(); + + /** + * Return an instance with the specified body parameters. + * + * These MAY be injected during instantiation. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, use this method + * ONLY to inject the contents of $_POST. + * + * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of + * deserializing the request body content. Deserialization/parsing returns + * structured data, and, as such, this method ONLY accepts arrays or objects, + * or a null value if nothing was available to parse. + * + * As an example, if content negotiation determines that the request data + * is a JSON payload, this method could be used to create a request + * instance with the deserialized parameters. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param null|array|object $data The deserialized body data. This will + * typically be in an array or object. + * @return static + * @throws \InvalidArgumentException if an unsupported argument type is + * provided. + */ + public function withParsedBody($data); + + /** + * Retrieve attributes derived from the request. + * + * The request "attributes" may be used to allow injection of any + * parameters derived from the request: e.g., the results of path + * match operations; the results of decrypting cookies; the results of + * deserializing non-form-encoded message bodies; etc. Attributes + * will be application and request specific, and CAN be mutable. + * + * @return array Attributes derived from the request. + */ + public function getAttributes(); + + /** + * Retrieve a single derived request attribute. + * + * Retrieves a single derived request attribute as described in + * getAttributes(). If the attribute has not been previously set, returns + * the default value as provided. + * + * This method obviates the need for a hasAttribute() method, as it allows + * specifying a default value to return if the attribute is not found. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * @return mixed + */ + public function getAttribute($name, $default = null); + + /** + * Return an instance with the specified derived request attribute. + * + * This method allows setting a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $value The value of the attribute. + * @return static + */ + public function withAttribute($name, $value); + + /** + * Return an instance that removes the specified derived request attribute. + * + * This method allows removing a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @return static + */ + public function withoutAttribute($name); +} diff --git a/plugins/login-oauth2/vendor/psr/http-message/src/StreamInterface.php b/plugins/login-oauth2/vendor/psr/http-message/src/StreamInterface.php new file mode 100644 index 0000000..f68f391 --- /dev/null +++ b/plugins/login-oauth2/vendor/psr/http-message/src/StreamInterface.php @@ -0,0 +1,158 @@ + + * [user-info@]host[:port] + * + * + * If the port component is not set or is the standard port for the current + * scheme, it SHOULD NOT be included. + * + * @see https://tools.ietf.org/html/rfc3986#section-3.2 + * @return string The URI authority, in "[user-info@]host[:port]" format. + */ + public function getAuthority(); + + /** + * Retrieve the user information component of the URI. + * + * If no user information is present, this method MUST return an empty + * string. + * + * If a user is present in the URI, this will return that value; + * additionally, if the password is also present, it will be appended to the + * user value, with a colon (":") separating the values. + * + * The trailing "@" character is not part of the user information and MUST + * NOT be added. + * + * @return string The URI user information, in "username[:password]" format. + */ + public function getUserInfo(); + + /** + * Retrieve the host component of the URI. + * + * If no host is present, this method MUST return an empty string. + * + * The value returned MUST be normalized to lowercase, per RFC 3986 + * Section 3.2.2. + * + * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 + * @return string The URI host. + */ + public function getHost(); + + /** + * Retrieve the port component of the URI. + * + * If a port is present, and it is non-standard for the current scheme, + * this method MUST return it as an integer. If the port is the standard port + * used with the current scheme, this method SHOULD return null. + * + * If no port is present, and no scheme is present, this method MUST return + * a null value. + * + * If no port is present, but a scheme is present, this method MAY return + * the standard port for that scheme, but SHOULD return null. + * + * @return null|int The URI port. + */ + public function getPort(); + + /** + * Retrieve the path component of the URI. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * Normally, the empty path "" and absolute path "/" are considered equal as + * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically + * do this normalization because in contexts with a trimmed base path, e.g. + * the front controller, this difference becomes significant. It's the task + * of the user to handle both "" and "/". + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.3. + * + * As an example, if the value should include a slash ("/") not intended as + * delimiter between path segments, that value MUST be passed in encoded + * form (e.g., "%2F") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.3 + * @return string The URI path. + */ + public function getPath(); + + /** + * Retrieve the query string of the URI. + * + * If no query string is present, this method MUST return an empty string. + * + * The leading "?" character is not part of the query and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.4. + * + * As an example, if a value in a key/value pair of the query string should + * include an ampersand ("&") not intended as a delimiter between values, + * that value MUST be passed in encoded form (e.g., "%26") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.4 + * @return string The URI query string. + */ + public function getQuery(); + + /** + * Retrieve the fragment component of the URI. + * + * If no fragment is present, this method MUST return an empty string. + * + * The leading "#" character is not part of the fragment and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.5. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.5 + * @return string The URI fragment. + */ + public function getFragment(); + + /** + * Return an instance with the specified scheme. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified scheme. + * + * Implementations MUST support the schemes "http" and "https" case + * insensitively, and MAY accommodate other schemes if required. + * + * An empty scheme is equivalent to removing the scheme. + * + * @param string $scheme The scheme to use with the new instance. + * @return static A new instance with the specified scheme. + * @throws \InvalidArgumentException for invalid or unsupported schemes. + */ + public function withScheme($scheme); + + /** + * Return an instance with the specified user information. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified user information. + * + * Password is optional, but the user information MUST include the + * user; an empty string for the user is equivalent to removing user + * information. + * + * @param string $user The user name to use for authority. + * @param null|string $password The password associated with $user. + * @return static A new instance with the specified user information. + */ + public function withUserInfo($user, $password = null); + + /** + * Return an instance with the specified host. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified host. + * + * An empty host value is equivalent to removing the host. + * + * @param string $host The hostname to use with the new instance. + * @return static A new instance with the specified host. + * @throws \InvalidArgumentException for invalid hostnames. + */ + public function withHost($host); + + /** + * Return an instance with the specified port. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified port. + * + * Implementations MUST raise an exception for ports outside the + * established TCP and UDP port ranges. + * + * A null value provided for the port is equivalent to removing the port + * information. + * + * @param null|int $port The port to use with the new instance; a null value + * removes the port information. + * @return static A new instance with the specified port. + * @throws \InvalidArgumentException for invalid ports. + */ + public function withPort($port); + + /** + * Return an instance with the specified path. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified path. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * If the path is intended to be domain-relative rather than path relative then + * it must begin with a slash ("/"). Paths not starting with a slash ("/") + * are assumed to be relative to some base path known to the application or + * consumer. + * + * Users can provide both encoded and decoded path characters. + * Implementations ensure the correct encoding as outlined in getPath(). + * + * @param string $path The path to use with the new instance. + * @return static A new instance with the specified path. + * @throws \InvalidArgumentException for invalid paths. + */ + public function withPath($path); + + /** + * Return an instance with the specified query string. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified query string. + * + * Users can provide both encoded and decoded query characters. + * Implementations ensure the correct encoding as outlined in getQuery(). + * + * 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 static A new instance with the specified query string. + * @throws \InvalidArgumentException for invalid query strings. + */ + public function withQuery($query); + + /** + * Return an instance with the specified URI fragment. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified URI fragment. + * + * Users can provide both encoded and decoded fragment characters. + * Implementations ensure the correct encoding as outlined in getFragment(). + * + * An empty fragment value is equivalent to removing the fragment. + * + * @param string $fragment The fragment to use with the new instance. + * @return static A new instance with the specified fragment. + */ + public function withFragment($fragment); + + /** + * Return the string representation as a URI reference. + * + * Depending on which components of the URI are present, the resulting + * string is either a full URI or relative reference according to RFC 3986, + * Section 4.1. The method concatenates the various components of the URI, + * using the appropriate delimiters: + * + * - If a scheme is present, it MUST be suffixed by ":". + * - If an authority is present, it MUST be prefixed by "//". + * - The path can be concatenated without delimiters. But there are two + * cases where the path has to be adjusted to make the URI reference + * valid as PHP does not allow to throw an exception in __toString(): + * - If the path is rootless and an authority is present, the path MUST + * be prefixed by "/". + * - If the path is starting with more than one "/" and no authority is + * present, the starting slashes MUST be reduced to one. + * - If a query is present, it MUST be prefixed by "?". + * - If a fragment is present, it MUST be prefixed by "#". + * + * @see http://tools.ietf.org/html/rfc3986#section-4.1 + * @return string + */ + public function __toString(); +} diff --git a/plugins/login-oauth2/vendor/ralouphie/getallheaders/LICENSE b/plugins/login-oauth2/vendor/ralouphie/getallheaders/LICENSE new file mode 100644 index 0000000..be5540c --- /dev/null +++ b/plugins/login-oauth2/vendor/ralouphie/getallheaders/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ralph Khattar + +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/plugins/login-oauth2/vendor/ralouphie/getallheaders/README.md b/plugins/login-oauth2/vendor/ralouphie/getallheaders/README.md new file mode 100644 index 0000000..9430d76 --- /dev/null +++ b/plugins/login-oauth2/vendor/ralouphie/getallheaders/README.md @@ -0,0 +1,27 @@ +getallheaders +============= + +PHP `getallheaders()` polyfill. Compatible with PHP >= 5.3. + +[![Build Status](https://travis-ci.org/ralouphie/getallheaders.svg?branch=master)](https://travis-ci.org/ralouphie/getallheaders) +[![Coverage Status](https://coveralls.io/repos/ralouphie/getallheaders/badge.png?branch=master)](https://coveralls.io/r/ralouphie/getallheaders?branch=master) +[![Latest Stable Version](https://poser.pugx.org/ralouphie/getallheaders/v/stable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![Latest Unstable Version](https://poser.pugx.org/ralouphie/getallheaders/v/unstable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![License](https://poser.pugx.org/ralouphie/getallheaders/license.png)](https://packagist.org/packages/ralouphie/getallheaders) + + +This is a simple polyfill for [`getallheaders()`](http://www.php.net/manual/en/function.getallheaders.php). + +## Install + +For PHP version **`>= 5.6`**: + +``` +composer require ralouphie/getallheaders +``` + +For PHP version **`< 5.6`**: + +``` +composer require ralouphie/getallheaders "^2" +``` diff --git a/plugins/login-oauth2/vendor/ralouphie/getallheaders/composer.json b/plugins/login-oauth2/vendor/ralouphie/getallheaders/composer.json new file mode 100644 index 0000000..de8ce62 --- /dev/null +++ b/plugins/login-oauth2/vendor/ralouphie/getallheaders/composer.json @@ -0,0 +1,26 @@ +{ + "name": "ralouphie/getallheaders", + "description": "A polyfill for getallheaders.", + "license": "MIT", + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "require": { + "php": ">=5.6" + }, + "require-dev": { + "phpunit/phpunit": "^5 || ^6.5", + "php-coveralls/php-coveralls": "^2.1" + }, + "autoload": { + "files": ["src/getallheaders.php"] + }, + "autoload-dev": { + "psr-4": { + "getallheaders\\Tests\\": "tests/" + } + } +} diff --git a/plugins/login-oauth2/vendor/ralouphie/getallheaders/src/getallheaders.php b/plugins/login-oauth2/vendor/ralouphie/getallheaders/src/getallheaders.php new file mode 100644 index 0000000..c7285a5 --- /dev/null +++ b/plugins/login-oauth2/vendor/ralouphie/getallheaders/src/getallheaders.php @@ -0,0 +1,46 @@ + 'Content-Type', + 'CONTENT_LENGTH' => 'Content-Length', + 'CONTENT_MD5' => 'Content-Md5', + ); + + foreach ($_SERVER as $key => $value) { + if (substr($key, 0, 5) === 'HTTP_') { + $key = substr($key, 5); + if (!isset($copy_server[$key]) || !isset($_SERVER[$key])) { + $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $key)))); + $headers[$key] = $value; + } + } elseif (isset($copy_server[$key])) { + $headers[$copy_server[$key]] = $value; + } + } + + if (!isset($headers['Authorization'])) { + if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { + $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; + } elseif (isset($_SERVER['PHP_AUTH_USER'])) { + $basic_pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; + $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $basic_pass); + } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) { + $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST']; + } + } + + return $headers; + } + +} diff --git a/plugins/login-oauth2/vendor/symfony/deprecation-contracts/.gitignore b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/.gitignore new file mode 100644 index 0000000..c49a5d8 --- /dev/null +++ b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/.gitignore @@ -0,0 +1,3 @@ +vendor/ +composer.lock +phpunit.xml diff --git a/plugins/login-oauth2/vendor/symfony/deprecation-contracts/CHANGELOG.md b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/CHANGELOG.md new file mode 100644 index 0000000..7932e26 --- /dev/null +++ b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/CHANGELOG.md @@ -0,0 +1,5 @@ +CHANGELOG +========= + +The changelog is maintained for all Symfony contracts at the following URL: +https://github.com/symfony/contracts/blob/main/CHANGELOG.md diff --git a/plugins/login-oauth2/vendor/symfony/deprecation-contracts/LICENSE b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/LICENSE new file mode 100644 index 0000000..406242f --- /dev/null +++ b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020-2022 Fabien Potencier + +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/plugins/login-oauth2/vendor/symfony/deprecation-contracts/README.md b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/README.md new file mode 100644 index 0000000..4957933 --- /dev/null +++ b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/README.md @@ -0,0 +1,26 @@ +Symfony Deprecation Contracts +============================= + +A generic function and convention to trigger deprecation notices. + +This package provides a single global function named `trigger_deprecation()` that triggers silenced deprecation notices. + +By using a custom PHP error handler such as the one provided by the Symfony ErrorHandler component, +the triggered deprecations can be caught and logged for later discovery, both on dev and prod environments. + +The function requires at least 3 arguments: + - the name of the Composer package that is triggering the deprecation + - the version of the package that introduced the deprecation + - the message of the deprecation + - more arguments can be provided: they will be inserted in the message using `printf()` formatting + +Example: +```php +trigger_deprecation('symfony/blockchain', '8.9', 'Using "%s" is deprecated, use "%s" instead.', 'bitcoin', 'fabcoin'); +``` + +This will generate the following message: +`Since symfony/blockchain 8.9: Using "bitcoin" is deprecated, use "fabcoin" instead.` + +While not necessarily recommended, the deprecation notices can be completely ignored by declaring an empty +`function trigger_deprecation() {}` in your application. diff --git a/plugins/login-oauth2/vendor/symfony/deprecation-contracts/composer.json b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/composer.json new file mode 100644 index 0000000..cc7cc12 --- /dev/null +++ b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/composer.json @@ -0,0 +1,35 @@ +{ + "name": "symfony/deprecation-contracts", + "type": "library", + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "2.5-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + } +} diff --git a/plugins/login-oauth2/vendor/symfony/deprecation-contracts/function.php b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/function.php new file mode 100644 index 0000000..d437150 --- /dev/null +++ b/plugins/login-oauth2/vendor/symfony/deprecation-contracts/function.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (!function_exists('trigger_deprecation')) { + /** + * Triggers a silenced deprecation notice. + * + * @param string $package The name of the Composer package that is triggering the deprecation + * @param string $version The version of the package that introduced the deprecation + * @param string $message The message of the deprecation + * @param mixed ...$args Values to insert in the message using printf() formatting + * + * @author Nicolas Grekas + */ + function trigger_deprecation(string $package, string $version, string $message, ...$args): void + { + @trigger_error(($package || $version ? "Since $package $version: " : '').($args ? vsprintf($message, $args) : $message), \E_USER_DEPRECATED); + } +} diff --git a/plugins/login-oauth2/watch.sh b/plugins/login-oauth2/watch.sh new file mode 100644 index 0000000..0432a1c --- /dev/null +++ b/plugins/login-oauth2/watch.sh @@ -0,0 +1,27 @@ +#!/bin/sh + +# +# Configuration +# + +# sass source + +SASS_SOURCE_PATH="scss" + +# sass options +SASS_OPTIONS="--source-map=false --style=nested" + +# css target +CSS_TARGET_PATH="css" + +# +# Check prerequisites +# +wtfile=$(command -v wt) || { echo "install wellington with 'brew install wellington"; exit 1; } + +# +# Watch folder for changes +# +cd -P `pwd` +$wtfile compile "$SASS_SOURCE_PATH" -b "$CSS_TARGET_PATH" $SASS_OPTIONS +$wtfile watch "$SASS_SOURCE_PATH" -b "$CSS_TARGET_PATH" $SASS_OPTIONS \ No newline at end of file