+## the following is mod_perl specific
+
+BEGIN{
+ if (exists $ENV{MOD_PERL_API_VERSION}) {
+ if ($ENV{MOD_PERL_API_VERSION} == 2) {
+ require Apache2::RequestIO;
+ require Apache2::RequestRec;
+ require Apache2::RequestUtil;
+ require Apache2::Const;
+ require APR::Finfo;
+ require APR::Const;
+ APR::Const->import(-compile => qw(FINFO_NORM));
+ Apache2::Const->import(-compile => qw(OK DECLINED FORBIDDEN NOT_FOUND HTTP_NOT_MODIFIED));
+ } else {
+ die "Unsupported mod perl api; mod_perl 2.0.0 or later is required";
+ }
+ }
+}
+
+sub handler {
+ die "Calling handler only makes sense if this is running under mod_perl" unless exists $ENV{MOD_PERL_API_VERSION};
+ my $r = shift or Apache2::RequestUtil->request;
+
+ # we only want GET or HEAD requests
+ unless ($r->method eq 'HEAD' or $r->method eq 'GET') {
+ return Apache2::Const::DECLINED();
+ }
+ $r->headers_out->{"X-Powered-By"} = "Debbugs libravatar";
+
+ my $uri = $r->uri();
+ # subtract out location
+ my $location = $r->location();
+ my ($email) = $uri =~ m/\Q$location\E\/?(.*)$/;
+ if (not length $email) {
+ return Apache2::Const::NOT_FOUND;
+ }
+ my $q = CGI::Simple->new();
+ my %param = cgi_parameters(query => $q,
+ single => [qw(avatar)],
+ default => {avatar => 'yes',
+ },
+ );
+ if ($param{avatar} ne 'yes' or not defined $email or not length $email) {
+ serve_cache_mod_perl('',$r);
+ return Apache2::Const::DECLINED();
+ }
+ # figure out what the md5sum of the e-mail is.
+ my $cache_location = cache_location(email => $email);
+ # if we've got it, and it's less than one hour old, return it.
+ if (cache_valid($cache_location)) {
+ serve_cache_mod_perl($cache_location,$r);
+ return Apache2::Const::DECLINED();
+ }
+ $cache_location = retreive_libravatar(location => $cache_location,
+ email => $email,
+ );
+ if (not defined $cache_location) {
+ # failure, serve the default image
+ serve_cache_mod_perl('',$r);
+ return Apache2::Const::DECLINED();
+ } else {
+ serve_cache_mod_perl($cache_location,$r);
+ return Apache2::Const::DECLINED();
+ }
+}
+
+
+sub serve_cache_mod_perl {
+ my ($cache_location,$r) = @_;
+ if (not defined $cache_location or not length $cache_location) {
+ # serve the default image
+ $cache_location = $config{libravatar_default_image};
+ }
+ $r->filename($cache_location);
+ $r->path_info('');
+ $r->finfo(APR::Finfo::stat($cache_location, APR::Const::FINFO_NORM, $r->pool));
+}