Server IP : 213.176.29.180 / Your IP : 3.145.70.108 Web Server : Apache System : Linux 213.176.29.180.hostiran.name 4.18.0-553.22.1.el8_10.x86_64 #1 SMP Tue Sep 24 05:16:59 EDT 2024 x86_64 User : webtaragh ( 1001) PHP Version : 8.3.14 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON Directory (0750) : /home/webtaragh/public_html/ |
[ Home ] | [ C0mmand ] | [ Upload File ] |
---|
PK gF'Z[쉱� � recaptcha/CONTRIBUTING.mdnu �[��� # Contributing Want to contribute? Great! First, read this page (including the small print at the end). ## Contributor License Agreement Before we can use your code, you must sign the [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1) (CLA), which you can do online. The CLA is necessary mainly because you own the copyright to your changes, even after your contribution becomes part of our codebase, so we need your permission to use and distribute your code. We also need to be sure of various other things—for instance that you'll tell us if you know that your code infringes on other people's patents. You don't have to sign the CLA until after you've submitted your code for review (a link will be automatically added to your Pull Request) and a member has approved it, but you must do it before we can put your code into our codebase. Before you start working on a larger contribution, you should get in touch with us first through the issue tracker with your idea so that we can help out and possibly guide you. Coordinating up front makes it much easier to avoid frustration later on. ## Linting and testing We use PHP Coding Standards Fixer to maintain coding standards and PHPUnit to run our tests. For convenience, there are Composer scripts to run each of these: ```sh composer run-script lint composer run-script test ``` These are run automatically by [Travis CI](https://travis-ci.org/google/recaptcha) against your Pull Request, but it's a good idea to run them locally before submission to avoid getting things bounced back. That said, tests can be a little daunting so feel free to submit your PR and ask for help. ## Code reviews All submissions, including submissions by project members, require review. Reviews are conducted on the Pull Requests. The reviews are there to ensure and improve code quality, so treat them like a discussion and opportunity to learn. Don't get disheartened if your Pull Request isn't just automatically approved. ### The small print Contributions made by corporations are covered by a different agreement than the one above, the Software Grant and Corporate Contributor License Agreement. PK gF'Z �9 recaptcha/src/autoload.phpnu �[��� <?php /* An autoloader for ReCaptcha\Foo classes. This should be required() * by the user before attempting to instantiate any of the ReCaptcha * classes. * * BSD 3-Clause License * @copyright (c) 2019, Google Inc. * @link https://www.google.com/recaptcha * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder nor the names of its * 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 HOLDER 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. */ spl_autoload_register(function ($class) { if (substr($class, 0, 10) !== 'ReCaptcha\\') { /* If the class does not lie under the "ReCaptcha" namespace, * then we can exit immediately. */ return; } /* All of the classes have names like "ReCaptcha\Foo", so we need * to replace the backslashes with frontslashes if we want the * name to map directly to a location in the filesystem. */ $class = str_replace('\\', '/', $class); /* First, check under the current directory. It is important that * we look here first, so that we don't waste time searching for * test classes in the common case. */ $path = dirname(__FILE__).'/'.$class.'.php'; if (is_readable($path)) { require_once $path; return; } /* If we didn't find what we're looking for already, maybe it's * a test class? */ $path = dirname(__FILE__).'/../tests/'.$class.'.php'; if (is_readable($path)) { require_once $path; } }); PK gF'Z����� � $ recaptcha/src/ReCaptcha/Response.phpnu �[��� <?php /** * This is a PHP library that handles calling reCAPTCHA. * * BSD 3-Clause License * @copyright (c) 2019, Google Inc. * @link https://www.google.com/recaptcha * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder nor the names of its * 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 HOLDER 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. */ namespace ReCaptcha; /** * The response returned from the service. */ class Response { /** * Success or failure. * @var boolean */ private $success = false; /** * Error code strings. * @var array */ private $errorCodes = array(); /** * The hostname of the site where the reCAPTCHA was solved. * @var string */ private $hostname; /** * Timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ) * @var string */ private $challengeTs; /** * APK package name * @var string */ private $apkPackageName; /** * Score assigned to the request * @var float */ private $score; /** * Action as specified by the page * @var string */ private $action; /** * Build the response from the expected JSON returned by the service. * * @param string $json * @return \ReCaptcha\Response */ public static function fromJson($json) { $responseData = json_decode($json, true); if (!$responseData) { return new Response(false, array(ReCaptcha::E_INVALID_JSON)); } $hostname = isset($responseData['hostname']) ? $responseData['hostname'] : null; $challengeTs = isset($responseData['challenge_ts']) ? $responseData['challenge_ts'] : null; $apkPackageName = isset($responseData['apk_package_name']) ? $responseData['apk_package_name'] : null; $score = isset($responseData['score']) ? floatval($responseData['score']) : null; $action = isset($responseData['action']) ? $responseData['action'] : null; if (isset($responseData['success']) && $responseData['success'] == true) { return new Response(true, array(), $hostname, $challengeTs, $apkPackageName, $score, $action); } if (isset($responseData['error-codes']) && is_array($responseData['error-codes'])) { return new Response(false, $responseData['error-codes'], $hostname, $challengeTs, $apkPackageName, $score, $action); } return new Response(false, array(ReCaptcha::E_UNKNOWN_ERROR), $hostname, $challengeTs, $apkPackageName, $score, $action); } /** * Constructor. * * @param boolean $success * @param string $hostname * @param string $challengeTs * @param string $apkPackageName * @param float $score * @param string $action * @param array $errorCodes */ public function __construct($success, array $errorCodes = array(), $hostname = null, $challengeTs = null, $apkPackageName = null, $score = null, $action = null) { $this->success = $success; $this->hostname = $hostname; $this->challengeTs = $challengeTs; $this->apkPackageName = $apkPackageName; $this->score = $score; $this->action = $action; $this->errorCodes = $errorCodes; } /** * Is success? * * @return boolean */ public function isSuccess() { return $this->success; } /** * Get error codes. * * @return array */ public function getErrorCodes() { return $this->errorCodes; } /** * Get hostname. * * @return string */ public function getHostname() { return $this->hostname; } /** * Get challenge timestamp * * @return string */ public function getChallengeTs() { return $this->challengeTs; } /** * Get APK package name * * @return string */ public function getApkPackageName() { return $this->apkPackageName; } /** * Get score * * @return float */ public function getScore() { return $this->score; } /** * Get action * * @return string */ public function getAction() { return $this->action; } public function toArray() { return array( 'success' => $this->isSuccess(), 'hostname' => $this->getHostname(), 'challenge_ts' => $this->getChallengeTs(), 'apk_package_name' => $this->getApkPackageName(), 'score' => $this->getScore(), 'action' => $this->getAction(), 'error-codes' => $this->getErrorCodes(), ); } } PK gF'Z�x�K ) recaptcha/src/ReCaptcha/RequestMethod.phpnu �[��� <?php /** * This is a PHP library that handles calling reCAPTCHA. * * BSD 3-Clause License * @copyright (c) 2019, Google Inc. * @link https://www.google.com/recaptcha * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder nor the names of its * 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 HOLDER 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. */ namespace ReCaptcha; /** * Method used to send the request to the service. */ interface RequestMethod { /** * Submit the request with the specified parameters. * * @param RequestParameters $params Request parameters * @return string Body of the reCAPTCHA response */ public function submit(RequestParameters $params); } PK gF'Z��� � - recaptcha/src/ReCaptcha/RequestParameters.phpnu �[��� <?php /** * This is a PHP library that handles calling reCAPTCHA. * * BSD 3-Clause License * @copyright (c) 2019, Google Inc. * @link https://www.google.com/recaptcha * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder nor the names of its * 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 HOLDER 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. */ namespace ReCaptcha; /** * Stores and formats the parameters for the request to the reCAPTCHA service. */ class RequestParameters { /** * The shared key between your site and reCAPTCHA. * @var string */ private $secret; /** * The user response token provided by reCAPTCHA, verifying the user on your site. * @var string */ private $response; /** * Remote user's IP address. * @var string */ private $remoteIp; /** * Client version. * @var string */ private $version; /** * Initialise parameters. * * @param string $secret Site secret. * @param string $response Value from g-captcha-response form field. * @param string $remoteIp User's IP address. * @param string $version Version of this client library. */ public function __construct($secret, $response, $remoteIp = null, $version = null) { $this->secret = $secret; $this->response = $response; $this->remoteIp = $remoteIp; $this->version = $version; } /** * Array representation. * * @return array Array formatted parameters. */ public function toArray() { $params = array('secret' => $this->secret, 'response' => $this->response); if (!is_null($this->remoteIp)) { $params['remoteip'] = $this->remoteIp; } if (!is_null($this->version)) { $params['version'] = $this->version; } return $params; } /** * Query string representation for HTTP request. * * @return string Query string formatted parameters. */ public function toQueryString() { return http_build_query($this->toArray(), '', '&'); } } PK gF'Z�|`� � 2 recaptcha/src/ReCaptcha/RequestMethod/CurlPost.phpnu �[��� <?php /** * This is a PHP library that handles calling reCAPTCHA. * * BSD 3-Clause License * @copyright (c) 2019, Google Inc. * @link https://www.google.com/recaptcha * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder nor the names of its * 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 HOLDER 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. */ namespace ReCaptcha\RequestMethod; use ReCaptcha\ReCaptcha; use ReCaptcha\RequestMethod; use ReCaptcha\RequestParameters; /** * Sends cURL request to the reCAPTCHA service. * Note: this requires the cURL extension to be enabled in PHP * @see http://php.net/manual/en/book.curl.php */ class CurlPost implements RequestMethod { /** * Curl connection to the reCAPTCHA service * @var Curl */ private $curl; /** * URL for reCAPTCHA siteverify API * @var string */ private $siteVerifyUrl; /** * Only needed if you want to override the defaults * * @param Curl $curl Curl resource * @param string $siteVerifyUrl URL for reCAPTCHA siteverify API */ public function __construct(Curl $curl = null, $siteVerifyUrl = null) { $this->curl = (is_null($curl)) ? new Curl() : $curl; $this->siteVerifyUrl = (is_null($siteVerifyUrl)) ? ReCaptcha::SITE_VERIFY_URL : $siteVerifyUrl; } /** * Submit the cURL request with the specified parameters. * * @param RequestParameters $params Request parameters * @return string Body of the reCAPTCHA response */ public function submit(RequestParameters $params) { $handle = $this->curl->init($this->siteVerifyUrl); $options = array( CURLOPT_POST => true, CURLOPT_POSTFIELDS => $params->toQueryString(), CURLOPT_HTTPHEADER => array( 'Content-Type: application/x-www-form-urlencoded' ), CURLINFO_HEADER_OUT => false, CURLOPT_HEADER => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => true ); $this->curl->setoptArray($handle, $options); $response = $this->curl->exec($handle); $this->curl->close($handle); if ($response !== false) { return $response; } return '{"success": false, "error-codes": ["'.ReCaptcha::E_CONNECTION_FAILED.'"]}'; } } PK gF'Z�^ 4 recaptcha/src/ReCaptcha/RequestMethod/SocketPost.phpnu �[��� <?php /** * This is a PHP library that handles calling reCAPTCHA. * * BSD 3-Clause License * @copyright (c) 2019, Google Inc. * @link https://www.google.com/recaptcha * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder nor the names of its * 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 HOLDER 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. */ namespace ReCaptcha\RequestMethod; use ReCaptcha\ReCaptcha; use ReCaptcha\RequestMethod; use ReCaptcha\RequestParameters; /** * Sends a POST request to the reCAPTCHA service, but makes use of fsockopen() * instead of get_file_contents(). This is to account for people who may be on * servers where allow_url_open is disabled. */ class SocketPost implements RequestMethod { /** * Socket to the reCAPTCHA service * @var Socket */ private $socket; /** * Only needed if you want to override the defaults * * @param \ReCaptcha\RequestMethod\Socket $socket optional socket, injectable for testing * @param string $siteVerifyUrl URL for reCAPTCHA siteverify API */ public function __construct(Socket $socket = null, $siteVerifyUrl = null) { $this->socket = (is_null($socket)) ? new Socket() : $socket; $this->siteVerifyUrl = (is_null($siteVerifyUrl)) ? ReCaptcha::SITE_VERIFY_URL : $siteVerifyUrl; } /** * Submit the POST request with the specified parameters. * * @param RequestParameters $params Request parameters * @return string Body of the reCAPTCHA response */ public function submit(RequestParameters $params) { $errno = 0; $errstr = ''; $urlParsed = parse_url($this->siteVerifyUrl); if (false === $this->socket->fsockopen('ssl://' . $urlParsed['host'], 443, $errno, $errstr, 30)) { return '{"success": false, "error-codes": ["'.ReCaptcha::E_CONNECTION_FAILED.'"]}'; } $content = $params->toQueryString(); $request = "POST " . $urlParsed['path'] . " HTTP/1.0\r\n"; $request .= "Host: " . $urlParsed['host'] . "\r\n"; $request .= "Content-Type: application/x-www-form-urlencoded\r\n"; $request .= "Content-length: " . strlen($content) . "\r\n"; $request .= "Connection: close\r\n\r\n"; $request .= $content . "\r\n\r\n"; $this->socket->fwrite($request); $response = ''; while (!$this->socket->feof()) { $response .= $this->socket->fgets(4096); } $this->socket->fclose(); if (0 !== strpos($response, 'HTTP/1.0 200 OK')) { return '{"success": false, "error-codes": ["'.ReCaptcha::E_BAD_RESPONSE.'"]}'; } $parts = preg_split("#\n\s*\n#Uis", $response); return $parts[1]; } } PK gF'Z�L��4 4 0 recaptcha/src/ReCaptcha/RequestMethod/Socket.phpnu �[��� <?php /** * This is a PHP library that handles calling reCAPTCHA. * * BSD 3-Clause License * @copyright (c) 2019, Google Inc. * @link https://www.google.com/recaptcha * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder nor the names of its * 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 HOLDER 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. */ namespace ReCaptcha\RequestMethod; /** * Convenience wrapper around native socket and file functions to allow for * mocking. */ class Socket { private $handle = null; /** * fsockopen * * @see http://php.net/fsockopen * @param string $hostname * @param int $port * @param int $errno * @param string $errstr * @param float $timeout * @return resource */ public function fsockopen($hostname, $port = -1, &$errno = 0, &$errstr = '', $timeout = null) { $this->handle = fsockopen($hostname, $port, $errno, $errstr, (is_null($timeout) ? ini_get("default_socket_timeout") : $timeout)); if ($this->handle != false && $errno === 0 && $errstr === '') { return $this->handle; } return false; } /** * fwrite * * @see http://php.net/fwrite * @param string $string * @param int $length * @return int | bool */ public function fwrite($string, $length = null) { return fwrite($this->handle, $string, (is_null($length) ? strlen($string) : $length)); } /** * fgets * * @see http://php.net/fgets * @param int $length * @return string */ public function fgets($length = null) { return fgets($this->handle, $length); } /** * feof * * @see http://php.net/feof * @return bool */ public function feof() { return feof($this->handle); } /** * fclose * * @see http://php.net/fclose * @return bool */ public function fclose() { return fclose($this->handle); } } PK gF'Z����5 5 . recaptcha/src/ReCaptcha/RequestMethod/Curl.phpnu �[��� <?php /** * This is a PHP library that handles calling reCAPTCHA. * * BSD 3-Clause License * @copyright (c) 2019, Google Inc. * @link https://www.google.com/recaptcha * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder nor the names of its * 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 HOLDER 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. */ namespace ReCaptcha\RequestMethod; /** * Convenience wrapper around the cURL functions to allow mocking. */ class Curl { /** * @see http://php.net/curl_init * @param string $url * @return resource cURL handle */ public function init($url = null) { return curl_init($url); } /** * @see http://php.net/curl_setopt_array * @param resource $ch * @param array $options * @return bool */ public function setoptArray($ch, array $options) { return curl_setopt_array($ch, $options); } /** * @see http://php.net/curl_exec * @param resource $ch * @return mixed */ public function exec($ch) { return curl_exec($ch); } /** * @see http://php.net/curl_close * @param resource $ch */ public function close($ch) { curl_close($ch); } } PK gF'Z�-؋� � . recaptcha/src/ReCaptcha/RequestMethod/Post.phpnu �[��� <?php /** * This is a PHP library that handles calling reCAPTCHA. * * BSD 3-Clause License * @copyright (c) 2019, Google Inc. * @link https://www.google.com/recaptcha * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder nor the names of its * 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 HOLDER 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. */ namespace ReCaptcha\RequestMethod; use ReCaptcha\ReCaptcha; use ReCaptcha\RequestMethod; use ReCaptcha\RequestParameters; /** * Sends POST requests to the reCAPTCHA service. */ class Post implements RequestMethod { /** * URL for reCAPTCHA siteverify API * @var string */ private $siteVerifyUrl; /** * Only needed if you want to override the defaults * * @param string $siteVerifyUrl URL for reCAPTCHA siteverify API */ public function __construct($siteVerifyUrl = null) { $this->siteVerifyUrl = (is_null($siteVerifyUrl)) ? ReCaptcha::SITE_VERIFY_URL : $siteVerifyUrl; } /** * Submit the POST request with the specified parameters. * * @param RequestParameters $params Request parameters * @return string Body of the reCAPTCHA response */ public function submit(RequestParameters $params) { $options = array( 'http' => array( 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => $params->toQueryString(), // Force the peer to validate (not needed in 5.6.0+, but still works) 'verify_peer' => true, ), ); $context = stream_context_create($options); $response = file_get_contents($this->siteVerifyUrl, false, $context); if ($response !== false) { return $response; } return '{"success": false, "error-codes": ["'.ReCaptcha::E_CONNECTION_FAILED.'"]}'; } } PK gF'ZC3���! �! % recaptcha/src/ReCaptcha/ReCaptcha.phpnu �[��� <?php /** * This is a PHP library that handles calling reCAPTCHA. * * BSD 3-Clause License * @copyright (c) 2019, Google Inc. * @link https://www.google.com/recaptcha * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder nor the names of its * 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 HOLDER 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. */ namespace ReCaptcha; /** * reCAPTCHA client. */ class ReCaptcha { /** * Version of this client library. * @const string */ const VERSION = 'php_1.2.4'; /** * URL for reCAPTCHA siteverify API * @const string */ const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify'; /** * Invalid JSON received * @const string */ const E_INVALID_JSON = 'invalid-json'; /** * Could not connect to service * @const string */ const E_CONNECTION_FAILED = 'connection-failed'; /** * Did not receive a 200 from the service * @const string */ const E_BAD_RESPONSE = 'bad-response'; /** * Not a success, but no error codes received! * @const string */ const E_UNKNOWN_ERROR = 'unknown-error'; /** * ReCAPTCHA response not provided * @const string */ const E_MISSING_INPUT_RESPONSE = 'missing-input-response'; /** * Expected hostname did not match * @const string */ const E_HOSTNAME_MISMATCH = 'hostname-mismatch'; /** * Expected APK package name did not match * @const string */ const E_APK_PACKAGE_NAME_MISMATCH = 'apk_package_name-mismatch'; /** * Expected action did not match * @const string */ const E_ACTION_MISMATCH = 'action-mismatch'; /** * Score threshold not met * @const string */ const E_SCORE_THRESHOLD_NOT_MET = 'score-threshold-not-met'; /** * Challenge timeout * @const string */ const E_CHALLENGE_TIMEOUT = 'challenge-timeout'; /** * Shared secret for the site. * @var string */ private $secret; /** * Method used to communicate with service. Defaults to POST request. * @var RequestMethod */ private $requestMethod; /** * Create a configured instance to use the reCAPTCHA service. * * @param string $secret The shared key between your site and reCAPTCHA. * @param RequestMethod $requestMethod method used to send the request. Defaults to POST. * @throws \RuntimeException if $secret is invalid */ public function __construct($secret, RequestMethod $requestMethod = null) { if (empty($secret)) { throw new \RuntimeException('No secret provided'); } if (!is_string($secret)) { throw new \RuntimeException('The provided secret must be a string'); } $this->secret = $secret; $this->requestMethod = (is_null($requestMethod)) ? new RequestMethod\Post() : $requestMethod; } /** * Calls the reCAPTCHA siteverify API to verify whether the user passes * CAPTCHA test and additionally runs any specified additional checks * * @param string $response The user response token provided by reCAPTCHA, verifying the user on your site. * @param string $remoteIp The end user's IP address. * @return Response Response from the service. */ public function verify($response, $remoteIp = null) { // Discard empty solution submissions if (empty($response)) { $recaptchaResponse = new Response(false, array(self::E_MISSING_INPUT_RESPONSE)); return $recaptchaResponse; } $params = new RequestParameters($this->secret, $response, $remoteIp, self::VERSION); $rawResponse = $this->requestMethod->submit($params); $initialResponse = Response::fromJson($rawResponse); $validationErrors = array(); if (isset($this->hostname) && strcasecmp($this->hostname, $initialResponse->getHostname()) !== 0) { $validationErrors[] = self::E_HOSTNAME_MISMATCH; } if (isset($this->apkPackageName) && strcasecmp($this->apkPackageName, $initialResponse->getApkPackageName()) !== 0) { $validationErrors[] = self::E_APK_PACKAGE_NAME_MISMATCH; } if (isset($this->action) && strcasecmp($this->action, $initialResponse->getAction()) !== 0) { $validationErrors[] = self::E_ACTION_MISMATCH; } if (isset($this->threshold) && $this->threshold > $initialResponse->getScore()) { $validationErrors[] = self::E_SCORE_THRESHOLD_NOT_MET; } if (isset($this->timeoutSeconds)) { $challengeTs = strtotime($initialResponse->getChallengeTs()); if ($challengeTs > 0 && time() - $challengeTs > $this->timeoutSeconds) { $validationErrors[] = self::E_CHALLENGE_TIMEOUT; } } if (empty($validationErrors)) { return $initialResponse; } return new Response( false, array_merge($initialResponse->getErrorCodes(), $validationErrors), $initialResponse->getHostname(), $initialResponse->getChallengeTs(), $initialResponse->getApkPackageName(), $initialResponse->getScore(), $initialResponse->getAction() ); } /** * Provide a hostname to match against in verify() * This should be without a protocol or trailing slash, e.g. www.google.com * * @param string $hostname Expected hostname * @return ReCaptcha Current instance for fluent interface */ public function setExpectedHostname($hostname) { $this->hostname = $hostname; return $this; } /** * Provide an APK package name to match against in verify() * * @param string $apkPackageName Expected APK package name * @return ReCaptcha Current instance for fluent interface */ public function setExpectedApkPackageName($apkPackageName) { $this->apkPackageName = $apkPackageName; return $this; } /** * Provide an action to match against in verify() * This should be set per page. * * @param string $action Expected action * @return ReCaptcha Current instance for fluent interface */ public function setExpectedAction($action) { $this->action = $action; return $this; } /** * Provide a threshold to meet or exceed in verify() * Threshold should be a float between 0 and 1 which will be tested as response >= threshold. * * @param float $threshold Expected threshold * @return ReCaptcha Current instance for fluent interface */ public function setScoreThreshold($threshold) { $this->threshold = floatval($threshold); return $this; } /** * Provide a timeout in seconds to test against the challenge timestamp in verify() * * @param int $timeoutSeconds Expected hostname * @return ReCaptcha Current instance for fluent interface */ public function setChallengeTimeout($timeoutSeconds) { $this->timeoutSeconds = $timeoutSeconds; return $this; } } PK gF'Z���h� � recaptcha/ARCHITECTURE.mdnu �[��� # Architecture The general pattern of usage is to instantiate the `ReCaptcha` class with your secret key, specify any additional validation rules, and then call `verify()` with the reCAPTCHA response and user's IP address. For example: ```php <?php $recaptcha = new \ReCaptcha\ReCaptcha($secret); $resp = $recaptcha->setExpectedHostname('recaptcha-demo.appspot.com') ->verify($gRecaptchaResponse, $remoteIp); if ($resp->isSuccess()) { // Verified! } else { $errors = $resp->getErrorCodes(); } ``` By default, this will use the [`stream_context_create()`](https://secure.php.net/stream_context_create) and [`file_get_contents()`](https://secure.php.net/file_get_contents) to make a POST request to the reCAPTCHA service. This is handled by the [`RequestMethod\Post`](./src/ReCaptcha/RequestMethod/Post.php) class. ## Alternate request methods You may need to use other methods for making requests in your environment. The [`ReCaptcha`](./src/ReCaptcha/ReCaptcha.php) class allows an optional [`RequestMethod`](./src/ReCaptcha/RequestMethod.php) instance to configure this. For example, if you want to use [cURL](https://secure.php.net/curl) instead you can do this: ```php <?php $recaptcha = new \ReCaptcha\ReCaptcha($secret, new \ReCaptcha\RequestMethod\CurlPost()); ``` Alternatively, you can also use a [socket](https://secure.php.net/fsockopen): ```php <?php $recaptcha = new \ReCaptcha\ReCaptcha($secret, new \ReCaptcha\RequestMethod\SocketPost()); ``` ## Adding new request methods Create a class that implements the [`RequestMethod`](./src/ReCaptcha/RequestMethod.php) interface. The convention is to name this class `RequestMethod\`_MethodType_`Post` and create a separate `RequestMethod\`_MethodType_ class that wraps just the calls to the network calls themselves. This means that the `RequestMethod\`_MethodType_`Post` can be unit tested by passing in a mock. Take a look at [`RequestMethod\CurlPost`](./src/ReCaptcha/RequestMethod/CurlPost.php) and [`RequestMethod\Curl`](./src/ReCaptcha/RequestMethod/Curl.php) with the matching [`RequestMethod/CurlPostTest`](./tests/ReCaptcha/RequestMethod/CurlPostTest.php) to see this pattern in action. ### Error conventions The client returns the response as provided by the reCAPTCHA services augmented with additional error codes based on the client's checks. When adding a new [`RequestMethod`](./src/ReCaptcha/RequestMethod.php) ensure that it returns the `ReCaptcha::E_CONNECTION_FAILED` and `ReCaptcha::E_BAD_RESPONSE` where appropriate. PK gF'Z�2��� � recaptcha/README.mdnu �[��� # reCAPTCHA PHP client library [![Build Status](https://travis-ci.org/google/recaptcha.svg)](https://travis-ci.org/google/recaptcha) [![Coverage Status](https://coveralls.io/repos/github/google/recaptcha/badge.svg)](https://coveralls.io/github/google/recaptcha) [![Latest Stable Version](https://poser.pugx.org/google/recaptcha/v/stable.svg)](https://packagist.org/packages/google/recaptcha) [![Total Downloads](https://poser.pugx.org/google/recaptcha/downloads.svg)](https://packagist.org/packages/google/recaptcha) reCAPTCHA is a free CAPTCHA service that protects websites from spam and abuse. This is a PHP library that wraps up the server-side verification step required to process responses from the reCAPTCHA service. This client supports both v2 and v3. - reCAPTCHA: https://www.google.com/recaptcha - This repo: https://github.com/google/recaptcha - Hosted demo: https://recaptcha-demo.appspot.com/ - Version: 1.2.4 - License: BSD, see [LICENSE](LICENSE) ## Installation ### Composer (recommended) Use [Composer](https://getcomposer.org) to install this library from Packagist: [`google/recaptcha`](https://packagist.org/packages/google/recaptcha) Run the following command from your project directory to add the dependency: ```sh composer require google/recaptcha "^1.2" ``` Alternatively, add the dependency directly to your `composer.json` file: ```json "require": { "google/recaptcha": "^1.2" } ``` ### Direct download Download the [ZIP file](https://github.com/google/recaptcha/archive/master.zip) and extract into your project. An autoloader script is provided in `src/autoload.php` which you can require into your script. For example: ```php require_once '/path/to/recaptcha/src/autoload.php'; $recaptcha = new \ReCaptcha\ReCaptcha($secret); ``` The classes in the project are structured according to the [PSR-4](http://www.php-fig.org/psr/psr-4/) standard, so you can also use your own autoloader or require the needed files directly in your code. ## Usage First obtain the appropriate keys for the type of reCAPTCHA you wish to integrate for v2 at https://www.google.com/recaptcha/admin or v3 at https://g.co/recaptcha/v3. Then follow the [integration guide on the developer site](https://developers.google.com/recaptcha/intro) to add the reCAPTCHA functionality into your frontend. This library comes in when you need to verify the user's response. On the PHP side you need the response from the reCAPTCHA service and secret key from your credentials. Instantiate the `ReCaptcha` class with your secret key, specify any additional validation rules, and then call `verify()` with the reCAPTCHA response and user's IP address. For example: ```php <?php $recaptcha = new \ReCaptcha\ReCaptcha($secret); $resp = $recaptcha->setExpectedHostname('recaptcha-demo.appspot.com') ->verify($gRecaptchaResponse, $remoteIp); if ($resp->isSuccess()) { // Verified! } else { $errors = $resp->getErrorCodes(); } ``` The following methods are available: - `setExpectedHostname($hostname)`: ensures the hostname matches. You must do this if you have disabled "Domain/Package Name Validation" for your credentials. - `setExpectedApkPackageName($apkPackageName)`: if you're verifying a response from an Android app. Again, you must do this if you have disabled "Domain/Package Name Validation" for your credentials. - `setExpectedAction($action)`: ensures the action matches for the v3 API. - `setScoreThreshold($threshold)`: set a score threshold for responses from the v3 API - `setChallengeTimeout($timeoutSeconds)`: set a timeout between the user passing the reCAPTCHA and your server processing it. Each of the `set`\*`()` methods return the `ReCaptcha` instance so you can chain them together. For example: ```php <?php $recaptcha = new \ReCaptcha\ReCaptcha($secret); $resp = $recaptcha->setExpectedHostname('recaptcha-demo.appspot.com') ->setExpectedAction('homepage') ->setScoreThreshold(0.5) ->verify($gRecaptchaResponse, $remoteIp); if ($resp->isSuccess()) { // Verified! } else { $errors = $resp->getErrorCodes(); } ``` You can find the constants for the libraries error codes in the `ReCaptcha` class constants, e.g. `ReCaptcha::E_HOSTNAME_MISMATCH` For more details on usage and structure, see [ARCHITECTURE](ARCHITECTURE.md). ### Examples You can see examples of each reCAPTCHA type in [examples/](examples/). You can run the examples locally by using the Composer script: ```sh composer run-script serve-examples ``` This makes use of the in-built PHP dev server to host the examples at http://localhost:8080/ These are also hosted on Google AppEngine Flexible environment at https://recaptcha-demo.appspot.com/. This is configured by [`app.yaml`](./app.yaml) which you can also use to [deploy to your own AppEngine project](https://cloud.google.com/appengine/docs/flexible/php/download). ## Contributing No one ever has enough engineers, so we're very happy to accept contributions via Pull Requests. For details, see [CONTRIBUTING](CONTRIBUTING.md) PK gF'Z��'� � recaptcha/LICENSEnu �[��� BSD 3-Clause License Copyright (c) 2019, Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder nor the names of its 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 HOLDER 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. PK gF'ZEȿZW W recaptcha/app.yamlnu �[��� runtime: php env: flex skip_files: - tests runtime_config: document_root: examples PK gF'Z�B� apiclient/CONTRIBUTING.mdnu �[��� # How to become a contributor and submit your own code ## Contributor License Agreements We'd love to accept your code patches! However, before we can take them, we have to jump a couple of legal hurdles. Please fill out either the individual or corporate Contributor License Agreement (CLA). * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html). * If you work for a company that wants to allow you to contribute your work to this client library, then you'll need to sign a[corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html). Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll add you to the official list of contributors and be able to accept your patches. ## Submitting Patches 1. Fork the PHP client library on GitHub 1. Decide which code you want to submit. A submission should be a set of changes that addresses one issue in the issue tracker. Please file one change per issue, and address one issue per change. If you want to make a change that doesn't have a corresponding issue in the issue tracker, please file a new ticket! 1. Ensure that your code adheres to standard PHP conventions, as used in the rest of the library. 1. Ensure that there are unit tests for your code. 1. Sign a Contributor License Agreement (see above). 1. Submit a pull request with your patch on Github. PK gF'Z�~�ѽ � apiclient/CODE_OF_CONDUCT.mdnu �[��� # Contributor Code of Conduct As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) PK gF'Z��+- +- apiclient/UPGRADING.mdnu �[��� Google API Client Upgrade Guide =============================== 1.0 to 2.0 ---------- The Google API Client for PHP has undergone major internal changes in `2.0`. Please read through the list below in order to upgrade to the latest version: ## Installation now uses `Composer` **Before** The project was cloned in your project and you would run the autoloader from wherever: ```php // the autoload file was included require_once 'google-api-php-client/src/Google/autoload.php'; // or wherever autoload.php is located // OR classes were added one-by-one require_once 'Google/Client.php'; require_once 'Google/Service/YouTube.php'; ``` **After** This library now uses [composer](https://getcomposer.org) (We suggest installing composer [globally](http://symfony.com/doc/current/cookbook/composer.html)). Add this library by running the following in the root of your project: ``` $ composer require google/apiclient:~2.0 ``` This will install this library and generate an autoload file in `vendor/autoload.php` in the root of your project. You can now include this library with the following code: ```php require_once 'vendor/autoload.php'; ``` ## Access Tokens are passed around as arrays instead of JSON strings **Before** ```php $accessToken = $client->getAccessToken(); print_r($accessToken); // would output: // string(153) "{"access_token":"ya29.FAKsaByOPoddfzvKRo_LBpWWCpVTiAm4BjsvBwxtN7IgSNoUfcErBk_VPl4iAiE1ntb_","token_type":"Bearer","expires_in":3593,"created":1445548590}" file_put_contents($credentialsPath, $accessToken); ``` **After** ```php $accessToken = $client->getAccessToken(); print_r($accessToken); // will output: // array(4) { // ["access_token"]=> // string(73) "ya29.FAKsaByOPoddfzvKRo_LBpWWCpVTiAm4BjsvBwxtN7IgSNoUfcErBk_VPl4iAiE1ntb_" // ["token_type"]=> // string(6) "Bearer" // ["expires_in"]=> // int(3593) // ["created"]=> // int(1445548590) // } file_put_contents($credentialsPath, json_encode($accessToken)); ``` ## ID Token data is returned as an array **Before** ```php $ticket = $client->verifyIdToken($idToken); $data = $ticket->getAttributes(); $userId = $data['payload']['sub']; ``` **After** ```php $userData = $client->verifyIdToken($idToken); $userId = $userData['sub']; ``` ## `Google_Auth_AssertionCredentials` has been removed For service accounts, we now use `setAuthConfig` or `useApplicationDefaultCredentials` **Before** ```php $client_email = '1234567890-a1b2c3d4e5f6g7h8i@developer.gserviceaccount.com'; $private_key = file_get_contents('MyProject.p12'); $scopes = array('https://www.googleapis.com/auth/sqlservice.admin'); $credentials = new Google_Auth_AssertionCredentials( $client_email, $scopes, $private_key ); ``` **After** ```php $client->setAuthConfig('/path/to/service-account.json'); // OR use environment variables (recommended) putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json'); $client->useApplicationDefaultCredentials(); ``` > Note: P12s are deprecated in favor of service account JSON, which can be generated in the > Credentials section of Google Developer Console. In order to impersonate a user, call `setSubject` when your service account credentials are being used. **Before** ```php $user_to_impersonate = 'user@example.org'; $credentials = new Google_Auth_AssertionCredentials( $client_email, $scopes, $private_key, 'notasecret', // Default P12 password 'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type $user_to_impersonate, ); ``` **After** ```php $user_to_impersonate = 'user@example.org'; $client->setSubject($user_to_impersonate); ``` Additionally, `Google_Client::loadServiceAccountJson` has been removed in favor of `Google_Client::setAuthConfig`: **Before** ```php $scopes = [ Google_Service_Books::BOOKS ]; $client->loadServiceAccountJson('/path/to/service-account.json', $scopes); ``` **After** ```php $scopes = [ Google_Service_Books::BOOKS ]; $client->setAuthConfig('/path/to/service-account.json'); $client->setScopes($scopes); ``` ## `Google_Auth_AppIdentity` has been removed For App Engine authentication, we now use the underlying [`google/auth`][Google Auth] and call `useApplicationDefaultCredentials`: **Before** ```php $client->setAuth(new Google_Auth_AppIdentity($client)); $client->getAuth() ->authenticateForScope('https://www.googleapis.com/auth/sqlservice.admin') ``` **After** ```php $client->useApplicationDefaultCredentials(); $client->addScope('https://www.googleapis.com/auth/sqlservice.admin'); ``` This will detect when the App Engine environment is present, and use the appropriate credentials. ## `Google_Auth_Abstract` classes have been removed [`google/auth`][Google Auth] is now used for authentication. As a result, all `Google_Auth`-related functionality has been removed. The methods that were a part of `Google_Auth_Abstract` have been moved into the `Google_Client` object. **Before** ```php $request = new Google_Http_Request(); $client->getAuth()->sign($request); ``` **After** ```php // create an authorized HTTP client $httpClient = $client->authorize(); // OR add authorization to an existing client $httpClient = new GuzzleHttp\Client(); $httpClient = $client->authorize($httpClient); ``` **Before** ```php $request = new Google_Http_Request(); $response = $client->getAuth()->authenticatedRequest($request); ``` **After** ```php $httpClient = $client->authorize(); $request = new GuzzleHttp\Psr7\Request('POST', $url); $response = $httpClient->send($request); ``` > NOTE: `$request` can be any class implementing > `Psr\Http\Message\RequestInterface` In addition, other methods that were callable on `Google_Auth_OAuth2` are now called on the `Google_Client` object: **Before** ```php $client->getAuth()->refreshToken($token); $client->getAuth()->refreshTokenWithAssertion(); $client->getAuth()->revokeToken($token); $client->getAuth()->isAccessTokenExpired(); ``` **After** ```php $client->refreshToken($token); $client->refreshTokenWithAssertion(); $client->revokeToken($token); $client->isAccessTokenExpired(); ``` ## PHP 5.4 is now the minimum supported PHP version This was previously `PHP 5.2`. If you still need to use PHP 5.2, please continue to use the [v1-master](https://github.com/google/google-api-php-client/tree/v1-master) branch. ## Guzzle and PSR-7 are used for HTTP Requests The HTTP library Guzzle is used for all HTTP Requests. By default, [`Guzzle 6`][Guzzle 6] is used, but this library is also compatible with [`Guzzle 5`][Guzzle 5]. As a result, all `Google_IO`-related functionality and `Google_Http`-related functionality has been changed or removed. 1. Removed `Google_Http_Request` 1. Removed `Google_IO_Abstract`, `Google_IO_Exception`, `Google_IO_Curl`, and `Google_IO_Stream` 1. Removed methods `Google_Client::getIo` and `Google_Client::setIo` 1. Refactored `Google_Http_Batch` and `Google_Http_MediaFileUpload` for Guzzle 1. Added `Google_Client::getHttpClient` and `Google_Client::setHttpClient` for getting and setting the Guzzle `GuzzleHttp\ClientInterface` object. > NOTE: `PSR-7`-compatible libraries can now be used with this library. ## Other Changes - [`PSR 3`][PSR 3] `LoggerInterface` is now supported, and [Monolog][Monolog] is used for all logging. As a result, all `Google_Logger`-related functionality has been removed: 1. Removed `Google_Logger_Abstract`, `Google_Logger_Exception`, `Google_Logger_File`, `Google_Logger_Null`, and `Google_Logger_Psr` 1. `Google_Client::setLogger` now requires `Psr\Log\LoggerInterface` - [`firebase/jwt`][Firebase JWT] is now used for all JWT signing and verifying. As a result, the following classes have been changed or removed: 1. Removed `Google_Signer_P12` 1. Removed `Google_Verifier_Pem` 1. Removed `Google_Auth_LoginTicket` (see below) - The following classes and methods have been removed in favor of [`google/auth`][Google Auth]: 1. Removed methods `Google_Client::getAuth` and `Google_Client::setAuth` 1. Removed `Google_Auth_Abstract` - `Google_Auth_Abstract::sign` and `Google_Auth_Abstract::authenticatedRequest` have been replaced by `Google_Client::authorize`. See the above examples for more details. 1. Removed `Google_Auth_AppIdentity`. This is now supported in [`google/auth`][Google Auth AppIdentity] and is used automatically when `Google_Client::useApplicationDefaultCredentials` is called. 1. Removed `Google_Auth_AssertionCredentials`. Use `Google_Client::setAuthConfig` instead. 1. Removed `Google_Auth_ComputeEngine`. This is now supported in [`google/auth`][Google Auth GCE], and is used automatically when `Google_Client::useApplicationDefaultCredentials` is called. 1. Removed `Google_Auth_Exception` 1. Removed `Google_Auth_LoginTicket`. Calls to `Google_Client::verifyIdToken` now returns the payload of the ID Token as an array if the verification is successful. 1. Removed `Google_Auth_OAuth2`. This functionality is now supported in [`google/auth`][Google Auth OAuth2] and wrapped in `Google_Client`. These changes will only affect applications calling `Google_Client::getAuth`, as the methods on `Google_Client` have not changed. 1. Removed `Google_Auth_Simple`. This is now supported in [`google/auth`][Google Auth Simple] and is used automatically when `Google_Client::setDeveloperKey` is called. - `Google_Client::sign` has been replaced by `Google_Client::authorize`. This function now takes a `GuzzleHttp\ClientInterface` object and uses the following decision tree for authentication: 1. Uses Application Default Credentials when `Google_Client::useApplicationDefaultCredentials` is called - Looks for `GOOGLE_APPLICATION_CREDENTIALS` environment variable if set - Looks in `~/.config/gcloud/application_default_credentials.json` - Otherwise, uses `GCECredentials` 1. Uses API Key if set (see `Client::setDeveloperKey`) 1. Uses Access Token if set (call `Client::setAccessToken`) 1. Automatically refreshes access tokens if one is set and the access token is expired - Removed `Google_Config` - Removed `Google_Utils` - [`PSR-6`][PSR 6] cache is used for all caching. As a result: 1. Removed `Google_Cache_Abstract` 1. Classes `Google_Cache_Apc`, `Google_Cache_File`, `Google_Cache_Memcache`, and `Google_Cache_Null` now implement `Google\Auth\CacheInterface`. 1. Google Auth provides simple [caching utilities][Google Auth Cache] which are used by default unless you provide alternatives. - Removed `$boundary` constructor argument for `Google_Http_MediaFileUpload` [PSR 3]: https://www.php-fig.org/psr/psr-3/ [PSR 6]: https://www.php-fig.org/psr/psr-6/ [Guzzle 5]: https://github.com/guzzle/guzzle [Guzzle 6]: http://docs.guzzlephp.org/en/latest/psr7.html [Monolog]: https://github.com/Seldaek/monolog [Google Auth]: https://github.com/google/google-auth-library-php [Google Auth Cache]: https://github.com/googleapis/google-auth-library-php/tree/master/src/Cache [Google Auth GCE]: https://github.com/google/google-auth-library-php/blob/master/src/GCECredentials.php [Google Auth OAuth2]: https://github.com/google/google-auth-library-php/blob/master/src/OAuth2.php [Google Auth Simple]: https://github.com/google/google-auth-library-php/blob/master/src/Simple.php [Google Auth AppIdentity]: https://github.com/google/google-auth-library-php/blob/master/src/AppIdentityCredentials.php [Firebase JWT]: https://github.com/firebase/php-jwt PK gF'Zb>�t 7 apiclient/src/Google/AuthHandler/Guzzle6AuthHandler.phpnu �[��� <?php use Google\Auth\CredentialsLoader; use Google\Auth\HttpHandler\HttpHandlerFactory; use Google\Auth\FetchAuthTokenCache; use Google\Auth\Middleware\AuthTokenMiddleware; use Google\Auth\Middleware\ScopedAccessTokenMiddleware; use Google\Auth\Middleware\SimpleMiddleware; use GuzzleHttp\Client; use GuzzleHttp\ClientInterface; use Psr\Cache\CacheItemPoolInterface; /** * This supports Guzzle 6 */ class Google_AuthHandler_Guzzle6AuthHandler { protected $cache; protected $cacheConfig; public function __construct(CacheItemPoolInterface $cache = null, array $cacheConfig = []) { $this->cache = $cache; $this->cacheConfig = $cacheConfig; } public function attachCredentials( ClientInterface $http, CredentialsLoader $credentials, callable $tokenCallback = null ) { // use the provided cache if ($this->cache) { $credentials = new FetchAuthTokenCache( $credentials, $this->cacheConfig, $this->cache ); } // if we end up needing to make an HTTP request to retrieve credentials, we // can use our existing one, but we need to throw exceptions so the error // bubbles up. $authHttp = $this->createAuthHttp($http); $authHttpHandler = HttpHandlerFactory::build($authHttp); $middleware = new AuthTokenMiddleware( $credentials, $authHttpHandler, $tokenCallback ); $config = $http->getConfig(); $config['handler']->remove('google_auth'); $config['handler']->push($middleware, 'google_auth'); $config['auth'] = 'google_auth'; $http = new Client($config); return $http; } public function attachToken(ClientInterface $http, array $token, array $scopes) { $tokenFunc = function ($scopes) use ($token) { return $token['access_token']; }; $middleware = new ScopedAccessTokenMiddleware( $tokenFunc, $scopes, $this->cacheConfig, $this->cache ); $config = $http->getConfig(); $config['handler']->remove('google_auth'); $config['handler']->push($middleware, 'google_auth'); $config['auth'] = 'scoped'; $http = new Client($config); return $http; } public function attachKey(ClientInterface $http, $key) { $middleware = new SimpleMiddleware(['key' => $key]); $config = $http->getConfig(); $config['handler']->remove('google_auth'); $config['handler']->push($middleware, 'google_auth'); $config['auth'] = 'simple'; $http = new Client($config); return $http; } private function createAuthHttp(ClientInterface $http) { return new Client( [ 'base_uri' => $http->getConfig('base_uri'), 'exceptions' => true, 'verify' => $http->getConfig('verify'), 'proxy' => $http->getConfig('proxy'), ] ); } } PK gF'Z�?�g� � 7 apiclient/src/Google/AuthHandler/Guzzle7AuthHandler.phpnu �[��� <?php /** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This supports Guzzle 7 */ class Google_AuthHandler_Guzzle7AuthHandler extends Google_AuthHandler_Guzzle6AuthHandler { } PK gF'Z��� � 7 apiclient/src/Google/AuthHandler/Guzzle5AuthHandler.phpnu �[��� <?php use Google\Auth\CredentialsLoader; use Google\Auth\HttpHandler\HttpHandlerFactory; use Google\Auth\FetchAuthTokenCache; use Google\Auth\Subscriber\AuthTokenSubscriber; use Google\Auth\Subscriber\ScopedAccessTokenSubscriber; use Google\Auth\Subscriber\SimpleSubscriber; use GuzzleHttp\Client; use GuzzleHttp\ClientInterface; use Psr\Cache\CacheItemPoolInterface; /** * */ class Google_AuthHandler_Guzzle5AuthHandler { protected $cache; protected $cacheConfig; public function __construct(CacheItemPoolInterface $cache = null, array $cacheConfig = []) { $this->cache = $cache; $this->cacheConfig = $cacheConfig; } public function attachCredentials( ClientInterface $http, CredentialsLoader $credentials, callable $tokenCallback = null ) { // use the provided cache if ($this->cache) { $credentials = new FetchAuthTokenCache( $credentials, $this->cacheConfig, $this->cache ); } // if we end up needing to make an HTTP request to retrieve credentials, we // can use our existing one, but we need to throw exceptions so the error // bubbles up. $authHttp = $this->createAuthHttp($http); $authHttpHandler = HttpHandlerFactory::build($authHttp); $subscriber = new AuthTokenSubscriber( $credentials, $authHttpHandler, $tokenCallback ); $http->setDefaultOption('auth', 'google_auth'); $http->getEmitter()->attach($subscriber); return $http; } public function attachToken(ClientInterface $http, array $token, array $scopes) { $tokenFunc = function ($scopes) use ($token) { return $token['access_token']; }; $subscriber = new ScopedAccessTokenSubscriber( $tokenFunc, $scopes, $this->cacheConfig, $this->cache ); $http->setDefaultOption('auth', 'scoped'); $http->getEmitter()->attach($subscriber); return $http; } public function attachKey(ClientInterface $http, $key) { $subscriber = new SimpleSubscriber(['key' => $key]); $http->setDefaultOption('auth', 'simple'); $http->getEmitter()->attach($subscriber); return $http; } private function createAuthHttp(ClientInterface $http) { return new Client( [ 'base_url' => $http->getBaseUrl(), 'defaults' => [ 'exceptions' => true, 'verify' => $http->getDefaultOption('verify'), 'proxy' => $http->getDefaultOption('proxy'), ] ] ); } } PK gF'Z�*f� � 7 apiclient/src/Google/AuthHandler/AuthHandlerFactory.phpnu �[��� <?php /** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use GuzzleHttp\Client; use GuzzleHttp\ClientInterface; class Google_AuthHandler_AuthHandlerFactory { /** * Builds out a default http handler for the installed version of guzzle. * * @return Google_AuthHandler_Guzzle5AuthHandler|Google_AuthHandler_Guzzle6AuthHandler * @throws Exception */ public static function build($cache = null, array $cacheConfig = []) { $guzzleVersion = null; if (defined('\GuzzleHttp\ClientInterface::MAJOR_VERSION')) { $guzzleVersion = ClientInterface::MAJOR_VERSION; } elseif (defined('\GuzzleHttp\ClientInterface::VERSION')) { $guzzleVersion = (int) substr(ClientInterface::VERSION, 0, 1); } switch ($guzzleVersion) { case 5: return new Google_AuthHandler_Guzzle5AuthHandler($cache, $cacheConfig); case 6: return new Google_AuthHandler_Guzzle6AuthHandler($cache, $cacheConfig); case 7: return new Google_AuthHandler_Guzzle7AuthHandler($cache, $cacheConfig); default: throw new Exception('Version not supported'); } } } PK gF'Z��� � ! apiclient/src/Google/autoload.phpnu �[��� <?php /** * THIS FILE IS FOR BACKWARDS COMPATIBLITY ONLY * * If you were not already including this file in your project, please ignore it */ $file = __DIR__ . '/../../vendor/autoload.php'; if (!file_exists($file)) { $exception = 'This library must be installed via composer or by downloading the full package.'; $exception .= ' See the instructions at https://github.com/google/google-api-php-client#installation.'; throw new Exception($exception); } $error = 'google-api-php-client\'s autoloader was moved to vendor/autoload.php in 2.0.0. This '; $error .= 'redirect will be removed in 2.1. Please adjust your code to use the new location.'; trigger_error($error, E_USER_DEPRECATED); require_once $file; PK gF'ZN�3� � '