Merge branch 'MDL-27515_m19' of git://github.com/rwijaya/moodle into MOODLE_19_STABLE
[moodle.git] / lib / recaptchalib.php
blobadddbb8075b680718cb99e7492867b8ec1261474
1 <?php
2 /*
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 * http://recaptcha.net/api/getkey
8 * - Discussion group
9 * http://groups.google.com/group/recaptcha
11 * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
12 * AUTHORS:
13 * Mike Crawford
14 * Ben Maurer
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
32 * THE SOFTWARE.
35 /**
36 * The reCAPTCHA server URL's
38 define("RECAPTCHA_API_SERVER", "http://api.recaptcha.net");
39 define("RECAPTCHA_API_SECURE_SERVER", "https://api-secure.recaptcha.net");
40 define("RECAPTCHA_VERIFY_SERVER", "api-verify.recaptcha.net");
42 /**
43 * Encodes the given data into a query string format
44 * @param $data - array of string elements to be encoded
45 * @return string - encoded request
47 function _recaptcha_qsencode ($data) {
48 $req = "";
49 foreach ( $data as $key => $value )
50 $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';
52 // Cut the last '&'
53 $req=substr($req,0,strlen($req)-1);
54 return $req;
59 /**
60 * Submits an HTTP POST to a reCAPTCHA server
61 * @param string $host
62 * @param string $path
63 * @param array $data
64 * @param int port
65 * @return array response
67 function _recaptcha_http_post($host, $path, $data, $port = 80, $https=false) {
68 global $CFG;
69 $protocol = 'http';
70 if ($https) {
71 $protocol = 'https';
74 require_once $CFG->libdir . '/filelib.php';
76 $req = _recaptcha_qsencode ($data);
78 $headers = array();
79 $headers['Host'] = $host;
80 $headers['Content-Type'] = 'application/x-www-form-urlencoded';
81 $headers['Content-Length'] = strlen($req);
82 $headers['User-Agent'] = 'reCAPTCHA/PHP';
84 $results = download_file_content("$protocol://" . $host . $path, $headers, $data, false, 300, 20, true);
86 if ($results) {
87 return array(1 => $results);
88 } else {
89 return false;
95 /**
96 * Gets the challenge HTML (javascript and non-javascript version).
97 * This is called from the browser, and the resulting reCAPTCHA HTML widget
98 * is embedded within the HTML form it was called from.
99 * @param string $pubkey A public key for reCAPTCHA
100 * @param string $error The error given by reCAPTCHA (optional, default is null)
101 * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
103 * @return string - The HTML to be embedded in the user's form.
105 function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false) {
106 global $CFG;
108 $recaptchatype = optional_param('recaptcha', 'image', PARAM_TEXT);
110 if ($pubkey == null || $pubkey == '') {
111 die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>");
114 if ($use_ssl) {
115 $server = RECAPTCHA_API_SECURE_SERVER;
116 } else {
117 $server = RECAPTCHA_API_SERVER;
120 $errorpart = "";
121 if ($error) {
122 $errorpart = "&amp;error=" . $error;
125 require_once $CFG->libdir . '/filelib.php';
126 $html = download_file_content($server . '/noscript?k=' . $pubkey . $errorpart, null, null, false, 300, 20, true);
127 preg_match('/image\?c\=([A-Za-z0-9\-\_]*)\"/', $html, $matches);
128 $challenge_hash = $matches[1];
129 $image_url = $server . '/image?c=' . $challenge_hash;
131 $strincorrectpleasetryagain = get_string('incorrectpleasetryagain', 'auth');
132 $strenterthewordsabove = get_string('enterthewordsabove', 'auth');
133 $strenterthenumbersyouhear = get_string('enterthenumbersyouhear', 'auth');
134 $strgetanothercaptcha = get_string('getanothercaptcha', 'auth');
135 $strgetanaudiocaptcha = get_string('getanaudiocaptcha', 'auth');
136 $strgetanimagecaptcha = get_string('getanimagecaptcha', 'auth');
138 $return = '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
139 <noscript>
140 <div id="recaptcha_widget_noscript">
141 <div id="recaptcha_image_noscript"><img src="' . $image_url . '" alt="reCAPTCHA"/></div>';
143 if ($error == 'incorrect-captcha-sol') {
144 $return .= '<div class="recaptcha_only_if_incorrect_sol" style="color:red">' . $strincorrectpleasetryagain . '</div>';
147 if ($recaptchatype == 'image') {
148 $return .= '<span class="recaptcha_only_if_image">' . $strenterthewordsabove . '</span>';
149 } elseif ($recaptchatype == 'audio') {
150 $return .= '<span class="recaptcha_only_if_audio">' . $strenterthenumbersyouhear . '</span>';
153 $return .= '<input type="text" id="recaptcha_response_field_noscript" name="recaptcha_response_field" />';
154 $return .= '<input type="hidden" id="recaptcha_challenge_field_noscript" name="recaptcha_challenge_field" value="' . $challenge_hash . '" />';
155 $return .= '<div><a href="signup.php">' . $strgetanothercaptcha . '</a></div>';
157 // Disabling audio recaptchas for now: not language-independent
159 if ($recaptchatype == 'image') {
160 $return .= '<div class="recaptcha_only_if_image"><a href="signup.php?recaptcha=audio">' . $strgetanaudiocaptcha . '</a></div>';
161 } elseif ($recaptchatype == 'audio') {
162 $return .= '<div class="recaptcha_only_if_audio"><a href="signup.php?recaptcha=image">' . $strgetanimagecaptcha . '</a></div>';
166 $return .= '
167 </div>
168 </noscript>';
170 return $return;
177 * A ReCaptchaResponse is returned from recaptcha_check_answer()
179 class ReCaptchaResponse {
180 var $is_valid;
181 var $error;
186 * Calls an HTTP POST function to verify if the user's guess was correct
187 * @param string $privkey
188 * @param string $remoteip
189 * @param string $challenge
190 * @param string $response
191 * @return ReCaptchaResponse
193 function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $https=false)
195 if ($privkey == null || $privkey == '') {
196 die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>");
199 if ($remoteip == null || $remoteip == '') {
200 die ("For security reasons, you must pass the remote ip to reCAPTCHA");
205 //discard spam submissions
206 if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
207 $recaptcha_response = new ReCaptchaResponse();
208 $recaptcha_response->is_valid = false;
209 $recaptcha_response->error = 'incorrect-captcha-sol';
210 return $recaptcha_response;
213 $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/verify",
214 array (
215 'privatekey' => $privkey,
216 'remoteip' => $remoteip,
217 'challenge' => $challenge,
218 'response' => $response
220 $https
223 $answers = explode ("\n", $response [1]);
224 $recaptcha_response = new ReCaptchaResponse();
226 if (trim ($answers [0]) == 'true') {
227 $recaptcha_response->is_valid = true;
229 else {
230 $recaptcha_response->is_valid = false;
231 $recaptcha_response->error = $answers [1];
233 return $recaptcha_response;
238 * gets a URL where the user can sign up for reCAPTCHA. If your application
239 * has a configuration page where you enter a key, you should provide a link
240 * using this function.
241 * @param string $domain The domain where the page is hosted
242 * @param string $appname The name of your application
244 function recaptcha_get_signup_url ($domain = null, $appname = null) {
245 return "http://recaptcha.net/api/getkey?" . _recaptcha_qsencode (array ('domain' => $domain, 'app' => $appname));
248 function _recaptcha_aes_pad($val) {
249 $block_size = 16;
250 $numpad = $block_size - (strlen ($val) % $block_size);
251 return str_pad($val, strlen ($val) + $numpad, chr($numpad));
254 /* Mailhide related code */
256 function _recaptcha_aes_encrypt($val,$ky) {
257 if (! function_exists ("mcrypt_encrypt")) {
258 die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
260 $mode=MCRYPT_MODE_CBC;
261 $enc=MCRYPT_RIJNDAEL_128;
262 $val=_recaptcha_aes_pad($val);
263 return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
267 function _recaptcha_mailhide_urlbase64 ($x) {
268 return strtr(base64_encode ($x), '+/', '-_');
271 /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
272 function recaptcha_mailhide_url($pubkey, $privkey, $email) {
273 if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
274 die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
275 "you can do so at <a href='http://mailhide.recaptcha.net/apikey'>http://mailhide.recaptcha.net/apikey</a>");
279 $ky = pack('H*', $privkey);
280 $cryptmail = _recaptcha_aes_encrypt ($email, $ky);
282 return "http://mailhide.recaptcha.net/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
286 * gets the parts of the email to expose to the user.
287 * eg, given johndoe@example,com return ["john", "example.com"].
288 * the email is then displayed as john...@example.com
290 function _recaptcha_mailhide_email_parts ($email) {
291 $arr = preg_split("/@/", $email );
293 if (strlen ($arr[0]) <= 4) {
294 $arr[0] = substr ($arr[0], 0, 1);
295 } else if (strlen ($arr[0]) <= 6) {
296 $arr[0] = substr ($arr[0], 0, 3);
297 } else {
298 $arr[0] = substr ($arr[0], 0, 4);
300 return $arr;
304 * Gets html to display an email address given a public an private key.
305 * to get a key, go to:
307 * http://mailhide.recaptcha.net/apikey
309 function recaptcha_mailhide_html($pubkey, $privkey, $email) {
310 $emailparts = _recaptcha_mailhide_email_parts ($email);
311 $url = recaptcha_mailhide_url ($pubkey, $privkey, $email);
313 return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
314 "' 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]);