reCAPTCHA for cakePHP

By Howard``, 2 Days ago, written in php.
  1. /* This is an easy to use component and helper set for you to get reCAPTCHA(including mailhide) running on your website now. If you don't know what reCAPTCHA is please head to http://recaptcha.net/ now to find out! Please note this code is largely derived off of the library provided for reCAPTCHA - it's just repurposed for ease of use in CakePHP.
  2.  
  3. Create the following files:
  4. app/controllers/components/recaptcha.php
  5. app/views/helpers/recaptcha.php
  6.  
  7.  
  8. code for app/controllers/components/recaptcha.php
  9. */
  10. class RecaptchaComponent extends Object {
  11.         var $publickey = "";
  12.         var $privatekey= "";
  13.        
  14.         var $is_valid = false;
  15.         var $error = "";
  16.        
  17.         function startup(&$controller){
  18.                 Configure::write("RECAPTCHA_API_SERVER","http://api.recaptcha.net");
  19.                 Configure::write("RECAPTCHA_API_SECURE_SERVER","https://api-secure.recaptcha.net");
  20.                 Configure::write("RECAPTCHA_VERIFY_SERVER","api-verify.recaptcha.net");
  21.                 Configure::write("RECAPTCHA_PUB_KEY", $this->publickey);
  22.                 Configure::write("RECAPTCHA_PRIV_KEY", $this->privatekey);
  23.         }
  24.        
  25.         function valid($form){
  26.         if (isset($form['recaptcha_challenge_field']) && isset($form['recaptcha_response_field'])){
  27.                 if($this->recaptcha_check_answer(
  28.                 $this->privatekey,
  29.                 $_SERVER["REMOTE_ADDR"],
  30.                 $form['recaptcha_challenge_field'],
  31.                 $form['recaptcha_response_field']
  32.             ) == 0)
  33.                 return false;
  34.  
  35.             if ($this->is_valid)
  36.                 return true;
  37.         }
  38.         return false;
  39.     }
  40.    
  41.         /**
  42.           * Calls an HTTP POST function to verify if the user's guess was correct
  43.           * @param string $privkey
  44.           * @param string $remoteip
  45.           * @param string $challenge
  46.           * @param string $response
  47.           * @param array $extra_params an array of extra variables to post to the server
  48.           * @return ReCaptchaResponse
  49.           */
  50.         function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array()){
  51.                 if ($privkey == null || $privkey == ''){
  52.                         die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>");
  53.                 }
  54.        
  55.                 if ($remoteip == null || $remoteip == ''){
  56.                         die ("For security reasons, you must pass the remote ip to reCAPTCHA");
  57.                 }              
  58.                        
  59.                 //discard spam submissions
  60.                 if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
  61.                         $this->is_valid = false;
  62.                         $this->error = 'incorrect-captcha-sol';
  63.                         return 0;
  64.                 }
  65.  
  66.                 $response = $this->_recaptcha_http_post(Configure::read('RECAPTCHA_VERIFY_SERVER'), "/verify",
  67.                                                   array (
  68.                                                          'privatekey' => $privkey,
  69.                                                          'remoteip' => $remoteip,
  70.                                                          'challenge' => $challenge,
  71.                                                          'response' => $response
  72.                                                          ) + $extra_params
  73.                                                   );
  74.        
  75.                 $answers = explode ("\n", $response [1]);
  76.                
  77.                 if (trim ($answers [0]) == 'true') {
  78.                         $this->is_valid = true;
  79.                         return 1;
  80.                 }else{
  81.                         $this->is_valid = false;
  82.                         $this->error = $answers [1];
  83.                         return 0;
  84.                 }
  85.         }
  86.        
  87.        
  88.         /**
  89.          * Submits an HTTP POST to a reCAPTCHA server
  90.          * @param string $host
  91.          * @param string $path
  92.          * @param array $data
  93.          * @param int port
  94.          * @return array response
  95.          */
  96.         function _recaptcha_http_post($host, $path, $data, $port = 80) {
  97.  
  98.         $req = $this->_recaptcha_qsencode ($data);
  99.  
  100.         $http_request  = "POST $path HTTP/1.0\r\n";
  101.         $http_request .= "Host: $host\r\n";
  102.         $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
  103.         $http_request .= "Content-Length: " . strlen($req) . "\r\n";
  104.         $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
  105.         $http_request .= "\r\n";
  106.         $http_request .= $req;
  107.  
  108.         $response = '';
  109.         if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
  110.                 die ('Could not open socket');
  111.         }
  112.  
  113.         fwrite($fs, $http_request);
  114.  
  115.         while ( !feof($fs) )
  116.                 $response .= fgets($fs, 1160); // One TCP-IP packet
  117.         fclose($fs);
  118.         $response = explode("\r\n\r\n", $response, 2);
  119.  
  120.         return $response;
  121.         }
  122.        
  123.        
  124.         /**
  125.          * Encodes the given data into a query string format
  126.          * @param $data - array of string elements to be encoded
  127.          * @return string - encoded request
  128.          */
  129.         function _recaptcha_qsencode ($data) {
  130.         $req = "";
  131.         foreach ( $data as $key => $value )
  132.                 $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';
  133.  
  134.         // Cut the last '&'
  135.         $req=substr($req,0,strlen($req)-1);
  136.         return $req;
  137.         }
  138. }
  139.  
  140. /*
  141.  
  142.  
  143.  
  144.  
  145. code for app/views/helpers/recaptcha.php
  146. */
  147. class RecaptchaHelper extends AppHelper {
  148.         var $helpers = array('form');
  149.        
  150.         function display_form($output_method = 'return', $error = null, $use_ssl = false){
  151.                 $data = $this->__form(Configure::read("RECAPTCHA_PUB_KEY"),$error,$use_ssl);
  152.                 if($output_method == "echo")
  153.                         echo $data;
  154.                 else
  155.                         return $data;
  156.         }
  157.        
  158.         function hide_mail($email = '',$output_method = 'return'){
  159.                 $data = $this->recaptcha_mailhide_html(Configure::read('RECAPTCHA_PUB_KEY'), Configure::read('RECAPTCHA_PRIV_KEY'), $email);
  160.                 if($output_method == "echo")
  161.                         echo $data;
  162.                 else
  163.                         return $data;
  164.         }
  165.        
  166.         /**
  167.          * Gets the challenge HTML (javascript and non-javascript version).
  168.          * This is called from the browser, and the resulting reCAPTCHA HTML widget
  169.          * is embedded within the HTML form it was called from.
  170.          * @param string $pubkey A public key for reCAPTCHA
  171.          * @param string $error The error given by reCAPTCHA (optional, default is null)
  172.          * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
  173.        
  174.          * @return string - The HTML to be embedded in the user's form.
  175.          */
  176.         function __form($pubkey, $error = null, $use_ssl = false){
  177.                 if ($pubkey == null || $pubkey == '') {
  178.                         die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>");
  179.                 }
  180.                
  181.                 if ($use_ssl) {
  182.                         $server = Configure::read('RECAPTCHA_API_SECURE_SERVER');
  183.                 } else {
  184.                         $server = Configure::read('RECAPTCHA_API_SERVER');
  185.                 }
  186.        
  187.                 $errorpart = "";
  188.                 if ($error) {
  189.                    $errorpart = "&amp;error=" . $error;
  190.                 }
  191.                 return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
  192.        
  193.                 <noscript>
  194.                         <iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
  195.                                 <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
  196.                                 <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
  197.                         <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
  198.                 </noscript>';
  199.         }
  200.  
  201.         /* Mailhide related code */
  202.         function _recaptcha_aes_encrypt($val,$ky) {
  203.                 if (! function_exists ("mcrypt_encrypt")) {
  204.                         die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
  205.                 }
  206.                 $mode=MCRYPT_MODE_CBC;  
  207.                 $enc=MCRYPT_RIJNDAEL_128;
  208.                 $val=$this->_recaptcha_aes_pad($val);
  209.                 return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  210.         }
  211.        
  212.         function _recaptcha_mailhide_urlbase64 ($x) {
  213.                 return strtr(base64_encode ($x), '+/', '-_');
  214.         }
  215.        
  216.         /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
  217.         function recaptcha_mailhide_url($pubkey, $privkey, $email) {
  218.                 if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
  219.                         die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
  220.                              "you can do so at <a href='http://mailhide.recaptcha.net/apikey'>http://mailhide.recaptcha.net/apikey</a>");
  221.                 }
  222.                
  223.        
  224.                 $ky = pack('H*', $privkey);
  225.                 $cryptmail = $this->_recaptcha_aes_encrypt ($email, $ky);
  226.                
  227.                 return "http://mailhide.recaptcha.net/d?k=" . $pubkey . "&c=" . $this->_recaptcha_mailhide_urlbase64 ($cryptmail);
  228.         }
  229.        
  230.         /**
  231.          * gets the parts of the email to expose to the user.
  232.          * eg, given johndoe@example,com return ["john", "example.com"].
  233.          * the email is then displayed as [email protected]
  234.          */
  235.         function _recaptcha_mailhide_email_parts ($email) {
  236.                 $arr = preg_split("/@/", $email );
  237.        
  238.                 if (strlen ($arr[0]) <= 4) {
  239.                         $arr[0] = substr ($arr[0], 0, 1);
  240.                 } else if (strlen ($arr[0]) <= 6) {
  241.                         $arr[0] = substr ($arr[0], 0, 3);
  242.                 } else {
  243.                         $arr[0] = substr ($arr[0], 0, 4);
  244.                 }
  245.                 return $arr;
  246.         }
  247.        
  248.         /**
  249.          * Gets html to display an email address given a public an private key.
  250.          * to get a key, go to:
  251.          *
  252.          * http://mailhide.recaptcha.net/apikey
  253.          */
  254.         function recaptcha_mailhide_html($pubkey, $privkey, $email) {
  255.                 $emailparts = $this->_recaptcha_mailhide_email_parts ($email);
  256.                 $url = $this->recaptcha_mailhide_url ($pubkey, $privkey, $email);
  257.                
  258.                 return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
  259.                         "' 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]);
  260.        
  261.         }
  262.                
  263.  
  264. }
  265. /*
  266.  
  267. To use the reCAPTCHA system load the helper & component
  268. */
  269. var $components = array('Recaptcha');
  270. var $helpers = array('Recaptcha');
  271. /*
  272.  
  273. After you save the component and helper and initiate them, set your public & private keys in "beforeFilter" of your controller to the ones you received when you signed up on the reCAPTCHA website.
  274.  
  275. */
  276. function beforeFilter(){
  277.    $this->Recaptcha->publickey = "";
  278.    $this->Recaptcha->privatekey = "";
  279. }
  280. /*
  281.  
  282. in the view, the helper can be used to verify form submissions or hide your e-mail addresses (NOTE: mcrypt is [b]required[/b] for this.)
  283. */
  284. //create the reCAPTCHA form.
  285.  $recaptcha->display_form('echo')
  286.  
  287. //hide an e-mail address
  288.  $recaptcha->hide_mail("[email protected]",'echo');
  289. /*
  290.  
  291.  
  292. in the controller to verify a form submission using reCAPTCHA do the following.
  293. */
  294. if($this->Recaptcha->valid($this->params['form']))
  295.   //submission is valid!
  296. else
  297.   //invalid reCAPTCHA entry.
  298. /*
  299.  
  300. I hope you enjoy it, this is the first component / helper (let alone helper) pair I've written.