PageRenderTime 188ms CodeModel.GetById 38ms RepoModel.GetById 6ms app.codeStats 0ms

/lib/recaptchalib.php

https://gitlab.com/unofficial-mirrors/moodle
PHP | 343 lines | 167 code | 58 blank | 118 comment | 48 complexity | 5a71318ed15418b03388e8c8632f2b79 MD5 | raw file
  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. * {@link 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( $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. *
  59. * @global object
  60. * @param string $host
  61. * @param string $path
  62. * @param array $data
  63. * @param int port
  64. * @return array response
  65. */
  66. function _recaptcha_http_post($host, $path, $data, $port = 80, $https=false) {
  67. global $CFG;
  68. $protocol = 'http';
  69. if ($https) {
  70. $protocol = 'https';
  71. }
  72. require_once $CFG->libdir . '/filelib.php';
  73. $req = _recaptcha_qsencode ($data);
  74. $headers = array();
  75. $headers['Host'] = $host;
  76. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  77. $headers['Content-Length'] = strlen($req);
  78. $headers['User-Agent'] = 'reCAPTCHA/PHP';
  79. $results = download_file_content("$protocol://" . $host . $path, $headers, $data, false, 300, 20, true);
  80. if ($results) {
  81. return array(1 => $results);
  82. } else {
  83. return false;
  84. }
  85. }
  86. /**
  87. * Return the recaptcha challenge and image and javascript urls
  88. *
  89. * @param string $server server url
  90. * @param string $pubkey public key
  91. * @param string $errorpart error part to append
  92. * @return array the challenge hash, image and javascript url
  93. * @since Moodle 3.2
  94. */
  95. function recaptcha_get_challenge_hash_and_urls($server, $pubkey, $errorpart = '') {
  96. global $CFG;
  97. require_once($CFG->libdir . '/filelib.php');
  98. $html = download_file_content($server . '/noscript?k=' . $pubkey . $errorpart, null, null, false, 300, 20, true);
  99. preg_match('/image\?c\=([A-Za-z0-9\-\_]*)\"/', $html, $matches);
  100. $challengehash = $matches[1];
  101. $imageurl = $server . '/image?c=' . $challengehash;
  102. $jsurl = $server . '/challenge?k=' . $pubkey . $errorpart;
  103. return array($challengehash, $imageurl, $jsurl);
  104. }
  105. /**
  106. * Gets the challenge HTML (javascript and non-javascript version).
  107. * This is called from the browser, and the resulting reCAPTCHA HTML widget
  108. * is embedded within the HTML form it was called from.
  109. *
  110. * @global object
  111. * @param string $pubkey A public key for reCAPTCHA
  112. * @param string $error The error given by reCAPTCHA (optional, default is null)
  113. * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
  114. * @return string - The HTML to be embedded in the user's form.
  115. */
  116. function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false) {
  117. global $PAGE;
  118. $recaptchatype = optional_param('recaptcha', 'image', PARAM_TEXT);
  119. if ($pubkey == null || $pubkey == '') {
  120. 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>");
  121. }
  122. if ($use_ssl) {
  123. $server = RECAPTCHA_API_SECURE_SERVER;
  124. } else {
  125. $server = RECAPTCHA_API_SERVER;
  126. }
  127. $errorpart = "";
  128. if ($error) {
  129. $errorpart = "&amp;error=" . $error;
  130. }
  131. list($challengehash, $imageurl, $jsurl) = recaptcha_get_challenge_hash_and_urls($server, $pubkey, $errorpart);
  132. $strincorrectpleasetryagain = get_string('incorrectpleasetryagain', 'auth');
  133. $strenterthewordsabove = get_string('enterthewordsabove', 'auth');
  134. $strenterthenumbersyouhear = get_string('enterthenumbersyouhear', 'auth');
  135. $strgetanothercaptcha = get_string('getanothercaptcha', 'auth');
  136. $strgetanaudiocaptcha = get_string('getanaudiocaptcha', 'auth');
  137. $strgetanimagecaptcha = get_string('getanimagecaptcha', 'auth');
  138. $return = html_writer::script('', $jsurl);
  139. $return .= '<noscript>
  140. <div id="recaptcha_widget_noscript">
  141. <div id="recaptcha_image_noscript"><img src="' . $imageurl . '" alt="reCAPTCHA"/></div>';
  142. if ($error == 'incorrect-captcha-sol') {
  143. $return .= '<div class="recaptcha_only_if_incorrect_sol" style="color:red">' . $strincorrectpleasetryagain . '</div>';
  144. }
  145. if ($recaptchatype == 'image') {
  146. $return .= '<span class="recaptcha_only_if_image">' . $strenterthewordsabove . '</span>';
  147. } elseif ($recaptchatype == 'audio') {
  148. $return .= '<span class="recaptcha_only_if_audio">' . $strenterthenumbersyouhear . '</span>';
  149. }
  150. $return .= '<input type="text" id="recaptcha_response_field_noscript" name="recaptcha_response_field" />';
  151. $return .= '<input type="hidden" id="recaptcha_challenge_field_noscript" name="recaptcha_challenge_field" value="' . $challengehash . '" />';
  152. $return .= '<div><a href="signup.php">' . $strgetanothercaptcha . '</a></div>';
  153. // Disabling audio recaptchas for now: not language-independent
  154. /*
  155. if ($recaptchatype == 'image') {
  156. $return .= '<div class="recaptcha_only_if_image"><a href="signup.php?recaptcha=audio">' . $strgetanaudiocaptcha . '</a></div>';
  157. } elseif ($recaptchatype == 'audio') {
  158. $return .= '<div class="recaptcha_only_if_audio"><a href="signup.php?recaptcha=image">' . $strgetanimagecaptcha . '</a></div>';
  159. }
  160. */
  161. $return .= '
  162. </div>
  163. </noscript>';
  164. return $return;
  165. }
  166. /**
  167. * A ReCaptchaResponse is returned from recaptcha_check_answer()
  168. *
  169. * @package moodlecore
  170. * @copyright (c) 2007 reCAPTCHA -- {@link http://www.google.com/recaptcha}
  171. */
  172. class ReCaptchaResponse {
  173. var $is_valid;
  174. var $error;
  175. }
  176. /**
  177. * Calls an HTTP POST function to verify if the user's guess was correct
  178. * @param string $privkey
  179. * @param string $remoteip
  180. * @param string $challenge
  181. * @param string $response
  182. * @return ReCaptchaResponse
  183. */
  184. function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $https=false)
  185. {
  186. if ($privkey == null || $privkey == '') {
  187. 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>");
  188. }
  189. if ($remoteip == null || $remoteip == '') {
  190. die ("For security reasons, you must pass the remote ip to reCAPTCHA");
  191. }
  192. //discard spam submissions
  193. if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
  194. $recaptcha_response = new ReCaptchaResponse();
  195. $recaptcha_response->is_valid = false;
  196. $recaptcha_response->error = 'incorrect-captcha-sol';
  197. return $recaptcha_response;
  198. }
  199. $response = _recaptcha_http_post(RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify",
  200. array (
  201. 'privatekey' => $privkey,
  202. 'remoteip' => $remoteip,
  203. 'challenge' => $challenge,
  204. 'response' => $response
  205. ),
  206. $https
  207. );
  208. $answers = explode ("\n", $response [1]);
  209. $recaptcha_response = new ReCaptchaResponse();
  210. if (trim ($answers [0]) == 'true') {
  211. $recaptcha_response->is_valid = true;
  212. }
  213. else {
  214. $recaptcha_response->is_valid = false;
  215. $recaptcha_response->error = $answers [1];
  216. }
  217. return $recaptcha_response;
  218. }
  219. /**
  220. * gets a URL where the user can sign up for reCAPTCHA. If your application
  221. * has a configuration page where you enter a key, you should provide a link
  222. * using this function.
  223. * @param string $domain The domain where the page is hosted
  224. * @param string $appname The name of your application
  225. */
  226. function recaptcha_get_signup_url ($domain = null, $appname = null) {
  227. return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname));
  228. }
  229. function _recaptcha_aes_pad($val) {
  230. $block_size = 16;
  231. $numpad = $block_size - (strlen ($val) % $block_size);
  232. return str_pad($val, strlen ($val) + $numpad, chr($numpad));
  233. }
  234. /* Mailhide related code */
  235. function _recaptcha_aes_encrypt($val,$ky) {
  236. if (! function_exists ("mcrypt_encrypt")) {
  237. die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
  238. }
  239. $mode=MCRYPT_MODE_CBC;
  240. $enc=MCRYPT_RIJNDAEL_128;
  241. $val=_recaptcha_aes_pad($val);
  242. return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  243. }
  244. function _recaptcha_mailhide_urlbase64 ($x) {
  245. return strtr(base64_encode ($x), '+/', '-_');
  246. }
  247. /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
  248. function recaptcha_mailhide_url($pubkey, $privkey, $email) {
  249. if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
  250. die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
  251. "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
  252. }
  253. $ky = pack('H*', $privkey);
  254. $cryptmail = _recaptcha_aes_encrypt ($email, $ky);
  255. return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
  256. }
  257. /**
  258. * gets the parts of the email to expose to the user.
  259. * eg, given johndoe@example,com return ["john", "example.com"].
  260. * the email is then displayed as john...@example.com
  261. */
  262. function _recaptcha_mailhide_email_parts ($email) {
  263. $arr = preg_split("/@/", $email );
  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. * Gets html to display an email address given a public an private key.
  275. * to get a key, go to:
  276. *
  277. * http://www.google.com/recaptcha/mailhide/apikey
  278. */
  279. function recaptcha_mailhide_html($pubkey, $privkey, $email) {
  280. $emailparts = _recaptcha_mailhide_email_parts ($email);
  281. $url = recaptcha_mailhide_url ($pubkey, $privkey, $email);
  282. return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
  283. "' 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]);
  284. }