3 * This is a PHP library that handles calling reCAPTCHA.
4 * - Documentation and latest version
5 * http://recaptcha.net/plugins/php/
6 * - Get a reCAPTCHA API Key
7 * https://www.google.com/recaptcha/admin/create
9 * http://groups.google.com/group/recaptcha
11 * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
16 * Permission is hereby granted, free of charge, to any person obtaining a copy
17 * of this software and associated documentation files (the "Software"), to deal
18 * in the Software without restriction, including without limitation the rights
19 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20 * copies of the Software, and to permit persons to whom the Software is
21 * furnished to do so, subject to the following conditions:
23 * The above copyright notice and this permission notice shall be included in
24 * all copies or substantial portions of the Software.
26 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
37 * A Services_Recaptcha_Response is returned from recaptcha_check_answer()
39 class Services_Recaptcha_Response {
44 * The reCAPTCHA server URL's
48 class Services_Recptcha {
50 static $API_SERVER = "http://www.google.com/recaptcha/api";
51 static $API_SECURE_SERVER = "https://www.google.com/recaptcha/api";
52 static $VERIFY_SERVER = "www.google.com";
55 * Encodes the given data into a query string format
56 * @param $data - array of string elements to be encoded
57 * @return string - encoded request
59 static function _qsencode ($data)
62 foreach ( $data as $key => $value )
63 $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';
66 $req=substr($req,0,strlen($req)-1);
73 * Submits an HTTP POST to a reCAPTCHA server
78 * @return array response
80 static function _http_post($host, $path, $data, $port = 80)
83 $req = self::_qsencode ($data);
85 $http_request = "POST $path HTTP/1.0\r\n";
86 $http_request .= "Host: $host\r\n";
87 $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
88 $http_request .= "Content-Length: " . strlen($req) . "\r\n";
89 $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
90 $http_request .= "\r\n";
91 $http_request .= $req;
94 if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
95 die ('Could not open socket');
98 fwrite($fs, $http_request);
101 $response .= fgets($fs, 1160); // One TCP-IP packet
103 $response = explode("\r\n\r\n", $response, 2);
111 * Gets the challenge HTML (javascript and non-javascript version).
112 * This is called from the browser, and the resulting reCAPTCHA HTML widget
113 * is embedded within the HTML form it was called from.
114 * @param string $pubkey A public key for reCAPTCHA
115 * @param string $error The error given by reCAPTCHA (optional, default is null)
116 * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
118 * @return string - The HTML to be embedded in the user's form.
120 static function get_html ($pubkey, $error = null, $use_ssl = false)
122 if ($pubkey == null || $pubkey == '') {
123 die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
127 $server = self::$API_SECURE_SERVER;
129 $server = self::$API_SERVER;
134 $errorpart = "&error=" . $error;
136 return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
139 <iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
140 <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
141 <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
151 * Calls an HTTP POST function to verify if the user's guess was correct
152 * @param string $privkey
153 * @param string $remoteip
154 * @param string $challenge
155 * @param string $response
156 * @param array $extra_params an array of extra variables to post to the server
157 * @return Services_Recaptcha_Response
159 static function check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array())
161 if ($privkey == null || $privkey == '') {
162 die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
165 if ($remoteip == null || $remoteip == '') {
166 die ("For security reasons, you must pass the remote ip to reCAPTCHA");
171 //discard spam submissions
172 if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
173 $recaptcha_response = new Services_Recaptcha_Response();
174 $recaptcha_response->is_valid = false;
175 $recaptcha_response->error = 'incorrect-captcha-sol';
176 return $recaptcha_response;
179 $response = self::_http_post (self::$VERIFY_SERVER, "/recaptcha/api/verify",
181 'privatekey' => $privkey,
182 'remoteip' => $remoteip,
183 'challenge' => $challenge,
184 'response' => $response
188 $answers = explode ("\n", $response [1]);
189 $recaptcha_response = new Services_Recaptcha_Response();
191 if (trim ($answers [0]) == 'true') {
192 $recaptcha_response->is_valid = true;
195 $recaptcha_response->is_valid = false;
196 $recaptcha_response->error = $answers [1];
198 return $recaptcha_response;
203 * gets a URL where the user can sign up for reCAPTCHA. If your application
204 * has a configuration page where you enter a key, you should provide a link
205 * using this function.
206 * @param string $domain The domain where the page is hosted
207 * @param string $appname The name of your application
209 static function get_signup_url ($domain = null, $appname = null)
211 return "https://www.google.com/recaptcha/admin/create?" . self::_qsencode (array ('domains' => $domain, 'app' => $appname));
214 static function _aes_pad($val)
217 $numpad = $block_size - (strlen ($val) % $block_size);
218 return str_pad($val, strlen ($val) + $numpad, chr($numpad));
221 /* Mailhide related code */
223 static function _aes_encrypt($val,$ky)
225 if (! function_exists ("mcrypt_encrypt")) {
226 die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
228 $mode=MCRYPT_MODE_CBC;
229 $enc=MCRYPT_RIJNDAEL_128;
230 $val= self::_aes_pad($val);
231 return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
235 static function _mailhide_urlbase64 ($x)
237 return strtr(base64_encode ($x), '+/', '-_');
240 /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
241 static function mailhide_url($pubkey, $privkey, $email)
243 if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
244 die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
245 "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
249 $ky = pack('H*', $privkey);
250 $cryptmail = self::_aes_encrypt ($email, $ky);
252 return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . self::_mailhide_urlbase64 ($cryptmail);
256 * gets the parts of the email to expose to the user.
257 * eg, given johndoe@example,com return ["john", "example.com"].
258 * the email is then displayed as john...@example.com
260 static function _mailhide_email_parts ($email)
262 $arr = preg_split("/@/", $email );
264 if (strlen ($arr[0]) <= 4) {
265 $arr[0] = substr ($arr[0], 0, 1);
266 } else if (strlen ($arr[0]) <= 6) {
267 $arr[0] = substr ($arr[0], 0, 3);
269 $arr[0] = substr ($arr[0], 0, 4);
275 * Gets html to display an email address given a public an private key.
276 * to get a key, go to:
278 * http://www.google.com/recaptcha/mailhide/apikey
280 static function mailhide_html($pubkey, $privkey, $email)
282 $emailparts = self::_mailhide_email_parts ($email);
283 $url = self::mailhide_url ($pubkey, $privkey, $email);
285 return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
286 "' onclick=\"window.open('" . htmlentities ($url) .
287 "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" .
288 htmlentities ($emailparts [1]);