fix image text
[pear] / Services / Recaptcha.php
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  *          https://www.google.com/recaptcha/admin/create
8  *    - Discussion group
9  *          http://groups.google.com/group/recaptcha
10  *
11  * Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
12  * AUTHORS:
13  *   Mike Crawford
14  *   Ben Maurer
15  *
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:
22  *
23  * The above copyright notice and this permission notice shall be included in
24  * all copies or substantial portions of the Software.
25  *
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.
33  */
34
35  
36 /**
37  * A Services_Recaptcha_Response is returned from recaptcha_check_answer()
38  */
39 class Services_Recaptcha_Response {
40         var $is_valid;
41         var $error;
42 }
43 /**
44  * The reCAPTCHA server URL's
45  */
46
47  
48 class Services_Recptcha {
49     
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";
53
54     /**
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
58      */
59     static function _qsencode ($data)
60     {
61         $req = "";
62         foreach ( $data as $key => $value )
63                 $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';
64
65         // Cut the last '&'
66         $req=substr($req,0,strlen($req)-1);
67         return $req;
68     }
69
70     
71     
72     /**
73      * Submits an HTTP POST to a reCAPTCHA server
74      * @param string $host
75      * @param string $path
76      * @param array $data
77      * @param int port
78      * @return array response
79      */
80     static function _http_post($host, $path, $data, $port = 80)
81     {
82
83         $req = self::_qsencode ($data);
84
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;
92
93         $response = '';
94         if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
95                 die ('Could not open socket');
96         }
97
98         fwrite($fs, $http_request);
99
100         while ( !feof($fs) )
101                 $response .= fgets($fs, 1160); // One TCP-IP packet
102         fclose($fs);
103         $response = explode("\r\n\r\n", $response, 2);
104
105         return $response;
106     }
107
108     
109     
110     /**
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)
117     
118      * @return string - The HTML to be embedded in the user's form.
119      */
120     static function get_html ($pubkey, $error = null, $use_ssl = false)
121     {
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>");
124         }
125         
126         if ($use_ssl) {
127                 $server = self::$API_SECURE_SERVER;
128         } else {
129                 $server = self::$API_SERVER;
130         }
131
132         $errorpart = "";
133         if ($error) {
134            $errorpart = "&amp;error=" . $error;
135         }
136         return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
137
138         <noscript>
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"/>
142         </noscript>';
143     }
144     
145
146
147
148     
149     
150     /**
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
158       */
159     static function check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array())
160     {
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>");
163         }
164
165         if ($remoteip == null || $remoteip == '') {
166                 die ("For security reasons, you must pass the remote ip to reCAPTCHA");
167         }
168
169         
170         
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;
177         }
178
179         $response = self::_http_post (self::$VERIFY_SERVER, "/recaptcha/api/verify",
180                                           array (
181                                                  'privatekey' => $privkey,
182                                                  'remoteip' => $remoteip,
183                                                  'challenge' => $challenge,
184                                                  'response' => $response
185                                                  ) + $extra_params
186                                           );
187
188         $answers = explode ("\n", $response [1]);
189         $recaptcha_response = new Services_Recaptcha_Response();
190
191         if (trim ($answers [0]) == 'true') {
192                 $recaptcha_response->is_valid = true;
193         }
194         else {
195                 $recaptcha_response->is_valid = false;
196                 $recaptcha_response->error = $answers [1];
197         }
198         return $recaptcha_response;
199     
200     }
201     
202     /**
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
208      */
209     static function get_signup_url ($domain = null, $appname = null)
210     {
211         return "https://www.google.com/recaptcha/admin/create?" .  self::_qsencode (array ('domains' => $domain, 'app' => $appname));
212     }
213     
214     static function _aes_pad($val)
215     {
216         $block_size = 16;
217         $numpad = $block_size - (strlen ($val) % $block_size);
218         return str_pad($val, strlen ($val) + $numpad, chr($numpad));
219     }
220     
221     /* Mailhide related code */
222     
223     static function _aes_encrypt($val,$ky)
224     {
225         if (! function_exists ("mcrypt_encrypt")) {
226                 die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
227         }
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");
232     }
233
234
235     static function _mailhide_urlbase64 ($x)
236     {
237         return strtr(base64_encode ($x), '+/', '-_');
238     }
239
240     /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
241     static function mailhide_url($pubkey, $privkey, $email)
242     {
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>");
246         }
247         
248
249         $ky = pack('H*', $privkey);
250         $cryptmail = self::_aes_encrypt ($email, $ky);
251         
252         return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . self::_mailhide_urlbase64 ($cryptmail);
253     }
254
255     /**
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
259      */
260     static function _mailhide_email_parts ($email)
261     {
262         $arr = preg_split("/@/", $email );
263
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);
268         } else {
269                 $arr[0] = substr ($arr[0], 0, 4);
270         }
271         return $arr;
272     }
273
274     /**
275      * Gets html to display an email address given a public an private key.
276      * to get a key, go to:
277      *
278      * http://www.google.com/recaptcha/mailhide/apikey
279      */
280     static function mailhide_html($pubkey, $privkey, $email)
281     {
282         $emailparts = self::_mailhide_email_parts ($email);
283         $url = self::mailhide_url ($pubkey, $privkey, $email);
284         
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]);
289
290     }
291
292 }