PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/recaptcha-plugins/perl/Captcha-reCAPTCHA/trunk/lib/Captcha/reCAPTCHA.pm

http://recaptcha.googlecode.com/
Perl | 400 lines | 317 code | 78 blank | 5 comment | 16 complexity | de0958c300e0bb0a41f806444260f487 MD5 | raw file
  1. package Captcha::reCAPTCHA;
  2. use warnings;
  3. use strict;
  4. use Carp;
  5. use LWP::UserAgent;
  6. use HTML::Tiny;
  7. our $VERSION = '0.94';
  8. use constant API_SERVER => 'http://www.google.com/recaptcha/api';
  9. use constant API_SECURE_SERVER =>
  10. 'https://www.google.com/recaptcha/api';
  11. use constant API_VERIFY_SERVER => 'http://www.google.com';
  12. use constant SERVER_ERROR => 'recaptcha-not-reachable';
  13. sub new {
  14. my $class = shift;
  15. my $self = bless {}, $class;
  16. $self->_initialize( @_ );
  17. return $self;
  18. }
  19. sub _initialize {
  20. my $self = shift;
  21. my $args = shift || {};
  22. croak "new must be called with a reference to a hash of parameters"
  23. unless 'HASH' eq ref $args;
  24. }
  25. sub _html { shift->{_html} ||= HTML::Tiny->new }
  26. sub get_options_setter {
  27. my $self = shift;
  28. my $options = shift || return '';
  29. croak "The argument to get_options_setter must be a hashref"
  30. unless 'HASH' eq ref $options;
  31. my $h = $self->_html;
  32. return $h->script(
  33. { type => 'text/javascript' },
  34. "\n//<![CDATA[\n"
  35. . "var RecaptchaOptions = "
  36. . $h->json_encode( $options )
  37. . ";\n//]]>\n"
  38. ) . "\n";
  39. }
  40. sub get_html {
  41. my $self = shift;
  42. my ( $pubkey, $error, $use_ssl, $options ) = @_;
  43. croak
  44. "To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create"
  45. unless $pubkey;
  46. my $h = $self->_html;
  47. my $server = $use_ssl ? API_SECURE_SERVER : API_SERVER;
  48. my $query = { k => $pubkey };
  49. if ( $error ) {
  50. # Handle the case where the result hash from check_answer
  51. # is passed.
  52. if ( 'HASH' eq ref $error ) {
  53. return '' if $error->{is_valid};
  54. $error = $error->{error};
  55. }
  56. $query->{error} = $error;
  57. }
  58. my $qs = $h->query_encode( $query );
  59. return join(
  60. '',
  61. $self->get_options_setter( $options ),
  62. $h->script(
  63. {
  64. type => 'text/javascript',
  65. src => "$server/challenge?$qs",
  66. }
  67. ),
  68. "\n",
  69. $h->noscript(
  70. [
  71. $h->iframe(
  72. {
  73. src => "$server/noscript?$qs",
  74. height => 300,
  75. width => 500,
  76. frameborder => 0
  77. }
  78. ),
  79. $h->textarea(
  80. {
  81. name => 'recaptcha_challenge_field',
  82. rows => 3,
  83. cols => 40
  84. }
  85. ),
  86. $h->input(
  87. {
  88. type => 'hidden',
  89. name => 'recaptcha_response_field',
  90. value => 'manual_challenge'
  91. }
  92. )
  93. ]
  94. ),
  95. "\n"
  96. );
  97. }
  98. sub _post_request {
  99. my $self = shift;
  100. my ( $url, $args ) = @_;
  101. my $ua = LWP::UserAgent->new();
  102. $ua->env_proxy();
  103. return $ua->post( $url, $args );
  104. }
  105. sub check_answer {
  106. my $self = shift;
  107. my ( $privkey, $remoteip, $challenge, $response ) = @_;
  108. croak
  109. "To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create"
  110. unless $privkey;
  111. croak "For security reasons, you must pass the remote ip to reCAPTCHA"
  112. unless $remoteip;
  113. return { is_valid => 0, error => 'incorrect-captcha-sol' }
  114. unless $challenge && $response;
  115. my $resp = $self->_post_request(
  116. API_VERIFY_SERVER . '/recaptcha/api/verify',
  117. {
  118. privatekey => $privkey,
  119. remoteip => $remoteip,
  120. challenge => $challenge,
  121. response => $response
  122. }
  123. );
  124. if ( $resp->is_success ) {
  125. my ( $answer, $message ) = split( /\n/, $resp->content, 2 );
  126. if ( $answer =~ /true/ ) {
  127. return { is_valid => 1 };
  128. }
  129. else {
  130. chomp $message;
  131. return { is_valid => 0, error => $message };
  132. }
  133. }
  134. else {
  135. return { is_valid => 0, error => SERVER_ERROR };
  136. }
  137. }
  138. 1;
  139. __END__
  140. =head1 NAME
  141. Captcha::reCAPTCHA - A Perl implementation of the reCAPTCHA API
  142. =head1 VERSION
  143. This document describes Captcha::reCAPTCHA version 0.94
  144. =head1 SYNOPSIS
  145. use Captcha::reCAPTCHA;
  146. my $c = Captcha::reCAPTCHA->new;
  147. # Output form
  148. print $c->get_html( 'your public key here' );
  149. # Verify submission
  150. my $result = $c->check_answer(
  151. 'your private key here', $ENV{'REMOTE_ADDR'},
  152. $challenge, $response
  153. );
  154. if ( $result->{is_valid} ) {
  155. print "Yes!";
  156. }
  157. else {
  158. # Error
  159. $error = $result->{error};
  160. }
  161. For complete examples see the /examples subdirectory
  162. =head1 DESCRIPTION
  163. reCAPTCHA is a hybrid mechanical turk and captcha that allows visitors
  164. who complete the captcha to assist in the digitization of books.
  165. From L<http://recaptcha.net/learnmore.html>:
  166. reCAPTCHA improves the process of digitizing books by sending words that
  167. cannot be read by computers to the Web in the form of CAPTCHAs for
  168. humans to decipher. More specifically, each word that cannot be read
  169. correctly by OCR is placed on an image and used as a CAPTCHA. This is
  170. possible because most OCR programs alert you when a word cannot be read
  171. correctly.
  172. This Perl implementation is modelled on the PHP interface that can be
  173. found here:
  174. L<http://recaptcha.net/plugins/php/>
  175. To use reCAPTCHA you need to register your site here:
  176. L<https://www.google.com/recaptcha/admin/create>
  177. =head1 INTERFACE
  178. =over
  179. =item C<< new >>
  180. Create a new C<< Captcha::reCAPTCHA >>.
  181. =item C<< get_html( $pubkey, $error, $use_ssl, $options ) >>
  182. Generates HTML to display the captcha.
  183. print $captcha->get_html( $PUB, $err );
  184. =over
  185. =item C<< $pubkey >>
  186. Your reCAPTCHA public key, from the API Signup Page
  187. =item C<< $error >>
  188. Optional. If set this should be either a string containing a reCAPTCHA
  189. status code or a result hash as returned by C<< check_answer >>.
  190. =item C<< $use_ssl >>
  191. Optional. Should the SSL-based API be used? If you are displaying a page
  192. to the user over SSL, be sure to set this to true so an error dialog
  193. doesn't come up in the user's browser.
  194. =item C<< $options >>
  195. Optional. A reference to a hash of options for the captcha. See
  196. C<< get_options_setter >> for more details.
  197. =back
  198. Returns a string containing the HTML that should be used to display
  199. the captcha.
  200. =item C<< get_options_setter( $options ) >>
  201. You can optionally customize the look of the reCAPTCHA widget with some
  202. JavaScript settings. C<get_options_setter> returns a block of Javascript
  203. wrapped in <script> .. </script> tags that will set the options to be used
  204. by the widget.
  205. C<$options> is a reference to a hash that may contain the following keys:
  206. =over
  207. =item C<theme>
  208. Defines which theme to use for reCAPTCHA. Possible values are 'red',
  209. 'white' or 'blackglass'. The default is 'red'.
  210. =item C<tabindex>
  211. Sets a tabindex for the reCAPTCHA text box. If other elements in the
  212. form use a tabindex, this should be set so that navigation is easier for
  213. the user. Default: 0.
  214. =back
  215. =item C<< check_answer >>
  216. After the user has filled out the HTML form, including their answer for
  217. the CAPTCHA, use C<< check_answer >> to check their answer when they
  218. submit the form. The user's answer will be in two form fields,
  219. recaptcha_challenge_field and recaptcha_response_field. The reCAPTCHA
  220. library will make an HTTP request to the reCAPTCHA server and verify the
  221. user's answer.
  222. =over
  223. =item C<< $privkey >>
  224. Your reCAPTCHA private key, from the API Signup Page.
  225. =item C<< $remoteip >>
  226. The user's IP address, in the format 192.168.0.1.
  227. =item C<< $challenge >>
  228. The value of the form field recaptcha_challenge_field
  229. =item C<< $response >>
  230. The value of the form field recaptcha_response_field.
  231. =back
  232. Returns a reference to a hash containing two fields: C<is_valid>
  233. and C<error>.
  234. my $result = $c->check_answer(
  235. 'your private key here', $ENV{'REMOTE_ADDR'},
  236. $challenge, $response
  237. );
  238. if ( $result->{is_valid} ) {
  239. print "Yes!";
  240. }
  241. else {
  242. # Error
  243. $error = $result->{error};
  244. }
  245. See the /examples subdirectory for examples of how to call C<check_answer>.
  246. Note: this method will make an HTTP request to Google to verify the user input.
  247. If this request must be routed via a proxy in your environment, use the
  248. standard environment variable to specify the proxy address, e.g.:
  249. $ENV{http_proxy} = 'http://myproxy:3128';
  250. =back
  251. =head1 CONFIGURATION AND ENVIRONMENT
  252. Captcha::reCAPTCHA requires no configuration files or environment
  253. variables.
  254. To use reCAPTCHA sign up for a key pair here:
  255. L<https://www.google.com/recaptcha/admin/create>
  256. =head1 DEPENDENCIES
  257. LWP::UserAgent,
  258. HTML::Tiny
  259. =head1 INCOMPATIBILITIES
  260. None reported .
  261. =head1 BUGS AND LIMITATIONS
  262. No bugs have been reported.
  263. Please report any bugs or feature requests to
  264. C<bug-captcha-recaptcha@rt.cpan.org>, or through the web interface at
  265. L<http://rt.cpan.org>.
  266. =head1 AUTHOR
  267. Andy Armstrong C<< <andy@hexten.net> >>
  268. =head1 LICENCE AND COPYRIGHT
  269. Copyright (c) 2007, Andy Armstrong C<< <andy@hexten.net> >>. All rights reserved.
  270. This module is free software; you can redistribute it and/or
  271. modify it under the same terms as Perl itself. See L<perlartistic>.
  272. =head1 DISCLAIMER OF WARRANTY
  273. BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  274. FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
  275. OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  276. PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
  277. EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  278. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
  279. ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
  280. YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
  281. NECESSARY SERVICING, REPAIR, OR CORRECTION.
  282. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  283. WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  284. REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
  285. LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
  286. OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
  287. THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
  288. RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
  289. FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
  290. SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
  291. SUCH DAMAGES.