recaptchalib.php 9.87 KB
Newer Older
Scott committed
1
<?php
Scott committed
2
/**
Scott committed
3 4
 * This is a PHP library that handles calling reCAPTCHA.
 *    - Documentation and latest version
Scott committed
5
 *          https://developers.google.com/recaptcha/docs/php
Scott committed
6 7 8 9 10
 *    - Get a reCAPTCHA API Key
 *          https://www.google.com/recaptcha/admin/create
 *    - Discussion group
 *          http://groups.google.com/group/recaptcha
 *
Scott committed
11 12
 * @copyright Copyright (c) 2014, Google Inc.
 * @link      http://www.google.com/recaptcha
Scott committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *
 * 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.
 */

/**
Scott committed
34
 * A ReCaptchaResponse is returned from verifyResponse().
Scott committed
35
 */
Scott committed
36 37 38 39
class ReCaptchaResponse
{
    public $success;
    public $errorCodes = array();
Scott committed
40 41
}

Amiya committed
42 43 44 45
/**
 * Stores and formats the parameters for the request to the reCAPTCHA service.
 */
class ReCaptchaRequestParameters
Scott committed
46
{
Amiya committed
47 48 49 50
    private $secret;
    private $response;
    private $remoteIp;
    private $version;
Scott committed
51 52

    /**
Amiya committed
53
     * Initialise parameters.
Scott committed
54
     *
Amiya committed
55 56 57 58
     * @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.
Scott committed
59
     */
Amiya committed
60
    public function __construct($secret, $response, $remoteIp = null, $version = null)
Scott committed
61
    {
Amiya committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
        $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;
Scott committed
79
        }
Amiya committed
80 81 82 83 84 85

        if (!is_null($this->version)) {
            $params['version'] = $this->version;
        }

        return $params;
Scott committed
86 87 88
    }

    /**
Amiya committed
89
     * Query string representation for HTTP request.
Scott committed
90
     *
Amiya committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
     * @return string Query string formatted parameters.
     */
    public function toQueryString()
    {
        return http_build_query($this->toArray(), '', '&');
    }
}

/**
 * Defines certain rules for a RequestMethod
 * Interface ReCaptchaRequestMethod
 */
interface ReCaptchaRequestMethod
{
    /**
     * Submit the request with the specified parameters.
Scott committed
107
     *
Amiya committed
108 109
     * @param ReCaptchaRequestParameters $params Request parameters
     * @return string Body of the reCAPTCHA response
Scott committed
110
     */
Amiya committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    public function submit(ReCaptchaRequestParameters $params);
}

/**
 * Sends GET requests to the reCAPTCHA service.
 */
class ReCaptchaGetRequestMethod implements ReCaptchaRequestMethod{

    const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify?';

    /**
     * Submit the request with the specified parameters.
     *
     * @param ReCaptchaRequestParameters $params Request parameters
     * @return string Body of the reCAPTCHA response
     */
    public function submit(ReCaptchaRequestParameters $params){
        return file_get_contents(self::SITE_VERIFY_URL . $params->toQueryString());
    }
}

/**
 * Convenience wrapper around native socket and file functions to allow for
 * mocking.
 */
class ReCaptchaSocket
{
    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)
Scott committed
152
    {
Amiya committed
153 154 155 156
        $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;
Scott committed
157 158
        }

Amiya committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172
        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));
Scott committed
173 174 175
    }

    /**
Amiya committed
176
     * fgets
Scott committed
177
     *
Amiya committed
178 179 180 181 182 183 184 185 186 187 188
     * @see http://php.net/fgets
     * @param int $length
     * @return string
     */
    public function fgets($length = null)
    {
        return fgets($this->handle, $length);
    }

    /**
     * feof
Scott committed
189
     *
Amiya committed
190 191
     * @see http://php.net/feof
     * @return bool
Scott committed
192
     */
Amiya committed
193
    public function feof()
Scott committed
194
    {
Amiya committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
        return feof($this->handle);
    }

    /**
     * fclose
     *
     * @see http://php.net/fclose
     * @return bool
     */
    public function fclose()
    {
        return fclose($this->handle);
    }
}

/**
 * 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_furl_open is disabled.
 */
class ReCaptchaSocketPostRequestMethod implements ReCaptchaRequestMethod
{
    const RECAPTCHA_HOST = 'www.google.com';
    const SITE_VERIFY_PATH = '/recaptcha/api/siteverify';
    const BAD_REQUEST = '{"success": false, "error-codes": ["invalid-request"]}';
    const BAD_RESPONSE = '{"success": false, "error-codes": ["invalid-response"]}';
    private $socket;

    public function __construct(ReCaptchaSocket $socket = null)
    {
        if (!is_null($socket)) {
            $this->socket = $socket;
        } else {
            $this->socket = new ReCaptchaSocket();
        }
    }

    /**
     * Submit the POST request with the specified parameters.
     *
     * @param ReCaptchaRequestParameters $params Request parameters
     * @return string Body of the reCAPTCHA response
     */
    public function submit(ReCaptchaRequestParameters $params)
    {
        $errno = 0;
        $errstr = '';

        if (false === $this->socket->fsockopen('ssl://' . self::RECAPTCHA_HOST, 443, $errno, $errstr, 30)) {
            return self::BAD_REQUEST;
        }

        $content = $params->toQueryString();

        $request = "POST " . self::SITE_VERIFY_PATH . " HTTP/1.1\r\n";
        $request .= "Host: " . self::RECAPTCHA_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.1 200 OK')) {
            return self::BAD_RESPONSE;
        }

        $parts = preg_split("#\n\s*\n#Uis", $response);

        return $parts[1];
    }
}

class ReCaptcha
{
    private static $_signupUrl = 'https://www.google.com/recaptcha/admin';

    const VERSION = 'php_1.1.2';
    private $secret;
    private $requestMethod;

    /**
     * Constructor.
     *
     * @param string $secret shared secret between site and ReCAPTCHA server.
     */
    public function __construct($secret , ReCaptchaRequestMethod $requestMethod = null)
    {
        if ($secret == null || $secret == '') {
            die('To use reCAPTCHA you must get an API key from <a href="' . self::$_signupUrl . '">' . self::$_signupUrl . '</a>');
        }

        if (!is_string($secret)) {
            die('The provided secret must be a string');
        }

        $this->secret = $secret;

        if (!is_null($requestMethod)) {
            $this->requestMethod = $requestMethod;
        } else {
            $this->requestMethod = new ReCaptchaGetRequestMethod();
        }
Scott committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    }

    /**
     * Calls the reCAPTCHA siteverify API to verify whether the user passes
     * CAPTCHA test.
     *
     * @param string $remoteIp   IP address of end user.
     * @param string $response   response string from recaptcha verification.
     *
     * @return ReCaptchaResponse
     */
    public function verifyResponse($remoteIp, $response)
    {
        // Discard empty solution submissions
        if ($response == null || strlen($response) == 0) {
            $recaptchaResponse = new ReCaptchaResponse();
            $recaptchaResponse->success = false;
            $recaptchaResponse->errorCodes = array('missing-input-response');
            return $recaptchaResponse;
Scott committed
324 325
        }

Amiya committed
326 327 328 329 330
        $params = new ReCaptchaRequestParameters($this->secret, $response, $remoteIp, self::VERSION);

        $rawResponse = $this->requestMethod->submit($params);
        $answers = json_decode($rawResponse, true);

Scott committed
331 332 333 334 335 336 337 338
        $recaptchaResponse = new ReCaptchaResponse();

        if (trim($answers['success']) == true) {
            $recaptchaResponse->success = true;
        } else {
            $recaptchaResponse->success = false;
            if (isset($answers['error-codes']))
                $recaptchaResponse->errorCodes = $answers['error-codes'];
Scott committed
339 340
        }

Scott committed
341 342
        return $recaptchaResponse;
    }
Scott committed
343

Scott committed
344 345 346 347
    public static function getSignupUrl()
    {
        return self::$_signupUrl;
    }
Scott committed
348
}