weekly release 3.8dev
[moodle.git] / lib / recaptchalib.php
CommitLineData
5d6308d4 1<?php
50fcb1d8 2
3/**
5d6308d4 4 * This is a PHP library that handles calling reCAPTCHA.
5 * - Documentation and latest version
ca1bee1a 6 * {@link http://code.google.com/apis/recaptcha/docs/php.html}
5d6308d4 7 * - Get a reCAPTCHA API Key
ca1bee1a 8 * {@link https://www.google.com/recaptcha/admin/create}
5d6308d4 9 * - Discussion group
50fcb1d8 10 * {@link http://groups.google.com/group/recaptcha}
5d6308d4 11 *
ca1bee1a 12 * Copyright (c) 2007 reCAPTCHA -- {@link http://www.google.com/recaptcha}
5d6308d4 13 * AUTHORS:
14 * Mike Crawford
15 * Ben Maurer
16 *
17 * Permission is hereby granted, free of charge, to any person obtaining a copy
18 * of this software and associated documentation files (the "Software"), to deal
19 * in the Software without restriction, including without limitation the rights
20 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
21 * copies of the Software, and to permit persons to whom the Software is
22 * furnished to do so, subject to the following conditions:
23 *
24 * The above copyright notice and this permission notice shall be included in
25 * all copies or substantial portions of the Software.
26 *
27 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
33 * THE SOFTWARE.
50fcb1d8 34 *
35 * @package moodlecore
ca1bee1a 36 * @copyright (c) 2007 reCAPTCHA -- {@link http://www.google.com/recaptcha}
5d6308d4 37 */
38
39/**
40 * The reCAPTCHA server URL's
41 */
ca1bee1a
AB
42define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api");
43define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api");
44define("RECAPTCHA_VERIFY_SERVER", "www.google.com");
5d6308d4 45
46/**
47 * Encodes the given data into a query string format
48 * @param $data - array of string elements to be encoded
49 * @return string - encoded request
50 */
51function _recaptcha_qsencode ($data) {
52 $req = "";
53 foreach ( $data as $key => $value )
294ce987 54 $req .= $key . '=' . urlencode( $value ) . '&';
5d6308d4 55
56 // Cut the last '&'
57 $req=substr($req,0,strlen($req)-1);
58 return $req;
59}
60
61
62
63/**
64 * Submits an HTTP POST to a reCAPTCHA server
50fcb1d8 65 *
66 * @global object
5d6308d4 67 * @param string $host
68 * @param string $path
69 * @param array $data
70 * @param int port
71 * @return array response
72 */
83947a36 73function _recaptcha_http_post($host, $path, $data, $port = 80, $https=false) {
7c572b8c 74 global $CFG;
83947a36 75 $protocol = 'http';
76 if ($https) {
77 $protocol = 'https';
78 }
79
9b5f87d2 80 require_once $CFG->libdir . '/filelib.php';
5d6308d4 81
9b5f87d2 82 $req = _recaptcha_qsencode ($data);
a836d6d3 83
9b5f87d2 84 $headers = array();
85 $headers['Host'] = $host;
86 $headers['Content-Type'] = 'application/x-www-form-urlencoded';
87 $headers['Content-Length'] = strlen($req);
88 $headers['User-Agent'] = 'reCAPTCHA/PHP';
a836d6d3 89
83947a36 90 $results = download_file_content("$protocol://" . $host . $path, $headers, $data, false, 300, 20, true);
a836d6d3 91
9b5f87d2 92 if ($results) {
93 return array(1 => $results);
7c572b8c 94 } else {
95 return false;
5d6308d4 96 }
5d6308d4 97}
98
f1062815
JL
99/**
100 * Return the recaptcha challenge and image and javascript urls
101 *
102 * @param string $server server url
103 * @param string $pubkey public key
104 * @param string $errorpart error part to append
105 * @return array the challenge hash, image and javascript url
106 * @since Moodle 3.2
107 */
108function recaptcha_get_challenge_hash_and_urls($server, $pubkey, $errorpart = '') {
109 global $CFG;
110
111 require_once($CFG->libdir . '/filelib.php');
112 $html = download_file_content($server . '/noscript?k=' . $pubkey . $errorpart, null, null, false, 300, 20, true);
113 preg_match('/image\?c\=([A-Za-z0-9\-\_]*)\"/', $html, $matches);
114 $challengehash = $matches[1];
115 $imageurl = $server . '/image?c=' . $challengehash;
116
117 $jsurl = $server . '/challenge?k=' . $pubkey . $errorpart;
118
119 return array($challengehash, $imageurl, $jsurl);
120}
5d6308d4 121
122
123/**
124 * Gets the challenge HTML (javascript and non-javascript version).
125 * This is called from the browser, and the resulting reCAPTCHA HTML widget
126 * is embedded within the HTML form it was called from.
50fcb1d8 127 *
128 * @global object
5d6308d4 129 * @param string $pubkey A public key for reCAPTCHA
130 * @param string $error The error given by reCAPTCHA (optional, default is null)
131 * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
132
133 * @return string - The HTML to be embedded in the user's form.
134 */
9b5f87d2 135function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false) {
f1062815 136 global $PAGE;
9b5f87d2 137
138 $recaptchatype = optional_param('recaptcha', 'image', PARAM_TEXT);
139
a836d6d3 140 if ($pubkey == null || $pubkey == '') {
ca1bee1a 141 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>");
a836d6d3 142 }
5d6308d4 143
a836d6d3 144 if ($use_ssl) {
145 $server = RECAPTCHA_API_SECURE_SERVER;
146 } else {
147 $server = RECAPTCHA_API_SERVER;
148 }
149
150 $errorpart = "";
151 if ($error) {
f1062815 152 $errorpart = "&amp;error=" . $error;
a836d6d3 153 }
5d6308d4 154
f1062815 155 list($challengehash, $imageurl, $jsurl) = recaptcha_get_challenge_hash_and_urls($server, $pubkey, $errorpart);
a836d6d3 156
9b5f87d2 157 $strincorrectpleasetryagain = get_string('incorrectpleasetryagain', 'auth');
158 $strenterthewordsabove = get_string('enterthewordsabove', 'auth');
159 $strenterthenumbersyouhear = get_string('enterthenumbersyouhear', 'auth');
160 $strgetanothercaptcha = get_string('getanothercaptcha', 'auth');
161 $strgetanaudiocaptcha = get_string('getanaudiocaptcha', 'auth');
162 $strgetanimagecaptcha = get_string('getanimagecaptcha', 'auth');
7a1f5e93 163
f1062815 164 $return = html_writer::script('', $jsurl);
7a1f5e93 165 $return .= '<noscript>
9b5f87d2 166 <div id="recaptcha_widget_noscript">
f1062815 167 <div id="recaptcha_image_noscript"><img src="' . $imageurl . '" alt="reCAPTCHA"/></div>';
7a1f5e93 168
9b5f87d2 169 if ($error == 'incorrect-captcha-sol') {
170 $return .= '<div class="recaptcha_only_if_incorrect_sol" style="color:red">' . $strincorrectpleasetryagain . '</div>';
171 }
172
173 if ($recaptchatype == 'image') {
174 $return .= '<span class="recaptcha_only_if_image">' . $strenterthewordsabove . '</span>';
175 } elseif ($recaptchatype == 'audio') {
f1062815 176 $return .= '<span class="recaptcha_only_if_audio">' . $strenterthenumbersyouhear . '</span>';
9b5f87d2 177 }
f1062815 178
9b5f87d2 179 $return .= '<input type="text" id="recaptcha_response_field_noscript" name="recaptcha_response_field" />';
f1062815 180 $return .= '<input type="hidden" id="recaptcha_challenge_field_noscript" name="recaptcha_challenge_field" value="' . $challengehash . '" />';
9b5f87d2 181 $return .= '<div><a href="signup.php">' . $strgetanothercaptcha . '</a></div>';
f1062815 182
9b5f87d2 183 // Disabling audio recaptchas for now: not language-independent
184 /*
185 if ($recaptchatype == 'image') {
186 $return .= '<div class="recaptcha_only_if_image"><a href="signup.php?recaptcha=audio">' . $strgetanaudiocaptcha . '</a></div>';
187 } elseif ($recaptchatype == 'audio') {
188 $return .= '<div class="recaptcha_only_if_audio"><a href="signup.php?recaptcha=image">' . $strgetanimagecaptcha . '</a></div>';
189 }
190 */
191
192 $return .= '
193 </div>
a836d6d3 194 </noscript>';
9b5f87d2 195
196 return $return;
5d6308d4 197}
198
199
200
201
202/**
203 * A ReCaptchaResponse is returned from recaptcha_check_answer()
50fcb1d8 204 *
205 * @package moodlecore
ca1bee1a 206 * @copyright (c) 2007 reCAPTCHA -- {@link http://www.google.com/recaptcha}
5d6308d4 207 */
208class ReCaptchaResponse {
209 var $is_valid;
210 var $error;
211}
212
213
214/**
215 * Calls an HTTP POST function to verify if the user's guess was correct
216 * @param string $privkey
217 * @param string $remoteip
218 * @param string $challenge
219 * @param string $response
220 * @return ReCaptchaResponse
221 */
83947a36 222function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $https=false)
5d6308d4 223{
a836d6d3 224 if ($privkey == null || $privkey == '') {
ca1bee1a 225 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>");
a836d6d3 226 }
5d6308d4 227
a836d6d3 228 if ($remoteip == null || $remoteip == '') {
229 die ("For security reasons, you must pass the remote ip to reCAPTCHA");
230 }
5d6308d4 231
5d6308d4 232 //discard spam submissions
233 if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
234 $recaptcha_response = new ReCaptchaResponse();
235 $recaptcha_response->is_valid = false;
236 $recaptcha_response->error = 'incorrect-captcha-sol';
237 return $recaptcha_response;
238 }
239
ca1bee1a 240 $response = _recaptcha_http_post(RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify",
83947a36 241 array (
242 'privatekey' => $privkey,
243 'remoteip' => $remoteip,
244 'challenge' => $challenge,
245 'response' => $response
246 ),
f1062815 247 $https
83947a36 248 );
5d6308d4 249
250 $answers = explode ("\n", $response [1]);
251 $recaptcha_response = new ReCaptchaResponse();
252
253 if (trim ($answers [0]) == 'true') {
254 $recaptcha_response->is_valid = true;
255 }
256 else {
257 $recaptcha_response->is_valid = false;
258 $recaptcha_response->error = $answers [1];
259 }
260 return $recaptcha_response;
261
262}
263
264/**
265 * gets a URL where the user can sign up for reCAPTCHA. If your application
266 * has a configuration page where you enter a key, you should provide a link
267 * using this function.
268 * @param string $domain The domain where the page is hosted
269 * @param string $appname The name of your application
270 */
271function recaptcha_get_signup_url ($domain = null, $appname = null) {
ca1bee1a 272 return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname));
5d6308d4 273}
274
275function _recaptcha_aes_pad($val) {
a836d6d3 276 $block_size = 16;
277 $numpad = $block_size - (strlen ($val) % $block_size);
278 return str_pad($val, strlen ($val) + $numpad, chr($numpad));
5d6308d4 279}
280
281/* Mailhide related code */
282
283function _recaptcha_aes_encrypt($val,$ky) {
a836d6d3 284 if (! function_exists ("mcrypt_encrypt")) {
285 die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
286 }
287 $mode=MCRYPT_MODE_CBC;
288 $enc=MCRYPT_RIJNDAEL_128;
289 $val=_recaptcha_aes_pad($val);
290 return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
5d6308d4 291}
292
293
294function _recaptcha_mailhide_urlbase64 ($x) {
a836d6d3 295 return strtr(base64_encode ($x), '+/', '-_');
5d6308d4 296}
297
298/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
299function recaptcha_mailhide_url($pubkey, $privkey, $email) {
a836d6d3 300 if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
301 die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
ca1bee1a 302 "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
a836d6d3 303 }
304
305
306 $ky = pack('H*', $privkey);
307 $cryptmail = _recaptcha_aes_encrypt ($email, $ky);
308
ca1bee1a 309 return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
5d6308d4 310}
311
312/**
313 * gets the parts of the email to expose to the user.
314 * eg, given johndoe@example,com return ["john", "example.com"].
315 * the email is then displayed as john...@example.com
316 */
317function _recaptcha_mailhide_email_parts ($email) {
a836d6d3 318 $arr = preg_split("/@/", $email );
319
320 if (strlen ($arr[0]) <= 4) {
321 $arr[0] = substr ($arr[0], 0, 1);
322 } else if (strlen ($arr[0]) <= 6) {
323 $arr[0] = substr ($arr[0], 0, 3);
324 } else {
325 $arr[0] = substr ($arr[0], 0, 4);
326 }
327 return $arr;
5d6308d4 328}
329
330/**
331 * Gets html to display an email address given a public an private key.
332 * to get a key, go to:
333 *
ca1bee1a 334 * http://www.google.com/recaptcha/mailhide/apikey
5d6308d4 335 */
336function recaptcha_mailhide_html($pubkey, $privkey, $email) {
a836d6d3 337 $emailparts = _recaptcha_mailhide_email_parts ($email);
338 $url = recaptcha_mailhide_url ($pubkey, $privkey, $email);
5d6308d4 339
a836d6d3 340 return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
341 "' onclick=\"window.open('" . htmlentities ($url) . "', '', '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>@" . htmlentities ($emailparts [1]);
5d6308d4 342
a836d6d3 343}