[ Index ]

PHP Cross Reference of Moodle 1.9.3 [Build 15-Oct-2008]

title

Body

[close]

/lib/ -> recaptchalib.php (source)

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


Generated: Wed Jan 14 11:33:29 2009 Cross-referenced by PHPXref 0.7