recaptchalib.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. <?php
  2. /*
  3. * @todo FIXME: Outdated URLs.
  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. * The reCAPTCHA server URL's
  38. */
  39. define("RECAPTCHA_API_SERVER", "http://api.recaptcha.net");
  40. define("RECAPTCHA_API_SECURE_SERVER", "https://api-secure.recaptcha.net");
  41. 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
  46. */
  47. function _recaptcha_qsencode ($data) {
  48. $req = "";
  49. foreach ( $data as $key => $value )
  50. $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';
  51. // Cut the last '&'
  52. $req=substr($req,0,strlen($req)-1);
  53. return $req;
  54. }
  55. /**
  56. * Submits an HTTP POST to a reCAPTCHA server
  57. * @param string $host
  58. * @param string $path
  59. * @param array $data
  60. * @param int port
  61. * @return array response
  62. */
  63. function _recaptcha_http_post($host, $path, $data, $port = 80) {
  64. $req = _recaptcha_qsencode ($data);
  65. $http_request = "POST $path HTTP/1.0\r\n";
  66. $http_request .= "Host: $host\r\n";
  67. $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
  68. $http_request .= "Content-Length: " . strlen($req) . "\r\n";
  69. $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
  70. $http_request .= "\r\n";
  71. $http_request .= $req;
  72. $response = '';
  73. if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
  74. die ('Could not open socket');
  75. }
  76. fwrite($fs, $http_request);
  77. while ( !feof($fs) )
  78. $response .= fgets($fs, 1160); // One TCP-IP packet
  79. fclose($fs);
  80. $response = explode("\r\n\r\n", $response, 2);
  81. return $response;
  82. }
  83. /**
  84. * Gets the challenge HTML (javascript and non-javascript version).
  85. * This is called from the browser, and the resulting reCAPTCHA HTML widget
  86. * is embedded within the HTML form it was called from.
  87. * @param string $pubkey A public key for reCAPTCHA
  88. * @param string $error The error given by reCAPTCHA (optional, default is null)
  89. * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
  90. * @return string - The HTML to be embedded in the user's form.
  91. */
  92. function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false)
  93. {
  94. if ($pubkey == null || $pubkey == '') {
  95. die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>");
  96. }
  97. if ($use_ssl) {
  98. $server = RECAPTCHA_API_SECURE_SERVER;
  99. } else {
  100. $server = RECAPTCHA_API_SERVER;
  101. }
  102. $errorpart = "";
  103. if ($error) {
  104. $errorpart = "&amp;error=" . $error;
  105. }
  106. return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
  107. <noscript>
  108. <iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
  109. <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
  110. <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
  111. </noscript>';
  112. }
  113. /**
  114. * A ReCaptchaResponse is returned from recaptcha_check_answer()
  115. */
  116. class ReCaptchaResponse {
  117. var $is_valid;
  118. var $error;
  119. }
  120. /**
  121. * Calls an HTTP POST function to verify if the user's guess was correct
  122. * @param string $privkey
  123. * @param string $remoteip
  124. * @param string $challenge
  125. * @param string $response
  126. * @param array $extra_params an array of extra variables to post to the server
  127. * @return ReCaptchaResponse
  128. */
  129. function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array())
  130. {
  131. if ($privkey == null || $privkey == '') {
  132. die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>");
  133. }
  134. if ($remoteip == null || $remoteip == '') {
  135. die ("For security reasons, you must pass the remote ip to reCAPTCHA");
  136. }
  137. //discard spam submissions
  138. if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
  139. $recaptcha_response = new ReCaptchaResponse();
  140. $recaptcha_response->is_valid = false;
  141. $recaptcha_response->error = 'incorrect-captcha-sol';
  142. return $recaptcha_response;
  143. }
  144. $response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/verify",
  145. array (
  146. 'privatekey' => $privkey,
  147. 'remoteip' => $remoteip,
  148. 'challenge' => $challenge,
  149. 'response' => $response
  150. ) + $extra_params
  151. );
  152. $answers = explode ("\n", $response [1]);
  153. $recaptcha_response = new ReCaptchaResponse();
  154. if (trim ($answers [0]) == 'true') {
  155. $recaptcha_response->is_valid = true;
  156. }
  157. else {
  158. $recaptcha_response->is_valid = false;
  159. $recaptcha_response->error = $answers [1];
  160. }
  161. return $recaptcha_response;
  162. }
  163. /**
  164. * gets a URL where the user can sign up for reCAPTCHA. If your application
  165. * has a configuration page where you enter a key, you should provide a link
  166. * using this function.
  167. * @param string $domain The domain where the page is hosted
  168. * @param string $appname The name of your application
  169. */
  170. function recaptcha_get_signup_url ($domain = null, $appname = null) {
  171. return "http://recaptcha.net/api/getkey?" . _recaptcha_qsencode (array ('domain' => $domain, 'app' => $appname));
  172. }
  173. function _recaptcha_aes_pad($val) {
  174. $block_size = 16;
  175. $numpad = $block_size - (strlen ($val) % $block_size);
  176. return str_pad($val, strlen ($val) + $numpad, chr($numpad));
  177. }
  178. /* Mailhide related code */
  179. function _recaptcha_aes_encrypt($val,$ky) {
  180. if (! function_exists ("mcrypt_encrypt")) {
  181. die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
  182. }
  183. $mode=MCRYPT_MODE_CBC;
  184. $enc=MCRYPT_RIJNDAEL_128;
  185. $val=_recaptcha_aes_pad($val);
  186. return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  187. }
  188. function _recaptcha_mailhide_urlbase64 ($x) {
  189. return strtr(base64_encode ($x), '+/', '-_');
  190. }
  191. /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
  192. function recaptcha_mailhide_url($pubkey, $privkey, $email) {
  193. if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
  194. die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
  195. "you can do so at <a href='http://mailhide.recaptcha.net/apikey'>http://mailhide.recaptcha.net/apikey</a>");
  196. }
  197. $ky = pack('H*', $privkey);
  198. $cryptmail = _recaptcha_aes_encrypt ($email, $ky);
  199. return "http://mailhide.recaptcha.net/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
  200. }
  201. /**
  202. * gets the parts of the email to expose to the user.
  203. * eg, given johndoe@example,com return ["john", "example.com"].
  204. * the email is then displayed as john...@example.com
  205. */
  206. function _recaptcha_mailhide_email_parts ($email) {
  207. $arr = preg_split("/@/", $email );
  208. if (strlen ($arr[0]) <= 4) {
  209. $arr[0] = substr ($arr[0], 0, 1);
  210. } else if (strlen ($arr[0]) <= 6) {
  211. $arr[0] = substr ($arr[0], 0, 3);
  212. } else {
  213. $arr[0] = substr ($arr[0], 0, 4);
  214. }
  215. return $arr;
  216. }
  217. /**
  218. * Gets html to display an email address given a public an private key.
  219. * to get a key, go to:
  220. *
  221. * http://mailhide.recaptcha.net/apikey
  222. */
  223. function recaptcha_mailhide_html($pubkey, $privkey, $email) {
  224. $emailparts = _recaptcha_mailhide_email_parts ($email);
  225. $url = recaptcha_mailhide_url ($pubkey, $privkey, $email);
  226. return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
  227. "' 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]);
  228. }