]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/reCaptcha/recaptchalib.php
Release 6.5.0
[Github/sugarcrm.git] / include / reCaptcha / recaptchalib.php
1 <?php
2
3
4 /*
5  * This is a PHP library that handles calling reCAPTCHA.
6  *    - Documentation and latest version
7  *          http://recaptcha.net/plugins/php/
8  *    - Get a reCAPTCHA API Key
9  *          http://recaptcha.net/api/getkey
10  *    - Discussion group
11  *          http://groups.google.com/group/recaptcha
12  *
13  * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
14  * AUTHORS:
15  *   Mike Crawford
16  *   Ben Maurer
17  *
18  * Permission is hereby granted, free of charge, to any person obtaining a copy
19  * of this software and associated documentation files (the "Software"), to deal
20  * in the Software without restriction, including without limitation the rights
21  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22  * copies of the Software, and to permit persons to whom the Software is
23  * furnished to do so, subject to the following conditions:
24  *
25  * The above copyright notice and this permission notice shall be included in
26  * all copies or substantial portions of the Software.
27  *
28  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
34  * THE SOFTWARE.
35  */
36
37 /**
38  * The reCAPTCHA server URL's
39  */
40 define("RECAPTCHA_API_SERVER", "http://api.recaptcha.net");
41 define("RECAPTCHA_API_SECURE_SERVER", "https://api-secure.recaptcha.net");
42 define("RECAPTCHA_VERIFY_SERVER", "api-verify.recaptcha.net");
43
44 /**
45  * Encodes the given data into a query string format
46  * @param $data - array of string elements to be encoded
47  * @return string - encoded request
48  */
49 function _recaptcha_qsencode ($data) {
50         $req = "";
51         foreach ( $data as $key => $value )
52                 $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';
53
54         // Cut the last '&'
55         $req=substr($req,0,strlen($req)-1);
56         return $req;
57 }
58
59
60
61 /**
62  * Submits an HTTP POST to a reCAPTCHA server
63  * @param string $host
64  * @param string $path
65  * @param array $data
66  * @param int port
67  * @return array response
68  */
69 function _recaptcha_http_post($host, $path, $data, $port = 80) {
70
71         $req = _recaptcha_qsencode ($data);
72
73         $http_request  = "POST $path HTTP/1.0\r\n";
74         $http_request .= "Host: $host\r\n";
75         $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
76         $http_request .= "Content-Length: " . strlen($req) . "\r\n";
77         $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
78         $http_request .= "\r\n";
79         $http_request .= $req;
80
81         $response = '';
82         if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
83                 die ('Could not open socket');
84         }
85
86         fwrite($fs, $http_request);
87
88         while ( !feof($fs) )
89                 $response .= fgets($fs, 1160); // One TCP-IP packet
90         fclose($fs);
91         $response = explode("\r\n\r\n", $response, 2);
92
93         return $response;
94 }
95
96
97
98 /**
99  * Gets the challenge HTML (javascript and non-javascript version).
100  * This is called from the browser, and the resulting reCAPTCHA HTML widget
101  * is embedded within the HTML form it was called from.
102  * @param string $pubkey A public key for reCAPTCHA
103  * @param string $error The error given by reCAPTCHA (optional, default is null)
104  * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
105
106  * @return string - The HTML to be embedded in the user's form.
107  */
108 function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false)
109 {
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>");
112         }
113         
114         if ($use_ssl) {
115                 $server = RECAPTCHA_API_SECURE_SERVER;
116         } else {
117                 $server = RECAPTCHA_API_SERVER;
118         }
119
120         $errorpart = "";
121         if ($error) {
122            $errorpart = "&amp;error=" . $error;
123         }
124         return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
125
126         <noscript>
127                 <iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
128                 <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
129                 <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
130         </noscript>';
131 }
132
133
134
135
136 /**
137  * A ReCaptchaResponse is returned from recaptcha_check_answer()
138  */
139 class ReCaptchaResponse {
140         var $is_valid;
141         var $error;
142 }
143
144
145 /**
146   * Calls an HTTP POST function to verify if the user's guess was correct
147   * @param string $privkey
148   * @param string $remoteip
149   * @param string $challenge
150   * @param string $response
151   * @param array $extra_params an array of extra variables to post to the server
152   * @return ReCaptchaResponse
153   */
154 function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array())
155 {
156         if ($privkey == null || $privkey == '') {
157                 die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>");
158         }
159
160         if ($remoteip == null || $remoteip == '') {
161                 die ("For security reasons, you must pass the remote ip to reCAPTCHA");
162         }
163
164         
165         
166         //discard spam submissions
167         if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
168                 $recaptcha_response = new ReCaptchaResponse();
169                 $recaptcha_response->is_valid = false;
170                 $recaptcha_response->error = 'incorrect-captcha-sol';
171                 return $recaptcha_response;
172         }
173
174         $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/verify",
175                                           array (
176                                                  'privatekey' => $privkey,
177                                                  'remoteip' => $remoteip,
178                                                  'challenge' => $challenge,
179                                                  'response' => $response
180                                                  ) + $extra_params
181                                           );
182
183         $answers = explode ("\n", $response [1]);
184         $recaptcha_response = new ReCaptchaResponse();
185
186         if (trim ($answers [0]) == 'true') {
187                 $recaptcha_response->is_valid = true;
188         }
189         else {
190                 $recaptcha_response->is_valid = false;
191                 $recaptcha_response->error = $answers [1];
192         }
193         return $recaptcha_response;
194
195 }
196
197 /**
198  * gets a URL where the user can sign up for reCAPTCHA. If your application
199  * has a configuration page where you enter a key, you should provide a link
200  * using this function.
201  * @param string $domain The domain where the page is hosted
202  * @param string $appname The name of your application
203  */
204 function recaptcha_get_signup_url ($domain = null, $appname = null) {
205         return "http://recaptcha.net/api/getkey?" .  _recaptcha_qsencode (array ('domain' => $domain, 'app' => $appname));
206 }
207
208 function _recaptcha_aes_pad($val) {
209         $block_size = 16;
210         $numpad = $block_size - (strlen ($val) % $block_size);
211         return str_pad($val, strlen ($val) + $numpad, chr($numpad));
212 }
213
214 /* Mailhide related code */
215
216 function _recaptcha_aes_encrypt($val,$ky) {
217         if (! function_exists ("mcrypt_encrypt")) {
218                 die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
219         }
220         $mode=MCRYPT_MODE_CBC;   
221         $enc=MCRYPT_RIJNDAEL_128;
222         $val=_recaptcha_aes_pad($val);
223         return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
224 }
225
226
227 function _recaptcha_mailhide_urlbase64 ($x) {
228         return strtr(base64_encode ($x), '+/', '-_');
229 }
230
231 /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
232 function recaptcha_mailhide_url($pubkey, $privkey, $email) {
233         if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
234                 die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
235                      "you can do so at <a href='http://mailhide.recaptcha.net/apikey'>http://mailhide.recaptcha.net/apikey</a>");
236         }
237         
238
239         $ky = pack('H*', $privkey);
240         $cryptmail = _recaptcha_aes_encrypt ($email, $ky);
241         
242         return "http://mailhide.recaptcha.net/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
243 }
244
245 /**
246  * gets the parts of the email to expose to the user.
247  * eg, given johndoe@example,com return ["john", "example.com"].
248  * the email is then displayed as john...@example.com
249  */
250 function _recaptcha_mailhide_email_parts ($email) {
251         $arr = preg_split("/@/", $email );
252
253         if (strlen ($arr[0]) <= 4) {
254                 $arr[0] = substr ($arr[0], 0, 1);
255         } else if (strlen ($arr[0]) <= 6) {
256                 $arr[0] = substr ($arr[0], 0, 3);
257         } else {
258                 $arr[0] = substr ($arr[0], 0, 4);
259         }
260         return $arr;
261 }
262
263 /**
264  * Gets html to display an email address given a public an private key.
265  * to get a key, go to:
266  *
267  * http://mailhide.recaptcha.net/apikey
268  */
269 function recaptcha_mailhide_html($pubkey, $privkey, $email) {
270         $emailparts = _recaptcha_mailhide_email_parts ($email);
271         $url = recaptcha_mailhide_url ($pubkey, $privkey, $email);
272         
273         return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
274                 "' 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]);
275
276 }
277
278 ?>