PageRenderTime 45ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/recaptchalib.php

https://bitbucket.org/ceu/moodle_demo
PHP | 325 lines | 162 code | 58 blank | 105 comment | 48 complexity | 6b1e748a1b221e32c024ea0e18ced507 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, LGPL-2.1
  1. <?php
  2. /*
  3. * This is a PHP library that handles calling reCAPTCHA.
  4. * - Documentation and latest version
  5. * {@link http://code.google.com/apis/recaptcha/docs/php.html}
  6. * - Get a reCAPTCHA API Key
  7. * {@link https://www.google.com/recaptcha/admin/create}
  8. * - Discussion group
  9. * http://groups.google.com/group/recaptcha
  10. *
  11. * Copyright (c) 2007 reCAPTCHA -- {@link http://www.google.com/recaptcha}
  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. * @package moodlecore
  35. * @copyright (c) 2007 reCAPTCHA -- {@link http://www.google.com/recaptcha}
  36. */
  37. /**
  38. * The reCAPTCHA server URL's
  39. */
  40. define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api");
  41. define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api");
  42. define("RECAPTCHA_VERIFY_SERVER", "www.google.com");
  43. /**
  44. * Encodes the given data into a query string format
  45. * @param $data - array of string elements to be encoded
  46. * @return string - encoded request
  47. */
  48. function _recaptcha_qsencode ($data) {
  49. $req = "";
  50. foreach ( $data as $key => $value )
  51. $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';
  52. // Cut the last '&'
  53. $req=substr($req,0,strlen($req)-1);
  54. return $req;
  55. }
  56. /**
  57. * Submits an HTTP POST to a reCAPTCHA server
  58. * @param string $host
  59. * @param string $path
  60. * @param array $data
  61. * @param int port
  62. * @return array response
  63. */
  64. function _recaptcha_http_post($host, $path, $data, $port = 80, $https=false) {
  65. global $CFG;
  66. $protocol = 'http';
  67. if ($https) {
  68. $protocol = 'https';
  69. }
  70. require_once $CFG->libdir . '/filelib.php';
  71. $req = _recaptcha_qsencode ($data);
  72. $headers = array();
  73. $headers['Host'] = $host;
  74. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  75. $headers['Content-Length'] = strlen($req);
  76. $headers['User-Agent'] = 'reCAPTCHA/PHP';
  77. $results = download_file_content("$protocol://" . $host . $path, $headers, $data, false, 300, 20, true);
  78. if ($results) {
  79. return array(1 => $results);
  80. } else {
  81. return false;
  82. }
  83. }
  84. /**
  85. * Gets the challenge HTML (javascript and non-javascript version).
  86. * This is called from the browser, and the resulting reCAPTCHA HTML widget
  87. * is embedded within the HTML form it was called from.
  88. * @param string $pubkey A public key for reCAPTCHA
  89. * @param string $error The error given by reCAPTCHA (optional, default is null)
  90. * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
  91. * @return string - The HTML to be embedded in the user's form.
  92. */
  93. function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false) {
  94. global $CFG;
  95. $recaptchatype = optional_param('recaptcha', 'image', PARAM_TEXT);
  96. if ($pubkey == null || $pubkey == '') {
  97. 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>");
  98. }
  99. if ($use_ssl) {
  100. $server = RECAPTCHA_API_SECURE_SERVER;
  101. } else {
  102. $server = RECAPTCHA_API_SERVER;
  103. }
  104. $errorpart = "";
  105. if ($error) {
  106. $errorpart = "&amp;error=" . $error;
  107. }
  108. require_once $CFG->libdir . '/filelib.php';
  109. $html = download_file_content($server . '/noscript?k=' . $pubkey . $errorpart, null, null, false, 300, 20, true);
  110. preg_match('/image\?c\=([A-Za-z0-9\-\_]*)\"/', $html, $matches);
  111. $challenge_hash = $matches[1];
  112. $image_url = $server . '/image?c=' . $challenge_hash;
  113. $strincorrectpleasetryagain = get_string('incorrectpleasetryagain', 'auth');
  114. $strenterthewordsabove = get_string('enterthewordsabove', 'auth');
  115. $strenterthenumbersyouhear = get_string('enterthenumbersyouhear', 'auth');
  116. $strgetanothercaptcha = get_string('getanothercaptcha', 'auth');
  117. $strgetanaudiocaptcha = get_string('getanaudiocaptcha', 'auth');
  118. $strgetanimagecaptcha = get_string('getanimagecaptcha', 'auth');
  119. $return = '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
  120. <noscript>
  121. <div id="recaptcha_widget_noscript">
  122. <div id="recaptcha_image_noscript"><img src="' . $image_url . '" alt="reCAPTCHA"/></div>';
  123. if ($error == 'incorrect-captcha-sol') {
  124. $return .= '<div class="recaptcha_only_if_incorrect_sol" style="color:red">' . $strincorrectpleasetryagain . '</div>';
  125. }
  126. if ($recaptchatype == 'image') {
  127. $return .= '<span class="recaptcha_only_if_image">' . $strenterthewordsabove . '</span>';
  128. } elseif ($recaptchatype == 'audio') {
  129. $return .= '<span class="recaptcha_only_if_audio">' . $strenterthenumbersyouhear . '</span>';
  130. }
  131. $return .= '<input type="text" id="recaptcha_response_field_noscript" name="recaptcha_response_field" />';
  132. $return .= '<input type="hidden" id="recaptcha_challenge_field_noscript" name="recaptcha_challenge_field" value="' . $challenge_hash . '" />';
  133. $return .= '<div><a href="signup.php">' . $strgetanothercaptcha . '</a></div>';
  134. // Disabling audio recaptchas for now: not language-independent
  135. /*
  136. if ($recaptchatype == 'image') {
  137. $return .= '<div class="recaptcha_only_if_image"><a href="signup.php?recaptcha=audio">' . $strgetanaudiocaptcha . '</a></div>';
  138. } elseif ($recaptchatype == 'audio') {
  139. $return .= '<div class="recaptcha_only_if_audio"><a href="signup.php?recaptcha=image">' . $strgetanimagecaptcha . '</a></div>';
  140. }
  141. */
  142. $return .= '
  143. </div>
  144. </noscript>';
  145. return $return;
  146. }
  147. /**
  148. * A ReCaptchaResponse is returned from recaptcha_check_answer()
  149. *
  150. * @package moodlecore
  151. * @copyright (c) 2007 reCAPTCHA -- {@link http://www.google.com/recaptcha}
  152. */
  153. class ReCaptchaResponse {
  154. var $is_valid;
  155. var $error;
  156. }
  157. /**
  158. * Calls an HTTP POST function to verify if the user's guess was correct
  159. * @param string $privkey
  160. * @param string $remoteip
  161. * @param string $challenge
  162. * @param string $response
  163. * @return ReCaptchaResponse
  164. */
  165. function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $https=false)
  166. {
  167. if ($privkey == null || $privkey == '') {
  168. 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>");
  169. }
  170. if ($remoteip == null || $remoteip == '') {
  171. die ("For security reasons, you must pass the remote ip to reCAPTCHA");
  172. }
  173. //discard spam submissions
  174. if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
  175. $recaptcha_response = new ReCaptchaResponse();
  176. $recaptcha_response->is_valid = false;
  177. $recaptcha_response->error = 'incorrect-captcha-sol';
  178. return $recaptcha_response;
  179. }
  180. $response = _recaptcha_http_post(RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify",
  181. array (
  182. 'privatekey' => $privkey,
  183. 'remoteip' => $remoteip,
  184. 'challenge' => $challenge,
  185. 'response' => $response
  186. ),
  187. $https
  188. );
  189. $answers = explode ("\n", $response [1]);
  190. $recaptcha_response = new ReCaptchaResponse();
  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. * gets a URL where the user can sign up for reCAPTCHA. If your application
  202. * has a configuration page where you enter a key, you should provide a link
  203. * using this function.
  204. * @param string $domain The domain where the page is hosted
  205. * @param string $appname The name of your application
  206. */
  207. function recaptcha_get_signup_url ($domain = null, $appname = null) {
  208. return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname));
  209. }
  210. function _recaptcha_aes_pad($val) {
  211. $block_size = 16;
  212. $numpad = $block_size - (strlen ($val) % $block_size);
  213. return str_pad($val, strlen ($val) + $numpad, chr($numpad));
  214. }
  215. /* Mailhide related code */
  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. function _recaptcha_mailhide_urlbase64 ($x) {
  226. return strtr(base64_encode ($x), '+/', '-_');
  227. }
  228. /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
  229. function recaptcha_mailhide_url($pubkey, $privkey, $email) {
  230. if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
  231. die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
  232. "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
  233. }
  234. $ky = pack('H*', $privkey);
  235. $cryptmail = _recaptcha_aes_encrypt ($email, $ky);
  236. return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
  237. }
  238. /**
  239. * gets the parts of the email to expose to the user.
  240. * eg, given johndoe@example,com return ["john", "example.com"].
  241. * the email is then displayed as john...@example.com
  242. */
  243. function _recaptcha_mailhide_email_parts ($email) {
  244. $arr = preg_split("/@/", $email );
  245. if (strlen ($arr[0]) <= 4) {
  246. $arr[0] = substr ($arr[0], 0, 1);
  247. } else if (strlen ($arr[0]) <= 6) {
  248. $arr[0] = substr ($arr[0], 0, 3);
  249. } else {
  250. $arr[0] = substr ($arr[0], 0, 4);
  251. }
  252. return $arr;
  253. }
  254. /**
  255. * Gets html to display an email address given a public an private key.
  256. * to get a key, go to:
  257. *
  258. * http://www.google.com/recaptcha/mailhide/apikey
  259. */
  260. function recaptcha_mailhide_html($pubkey, $privkey, $email) {
  261. $emailparts = _recaptcha_mailhide_email_parts ($email);
  262. $url = recaptcha_mailhide_url ($pubkey, $privkey, $email);
  263. return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
  264. "' 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]);
  265. }
  266. ?>