Recaptcha for Gallery Comments - Spam Protection from Spam Bots Recaptcha for Gallery Comments - Spam Protection from Spam Bots
 

News:

cpg1.5.48 Security release - upgrade mandatory!
The Coppermine development team is releasing a security update for Coppermine in order to counter a recently discovered vulnerability. It is important that all users who run version cpg1.5.46 or older update to this latest version as soon as possible.
[more]

Main Menu

Recaptcha for Gallery Comments - Spam Protection from Spam Bots

Started by Joe Carver, March 27, 2009, 05:14:49 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Joe Carver

See Reply #10 below for latest Revision
For Plugin version click here

Here is a way to integrate Recaptcha to protect Comments from spammers.
Two files: theme.php and db_input.php get a javascript and php snippet. Another
file for error handling is added to the cpg root.

It is now live on my user's gallery and personal gallery :  i-imagine.net and gallery.josephcarver.com/natural
(ver 1.4.2 patched)  

I have tested it with a few browsers and without js and so far so good.
Feedback is welcome. Please leave messages and/or test the mods as you like.

The mods and a readme is attached. I don't really don't know code that much
at all so supporting this might be difficult. I can try to share any experience though.

So far the recaptcha had worked ok for my contact forms but the spammers were
registering on the public site just to get past the user restrictions and it was getting old fast.
Hopefully this can help others - Coppermine is great and this is the little that I've got to give.

i-imagine

p.s. I'd like to know if the error handling can be done more elegantly.....
and it's on my personal site too: gallery.josephcarver.com  

Joe Carver

Hi Again,

Small changes attached in .zip here, hopefully for the better

1) Captcha error response has been changed to a cpg gallery page.

2) readme is more clear regarding required files/keys from recaptcha.net


Now running at a public/users gallery: i-imagine.net/artists

and my photo site: gallery.josephcarver.com/natural/

i-imagine


Joe Carver

Corrections here. First instruction above can break/interfere with other db_input.php functions. (fault found with album update)
Demonstration here  http://gallery.josephcarver.com/natural/index.php. You will need the keys and file recaptchalib.php from recaptcha.net. Note: there is minimal style formatting as instructed here - customizing is recommended.

Quoteedit db_input.php find $replacements[] = $word;
       }
    }
    $str=str_replace($replacements,'(...)',$str);
}
Quoteand insert after it if (!(GALLERY_ADMIN_MODE)) {

require_once('recaptchalib.php');   
$privatekey = "YOUR PRIVATE KEY FROM RECAPTCHA.NET IN HERE";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
die(header('Location: captcha_errmssg.php'));
}
}
Quoteedit theme.php find<!-- END input_box_no_smilies -->
Quoteand insert after it <tr><td align="center" colspan="3">
<script>
var RecaptchaOptions = {
theme : 'white'
};
</script>

<script type="text/javascript"
    src="http://api.recaptcha.net/challenge?k=<YOUR PUBLIC RECAPTCHA KEY HERE>">
</script>

<noscript><iframe src="http://api.recaptcha.net/noscript?k=<YOUR PUBLIC RECAPTCHA KEY HERE>"
      height="300" width="500" frameborder="0"></iframe><br>
    <textarea name="recaptcha_challenge_field" rows="3" cols="40">
  </textarea>
    <input type="hidden" name="recaptcha_response_field" value="manual_challenge"></noscript>
</td>
Create a file named captcha_errmssg.php for error handling
Quote<?php
define
('IN_COPPERMINE'true);
require(
'include/init.inc.php');
pageheader('CAPTCHA ERROR - COMMENTS INPUT');
    
starttable("100%");
    
?>

    <tr>
    <h1 align="center">
<a href="#" onclick="history.go(-1);return false;"><font color= "red">
SORRY, THERE WAS AN ERROR WITH THE CAPTCHA. </br>CLICK HERE AND TRY AGAIN.</br></br>
(OR USE THE BACK BUTTON ON YOUR BROWSER)</font></a>
</h1>
     </tr>
    <?php
    endtable
();
//  ends here
pagefooter();
ob_end_flush();
?>
Upload the files captcha_errmssg.php , recaptchalib.php and the modified db_input.php to your Coppermine Gallery root. Upload/replace your theme(s) into your theme directory. Your gallery comments are now protected from spambots.
Notes: "GALLERY_ADMIN_MODE" users will see the comments captcha, but will not need it. The captcha table/style images load from a remote server in this example. Local/custom images from your server are style options. You can test the remote server speed in your area by clicking the "Get a new challenge" icon. Apologies for any trouble caused by the previous post. See my other posts about recaptcha for registration and ecards. i-imagine

Joe Carver

This mod. version uses AJAX to load the captcha widget. With IE(7) there were "issues" conflicting with the excellent LightBox Slideshow plugin leading to the browser getting lost when it encountered the js mod.  This happened only with IE not Opera or FF.
This captcha recaptcha mod for Comments is now running here at: gallery.josephcarver.com/natural/

As above you will need a set of  keys and a file recaptchalib.php fom recaptcha.net (they are free). Files template.html, theme.php and db_input.php are modified and you create an error response file for this mod. Like my other recaptcha mods. this will not affect your gallery database or configuration. To uninstall - replace these mod. files with clean copies.

The captcha is hidden until called for in this style. Use your own styles as needed. The instructions are based on the Sample Theme and db_input.php included in cpg1.4.21. This will interfere with edit comment and has not been tested with smilies. Comment delete seems to work ok.

Quotein your template.html file insert this into the <head> <script type="text/javascript" src="http://api.recaptcha.net/js/recaptcha_ajax.js"></script>
Quotefind this in your theme.php file                           <td class="tableb_compact">
                                <input type="hidden" name="event" value="comment" />
                                <input type="hidden" name="pid" value="{PIC_ID}" />
                                <input type="submit" class="comment_button" name="submit" value="{OK}" />
                                </td>
Quotereplace it with this - add your public recaptcha key where shown
<td class="tableb_compact" align ="center" valign= "top" colspan="3">
<div></div>
<script>
function showRecaptcha(element, submitButton, themeName) {
  Recaptcha.create("YOUR PUBLIC RECAPTCHA KEY HERE", element, {
        theme: 'white',
        tabindex: 0,
        callback: Recaptcha.focus_response_field
  });
  hideSubmitButtons();
  document.getElementById(submitButton).style.visibility = "visible";
}

function hideSubmitButtons() {
  document.getElementById('submit_button_1').style.visibility = "hidden";
  }

function destroyRecaptchaWidget() {
  hideSubmitButtons();
  Recaptcha.destroy();
}
</script>
<form method="post" action="">
<p>
<input type="button" class="comment_button"  value="Click here - type the words - click submit"

onclick="showRecaptcha('dynamic_recaptcha_1', 'submit_button_1', 'red');"></input>
<div id="dynamic_recaptcha_1"></div>

                                <input type="hidden" name="event" value="comment" />
                                <input type="hidden" name="pid" value="{PIC_ID}" />
<input type="submit" value="Submit" style="visibility: hidden"

id="submit_button_1"class="comment_button" name="submit" value="Submit Comment" /></input>
<div></div>
</td>
</table>
</tr>
<tr>
<td class="tableb_compact" align ="center" colspan="3">

<input type="button" class="comment_button" value="Hide the reCAPTCHA widget"

onclick="destroyRecaptchaWidget();"></input>
</td>
<td class="tableb_compact"></td>
Quotein your db_input.php file find this $replacements[] = $word;
       }
    }
    $str=str_replace($replacements,'(...)',$str);
}
Quoteadd this below it, insert your private recaptcha key where shownif (!(GALLERY_ADMIN_MODE)) {

require_once('recaptchalib.php');   
$privatekey = "YOUR PRIVATE KEY FROM RECAPTCHA.NET IN HERE";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
die(header('Location: captcha_errmssg.php'));
}
}
Quotecreate a file with this, name captcha_errmssg.php<?php
define
('IN_COPPERMINE'true);
require(
'include/init.inc.php');
pageheader('CAPTCHA ERROR - COMMENTS INPUT');
    
starttable("100%");
    
?>

    <tr>
    <h1 align="center">
<a href="#" onclick="history.go(-1);return false;"><font color= "red">
SORRY, THERE WAS AN ERROR WITH THE CAPTCHA. </br>CLICK HERE AND TRY AGAIN.</br></br>
(OR USE THE BACK BUTTON ON YOUR BROWSER)</font></a>
</h1>
     </tr>
    <?php
    endtable
();
//  ends here
pagefooter();
ob_end_flush();
?>

Upload  files recaptchalib.php and captcha_errmssg.php to your gallery root directory. Upload the modded files to their respective origins. (a similar mod. using AJAX to load the captcha is now running at i-imagine.net and gallery.josephcarver.com/natural/ on the registration page (more to come))
Enjoy!

Zeroshade

Awesome feature, I really love it ... However, while having your Recaptcha feature integrated, users are unable to send data that they've typed in fields, such as editing their profile, updating their album etc, anywhere where a text field appear really. This is due to recaptcha monitoring all data send through the site, sure you could add recaptcha everywhere but who would want such annoying security where it's not needed.

Any suggestions to a quick fix?

Zeroshade

Correction, did a re-test, this error only happens when a user tries to update their personal galleries, such as typing in a description or adding a password.

Joe Carver

Try this. It seems to be working ok for my user's gallery.
The captcha will be ignored if the user is logged in.

QuoteFind this line in the mod. codeif (!(GALLERY_ADMIN_MODE)) {

QuoteReplace it with this if  (!(USER_ID)) {

This mod. affects only data being sent through db_input.php. You should have been able to create new accounts, etc. even with this mod. running.
Thanks for the feedback. I hope this works for you. And thanks for reminding me to write up another reply to this post. I now have a "cleaner" error response for the mod.
What is your gallery address? It would be nice to see this mod. somewhere else other than my (bot free) site.  :)

Zeroshade

Thanks, I'll be sure to try out the changes. My gallery is somewhat localhost bound for now, seeing as it still need alot of work.

Zeroshade

Quote from: Zeroshade on May 11, 2009, 07:26:44 PM
Thanks, I'll be sure to try out the changes. My gallery is somewhat localhost bound for now, seeing as it still need alot of work.

It works now but I don't like the changes, I would really like to protect any comments made even by users while still retaining the normal functionality of cpg.

Joe Carver

Wow, your users sound like trouble!  ;D Are you using any captcha to screen the registration also?
Anyway, try this. A quick test looks OK, your results will be interesting to know.

Start with a clean copy of db_input.php. Or just remove the mods. you have already made.

QuoteIn file db_input.php find this linecase 'comment':
        if (!(USER_CAN_POST_COMMENTS)) cpg_die(ERROR, $lang_errors['perm_denied'], __FILE__, __LINE__);

QuoteInsert below it require_once('recaptchalib.php'); 
$privatekey = "YOUR PRIVATE RECAPTCHA KEY IN HERE";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
cpg_die(ERROR, 'Sorry, Captcha Error - Go Back and Try Again');
}

Keep in mind that the captcha will now apply to all users, including you as the admin. There are probably simple ways to address that, however for the moment I'm staying with the original, mainly becauses it has adds a layer to db_input.php that I happen to like. Good Luck!

Joe Carver

Add a Recaptcha to Comments
AJAX method is used here to display a visual challenge - ReCAPTCHA - for users trying to post comments. This will not affect comment edit and delete and does not appear to interfere with other mods/plugins/scripts on my galleries. The mod. will only affect the comment input function of db_input.php

To use ReCAPTCHA you need you need a public/private API key pair from recaptcha.net [it is a free service]. To see how this works check this link  http://recaptcha.net/apidocs/captcha/client.html . Error handling is done by Coppermine's cpg_die function.

    1) Register your domains and get keys + file from  recaptcha.net
    • Public and Private Keys inserted as below
    • file  recaptchalib.php     copy to your gallery root directory

      2) Modify these files
      • template.html (for all themes you use)
      • theme.php (for all the themes you use)
      • db_input.php
      To uninstall this mod. replace the mod. files with clean backups. These instructions/code references were done on the Sample Theme.

      QuoteInsert this into the <head> of your template(s).html<script type="text/javascript"
      src="http://api.recaptcha.net/js/recaptcha_ajax.js"></script>

      QuoteFind this in your theme(s),php<td class="tableb_compact">
                                     <input type="hidden" name="event" value="comment" />
                                     <input type="hidden" name="pid" value="{PIC_ID}" />
                                     <input type="submit" class="comment_button" name="submit" value="{OK}" />
                                     </td>
                                                             </tr>
                             </table>
                     </td>
             </tr>

      QuoteReplace it with this - insert your PUBLIC key where shown<tr>
      <table  align="center" colspan="3" valign= "top"><tr>

                                     <td class="tableb_compact" align ="center" valign= "top" colspan="3">

      <div></div>
      <script>
      function showRecaptcha(element, submitButton, themeName) {
       Recaptcha.create("YOUR PUBLIC KEY HERE", element, {
             theme: 'white',
             tabindex: 0,
             callback: Recaptcha.focus_response_field
       });
       hideSubmitButtons();
       document.getElementById(submitButton).style.visibility = "visible";
      }

      function hideSubmitButtons() {
       document.getElementById('submit_button_1').style.visibility = "hidden";
       
      }

      function destroyRecaptchaWidget() {
       hideSubmitButtons();
       Recaptcha.destroy();
      }

      </script>

      <form method="post" action="">

      <p>
      <input type="button" class="comment_button"  value="Click here - type the words - click submit" onclick="showRecaptcha('dynamic_recaptcha_1', 'submit_button_1', 'red');"></input>
      <div id="dynamic_recaptcha_1"></div>


                                     <input type="hidden" name="event" value="comment" />
                                     <input type="hidden" name="pid" value="{PIC_ID}" />
      <input type="submit" value="Submit" style="visibility: hidden" id="submit_button_1"class="comment_button" name="submit" value="Submit Comment" /></input>

      <div></div>
                                     </td>
      </table>                                                      </tr>
                              <tr>
                                    <td class="tableb_compact" align ="center" colspan="3">

      <input type="button" class="comment_button" value="Hide the reCAPTCHA widget" onclick="destroyRecaptchaWidget();"></input>
      </td>
      </tr>
      <tr>
      <td class="tableb_compact" align="center">

      <noscript><h3 align="center"><br> Hello Visitor
      <br>Your browser has no javascript.<br> You cannot make a comment without javascript<br><br></h3>
      </noscript>
      </td>
        </tr>

      QuoteIn your db_input.php file find thiscase 'comment':
             if (!(USER_CAN_POST_COMMENTS)) cpg_die(ERROR, $lang_errors['perm_denied'], __FILE__, __LINE__);

      QuoteAdd below it this add your PRIVATE key where shown require_once('recaptchalib.php');  
      $privatekey = "YOUR PRIVATE KEY HERE";
      $resp = recaptcha_check_answer ($privatekey,
      $_SERVER["REMOTE_ADDR"],
      $_POST["recaptcha_challenge_field"],
      $_POST["recaptcha_response_field"]);
      if (!$resp->is_valid) {
      cpg_die(ERROR, 'Sorry, Captcha Error - Go Back and Try Again');
      }
        Upload and you are done. This adds a hidden captcha that is opened when the user clicks a button. Other styles can be applied

        For testing and other options....

          Testing
          • use the sample scripts at http://recaptcha.net/plugins/php/ to test your key validation
          • Try it on a separate or duplicate theme first(with a name your users won't click)

            User Options
            • Option 1 - logged in user is not required to solve captcha
            • Option 2 - Gallery Admin is not required to use the captcha

            QuoteOption 1 db_input.php code[/list][/list] if (!USER_ID){
            require_once('recaptchalib.php');  
            $privatekey = "YOUR PRIVATE RECAPTCHA KEY HERE";
            $resp = recaptcha_check_answer ($privatekey,
            $_SERVER["REMOTE_ADDR"],
            $_POST["recaptcha_challenge_field"],
            $_POST["recaptcha_response_field"]);
            if (!$resp->is_valid) {
            cpg_die(ERROR, 'Sorry, Captcha Error - Go Back and Try Again');
            }
            }

            QuoteOption 2 db_input.php code if (!(GALLERY_ADMIN_MODE)){
            require_once('recaptchalib.php');  
            $privatekey = "YOUR PRIVATE KEY HERE";
            $resp = recaptcha_check_answer ($privatekey,
            $_SERVER["REMOTE_ADDR"],
            $_POST["recaptcha_challenge_field"],
            $_POST["recaptcha_response_field"]);
            if (!$resp->is_valid) {
            cpg_die(ERROR, 'Sorry, Captcha Error - Go Back and Try Again');
            }
            }
              The user or admin will see the captcha but can just submit the comment without solving the captcha if the option is used.

              The mod. is installed here: gallery.josephcarver.com/natural/
              To give the users a "go back" while preserving the form data, see this thread here

              Note: Sample theme.php was used for this example. Your theme might be different and not have the comment form built in. If that is the case you can use the attached text file with the comment form and the recaptcha - add your public key where shown and insert the form into your theme.php.
              When you upgrade Coppermine you will/should have to modify your new db_input.php only.


              Apologies for these typos....[/list][/list].......seems to be a "sticky feature" for me
              For Plugin version click here

              Criss

              Hi!

              I've tried your hack, installed it but I don't see any changes in comments field:
              http://i40.tinypic.com/2zin4ma.jpg

              The only change I noticed is that after sumbitting any comment I receive th following message:
              http://i43.tinypic.com/9gvy4g.jpg

              I'm using CPG 1.4.23

              Please help!

              Joe Carver

              #12
              It looks like you have the db_input.php part done OK, but without bring able to actually see your gallery and/or page source I can only guess. But with that said....
              try checking.
              • The template.html has in the <head> section the code/line to load the captcha .
              • Try turning off ratings for a test. I have seen issues with those, but the captcha is still visible
              • Test your domain's interaction with recaptcha.net with their "hello world" test script  here
              • Use the Firefox error console -  check the message output
              • Double check your Public key
              • Post a link to your gallery

              Criss

              Thanks for getting back to me. I did everything you said but still can't get it to work. Link to the gallery:

              http://www.jcgallery.org
              user: test
              pass: test

              Joe Carver

              I did not see any captcha code below
              <!-- END input_box_smilies -->

              Which means that the theme.php file did not get the edits/mods.

              The file theme.php in your directory      themes/apr/  (or whatever the theme is named) is the one that still needs modification.
              QuoteThis is what needs to be replaced, as above in Reply #10<td class="tableb_compact">
                                             <input type="hidden" name="event" value="comment" />
                                             <input type="hidden" name="pid" value="28953" />
                                             <input type="submit" class="comment_button" name="submit" value="OK" />
                                             </td>

                                                                     </tr>
                                     </table>
                             </td>
                     </tr>

              Or perhaps you have modded another theme?


              Criss

              I have created a brand new theme.php file, added the code and it works great now! I guess it was messed up. Thank you for your help!  :D