Merge branch 'MDL-55358-master' of https://github.com/davidknu/moodle
[moodle.git] / lib / recaptchalib.php
blob79eb4a3fc610ff6d8f409d9d8eec9b3d7bab2774
1 <?php
3 /**
4 * This is a PHP library that handles calling reCAPTCHA.
5 * - Documentation and latest version
6 * {@link http://code.google.com/apis/recaptcha/docs/php.html}
7 * - Get a reCAPTCHA API Key
8 * {@link https://www.google.com/recaptcha/admin/create}
9 * - Discussion group
10 * {@link http://groups.google.com/group/recaptcha}
12 * Copyright (c) 2007 reCAPTCHA -- {@link http://www.google.com/recaptcha}
13 * AUTHORS:
14 * Mike Crawford
15 * Ben Maurer
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:
24 * The above copyright notice and this permission notice shall be included in
25 * all copies or substantial portions of the Software.
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.
35 * @package moodlecore
36 * @copyright (c) 2007 reCAPTCHA -- {@link http://www.google.com/recaptcha}
39 /**
40 * The reCAPTCHA server URL's
42 define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api");
43 define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api");
44 define("RECAPTCHA_VERIFY_SERVER", "www.google.com");
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
51 function _recaptcha_qsencode ($data) {
52 $req = "";
53 foreach ( $data as $key => $value )
54 $req .= $key . '=' . urlencode( $value ) . '&';
56 // Cut the last '&'
57 $req=substr($req,0,strlen($req)-1);
58 return $req;
63 /**
64 * Submits an HTTP POST to a reCAPTCHA server
66 * @global object
67 * @param string $host
68 * @param string $path
69 * @param array $data
70 * @param int port
71 * @return array response
73 function _recaptcha_http_post($host, $path, $data, $port = 80, $https=false) {
74 global $CFG;
75 $protocol = 'http';
76 if ($https) {
77 $protocol = 'https';
80 require_once $CFG->libdir . '/filelib.php';
82 $req = _recaptcha_qsencode ($data);
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';
90 $results = download_file_content("$protocol://" . $host . $path, $headers, $data, false, 300, 20, true);
92 if ($results) {
93 return array(1 => $results);
94 } else {
95 return false;
99 /**
100 * Return the recaptcha challenge and image and javascript urls
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
108 function recaptcha_get_challenge_hash_and_urls($server, $pubkey, $errorpart = '') {
109 global $CFG;
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;
117 $jsurl = $server . '/challenge?k=' . $pubkey . $errorpart;
119 return array($challengehash, $imageurl, $jsurl);
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.
128 * @global object
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)
133 * @return string - The HTML to be embedded in the user's form.
135 function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false) {
136 global $PAGE;
138 $recaptchatype = optional_param('recaptcha', 'image', PARAM_TEXT);
140 if ($pubkey == null || $pubkey == '') {
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>");
144 if ($use_ssl) {
145 $server = RECAPTCHA_API_SECURE_SERVER;
146 } else {
147 $server = RECAPTCHA_API_SERVER;
150 $errorpart = "";
151 if ($error) {
152 $errorpart = "&amp;error=" . $error;
155 list($challengehash, $imageurl, $jsurl) = recaptcha_get_challenge_hash_and_urls($server, $pubkey, $errorpart);
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');
164 $return = html_writer::script('', $jsurl);
165 $return .= '<noscript>
166 <div id="recaptcha_widget_noscript">
167 <div id="recaptcha_image_noscript"><img src="' . $imageurl . '" alt="reCAPTCHA"/></div>';
169 if ($error == 'incorrect-captcha-sol') {
170 $return .= '<div class="recaptcha_only_if_incorrect_sol" style="color:red">' . $strincorrectpleasetryagain . '</div>';
173 if ($recaptchatype == 'image') {
174 $return .= '<span class="recaptcha_only_if_image">' . $strenterthewordsabove . '</span>';
175 } elseif ($recaptchatype == 'audio') {
176 $return .= '<span class="recaptcha_only_if_audio">' . $strenterthenumbersyouhear . '</span>';
179 $return .= '<input type="text" id="recaptcha_response_field_noscript" name="recaptcha_response_field" />';
180 $return .= '<input type="hidden" id="recaptcha_challenge_field_noscript" name="recaptcha_challenge_field" value="' . $challengehash . '" />';
181 $return .= '<div><a href="signup.php">' . $strgetanothercaptcha . '</a></div>';
183 // Disabling audio recaptchas for now: not language-independent
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>';
192 $return .= '
193 </div>
194 </noscript>';
196 return $return;
203 * A ReCaptchaResponse is returned from recaptcha_check_answer()
205 * @package moodlecore
206 * @copyright (c) 2007 reCAPTCHA -- {@link http://www.google.com/recaptcha}
208 class ReCaptchaResponse {
209 var $is_valid;
210 var $error;
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
222 function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $https=false)
224 if ($privkey == null || $privkey == '') {
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>");
228 if ($remoteip == null || $remoteip == '') {
229 die ("For security reasons, you must pass the remote ip to reCAPTCHA");
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;
240 $response = _recaptcha_http_post(RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify",
241 array (
242 'privatekey' => $privkey,
243 'remoteip' => $remoteip,
244 'challenge' => $challenge,
245 'response' => $response
247 $https
250 $answers = explode ("\n", $response [1]);
251 $recaptcha_response = new ReCaptchaResponse();
253 if (trim ($answers [0]) == 'true') {
254 $recaptcha_response->is_valid = true;
256 else {
257 $recaptcha_response->is_valid = false;
258 $recaptcha_response->error = $answers [1];
260 return $recaptcha_response;
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
271 function recaptcha_get_signup_url ($domain = null, $appname = null) {
272 return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname));
275 function _recaptcha_aes_pad($val) {
276 $block_size = 16;
277 $numpad = $block_size - (strlen ($val) % $block_size);
278 return str_pad($val, strlen ($val) + $numpad, chr($numpad));
281 /* Mailhide related code */
283 function _recaptcha_aes_encrypt($val,$ky) {
284 if (! function_exists ("mcrypt_encrypt")) {
285 die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
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");
294 function _recaptcha_mailhide_urlbase64 ($x) {
295 return strtr(base64_encode ($x), '+/', '-_');
298 /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
299 function recaptcha_mailhide_url($pubkey, $privkey, $email) {
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, " .
302 "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
306 $ky = pack('H*', $privkey);
307 $cryptmail = _recaptcha_aes_encrypt ($email, $ky);
309 return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
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
317 function _recaptcha_mailhide_email_parts ($email) {
318 $arr = preg_split("/@/", $email );
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);
327 return $arr;
331 * Gets html to display an email address given a public an private key.
332 * to get a key, go to:
334 * http://www.google.com/recaptcha/mailhide/apikey
336 function recaptcha_mailhide_html($pubkey, $privkey, $email) {
337 $emailparts = _recaptcha_mailhide_email_parts ($email);
338 $url = recaptcha_mailhide_url ($pubkey, $privkey, $email);
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]);